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
|
---|---|---|---|---|---|---|---|---|---|
19897554ce9735aa821279efae12750e8036f8e2
|
lualib/http/client.lua
|
lualib/http/client.lua
|
local socket = require "socket"
local ssl = require "ssl"
local stream = require "http.stream"
local dns = require "dns"
local client = {}
local EMPTY = {}
local function parseurl(url)
local default = false
local scheme, host, port, path= string.match(url, "(http[s]-)://([^:/]+):?(%d*)([%w-%.?&=_/]*)")
if path == "" then
path = "/"
end
if port == "" then
if scheme == "https" then
port = "443"
elseif scheme == "http" then
port = "80"
else
assert(false, "unsupport parse url scheme:" .. scheme)
end
default = true
end
return scheme, host, port, path, default
end
local function send_request(io_do, fd, method, host, abs, header, body)
local tmp = ""
table.insert(header, 1, string.format("%s %s HTTP/1.1", method, abs))
table.insert(header, string.format("Host: %s", host))
table.insert(header, string.format("Content-Length: %d", #body))
table.insert(header, "User-Agent: Silly/0.2")
table.insert(header, "Connection: keep-alive")
table.insert(header, "\r\n")
tmp = table.concat(header, "\r\n")
tmp = tmp .. body
io_do.write(fd, tmp)
end
local function recv_response(io_do, fd)
local readl = function()
return io_do.readline(fd, "\r\n")
end
local readn = function(n)
return io_do.read(fd, n)
end
local status, first, header, body = stream.recv_request(readl, readn)
if not status then --disconnected
return nil
end
if status ~= 200 then
return status
end
local ver, status= first:match("HTTP/([%d|.]+)%s+(%d+)")
return tonumber(status), header, body, ver
end
local function process(uri, method, header, body)
local ip, io_do
local scheme, host, port, path, default = parseurl(uri)
if dns.isdomain(host) then
ip = dns.query(host)
else
ip = host
end
if scheme == "https" then
io_do = ssl
elseif scheme == "http" then
io_do = socket
end
if not default then
host = string.format("%s:%s", host, port)
end
ip = string.format("%s@%s", ip, port)
local fd = io_do.connect(ip)
if not fd then
return 599
end
header = header or EMPTY
body = body or ""
send_request(io_do, fd, method, host, path, header, body)
local status, header, body, ver = recv_response(io_do, fd)
io_do.close(fd)
return status, header, body, ver
end
function client.GET(uri, header)
return process(uri, "GET", header)
end
function client.POST(uri, header, body)
return process(uri, "POST", header, body)
end
return client
|
local socket = require "socket"
local ssl = require "ssl"
local stream = require "http.stream"
local dns = require "dns"
local client = {}
local function parseurl(url)
local default = false
local scheme, host, port, path= string.match(url, "(http[s]-)://([^:/]+):?(%d*)([%w-%.?&=_/]*)")
if path == "" then
path = "/"
end
if port == "" then
if scheme == "https" then
port = "443"
elseif scheme == "http" then
port = "80"
else
assert(false, "unsupport parse url scheme:" .. scheme)
end
default = true
end
return scheme, host, port, path, default
end
local function send_request(io_do, fd, method, host, abs, header, body)
local tmp = ""
table.insert(header, 1, string.format("%s %s HTTP/1.1", method, abs))
table.insert(header, string.format("Host: %s", host))
table.insert(header, string.format("Content-Length: %d", #body))
table.insert(header, "User-Agent: Silly/0.2")
table.insert(header, "Connection: keep-alive")
table.insert(header, "\r\n")
tmp = table.concat(header, "\r\n")
tmp = tmp .. body
io_do.write(fd, tmp)
end
local function recv_response(io_do, fd)
local readl = function()
return io_do.readline(fd, "\r\n")
end
local readn = function(n)
return io_do.read(fd, n)
end
local status, first, header, body = stream.recv_request(readl, readn)
if not status then --disconnected
return nil
end
if status ~= 200 then
return status
end
local ver, status= first:match("HTTP/([%d|.]+)%s+(%d+)")
return tonumber(status), header, body, ver
end
local function process(uri, method, header, body)
local ip, io_do
local scheme, host, port, path, default = parseurl(uri)
if dns.isdomain(host) then
ip = dns.query(host)
else
ip = host
end
if scheme == "https" then
io_do = ssl
elseif scheme == "http" then
io_do = socket
end
if not default then
host = string.format("%s:%s", host, port)
end
ip = string.format("%s@%s", ip, port)
local fd = io_do.connect(ip)
if not fd then
return 599
end
if not header then
header = {}
end
body = body or ""
send_request(io_do, fd, method, host, path, header, body)
local status, header, body, ver = recv_response(io_do, fd)
io_do.close(fd)
return status, header, body, ver
end
function client.GET(uri, header)
return process(uri, "GET", header)
end
function client.POST(uri, header, body)
return process(uri, "POST", header, body)
end
return client
|
bugfix: http client use default header
|
bugfix: http client use default header
|
Lua
|
mit
|
findstr/silly
|
1136c35cdafbc9e9264db51a16f998464a684e05
|
libraries/map.lua
|
libraries/map.lua
|
--Must merge this with api.lua
local Map = _Class("liko12.map")
function Map:initialize(w,h)
self.w, self.h = w or 24, h or 28
--Initialize the map table
self.m = {}
for x=1, self.w do
self.m[x] = {}
for y=1, self.h do
self.m[x][y] = 0
end
end
end
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = Map(w,h)
local m = nMap:map()
for mx=1,w do
for my=1,h do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
Sprite(sprid,spx*8*sx - 8*sx, spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
return Map
|
--Must merge this with api.lua
local Map = _Class("liko12.map")
function Map:initialize(w,h)
self.w, self.h = w or 24, h or 8
--Initialize the map table
self.m = {}
for x=1, self.w do
self.m[x] = {}
for y=1, self.h do
self.m[x][y] = 0
end
end
end
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
--self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
func(x,y,self.m[x][y])
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = Map(w,h)
local m = nMap:map()
for mx=1,w do
for my=1,h do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
if sprid < 1 then return end
api.Sprite(sprid,dx + spx*8*sx - 8*sx, dy + spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
return Map
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
36d13a227d6c9b26ee1e6101b1bb13377a802ef4
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 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
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 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
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
ce70d514487bb30aec315828fe270695929163f4
|
npc/base/responses.lua
|
npc/base/responses.lua
|
--- Response Parsers
--
-- This file is part of the easyNPC framework.
-- The function in this class take care for postprocessing the responses that
-- are said by the NPCs
--
-- Author: Martin Karing
require("base.class")
require("base.factions")
module("npc.base.responses", package.seeall)
processorList = {};
do
--- Default processor implementation that does simply nothing.
local processor = base.class.class(function(self)
-- "check" is the function called once a response is added. This function
-- has to determine if this processor has at any point a impact on the
-- response. If this function returns "false" the processor will never be
-- executed for this class.
self["check"] = _processor_check_default;
-- This function is called in order to process the actual response text.
-- This function has to return the new text in any case.
self["process"] = _processor_process_default;
end);
function _processor_check_default(self, response)
return false;
end;
function _processor_process_default(self, playerChar, npc, npcChar, response)
return response;
end;
do
-- Player name processor
-- This processor replaces %CHARNAME with the name of the character
-- that is talking with the NPC.
local playerNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function playerNameProcessor:check(response)
return (string.find(response, "%CHARNAME", 1, true) ~= nil);
end;
function playerNameProcessor:process(playerChar, npc, npcChar, response)
return string.gsub(response, "%%CHARNAME", playerChar.name);
end;
table.insert(processorList, playerNameProcessor());
end;
do
-- NPC name processor
-- This processor replaces %NPCNAME with the name of the NPC.
local npcNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function npcNameProcessor:check(response)
return (string.find(response, "%NPCNAME", 1, true) ~= nil);
end;
function npcNameProcessor:process(playerChar, npc, npcChar, response)
return string.gsub(response, "%%NPCNAME", npcChar.name);
end;
table.insert(processorList, npcNameProcessor());
end;
do
-- town processor
-- This processor replaces %TOWN with the name of the town a character belongs to.
local townNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function townNameProcessor:check(response)
return (string.find(response, "%TOWN", 1, true) ~= nil);
end;
function townNameProcessor:process(playerChar, npc, npcChar, response)
local townName = base.factions.getMemberShipByName(playerChar)
return string.gsub(response, "%%TOWN", townName);
end;
table.insert(processorList, townNameProcessor());
end;
do
-- rank processor
-- This processor replaces %RANK with the rank of a character.
local rankProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function rankProcessor:check(response)
return (string.find(response, "%RANK", 1, true) ~= nil);
end;
function rankProcessor:process(playerChar, npc, npcChar, response)
local rank = base.factions.getRank(playerChar)
return string.gsub(response, "%%RANK", rank);
end;
table.insert(processorList, rankProcessor());
end;
end;
|
--- Response Parsers
--
-- This file is part of the easyNPC framework.
-- The function in this class take care for postprocessing the responses that
-- are said by the NPCs
--
-- Author: Martin Karing
require("base.class")
require("base.factions")
module("npc.base.responses", package.seeall)
processorList = {};
do
--- Default processor implementation that does simply nothing.
local processor = base.class.class(function(self)
-- "check" is the function called once a response is added. This function
-- has to determine if this processor has at any point a impact on the
-- response. If this function returns "false" the processor will never be
-- executed for this class.
self["check"] = _processor_check_default;
-- This function is called in order to process the actual response text.
-- This function has to return the new text in any case.
self["process"] = _processor_process_default;
end);
function _processor_check_default(self, response)
return false;
end;
function _processor_process_default(self, playerChar, npc, npcChar, response)
return response;
end;
do
-- Player name processor
-- This processor replaces %CHARNAME with the name of the character
-- that is talking with the NPC.
local playerNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function playerNameProcessor:check(response)
return (string.find(response, "%%CHARNAME") ~= nil);
end;
function playerNameProcessor:process(playerChar, npc, npcChar, response)
return string.gsub(response, "%%CHARNAME", playerChar.name);
end;
table.insert(processorList, playerNameProcessor());
end;
do
-- NPC name processor
-- This processor replaces %NPCNAME with the name of the NPC.
local npcNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function npcNameProcessor:check(response)
return (string.find(response, "%%NPCNAME") ~= nil);
end;
function npcNameProcessor:process(playerChar, npc, npcChar, response)
return string.gsub(response, "%%NPCNAME", npcChar.name);
end;
table.insert(processorList, npcNameProcessor());
end;
do
-- town processor
-- This processor replaces %TOWN with the name of the town a character belongs to.
local townNameProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function townNameProcessor:check(response)
return (string.find(response, "%%TOWN") ~= nil);
end;
function townNameProcessor:process(playerChar, npc, npcChar, response)
local townName = base.factions.getMemberShipByName(playerChar)
return string.gsub(response, "%%TOWN", townName);
end;
table.insert(processorList, townNameProcessor());
end;
do
-- rank processor
-- This processor replaces %RANK with the rank of a character.
local rankProcessor = base.class.class(processor,
function(self, value)
processor:init(self);
end);
function rankProcessor:check(response)
return (string.find(response, "%%RANK") ~= nil);
end;
function rankProcessor:process(playerChar, npc, npcChar, response)
local rank = base.factions.getRank(playerChar)
return string.gsub(response, "%%RANK", rank);
end;
table.insert(processorList, rankProcessor());
end;
end;
|
Trying to fix response processors of the NPCs
|
Trying to fix response processors of the NPCs
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
|
e7b006debbc7c211dbb1f9e3f400017934ddf74d
|
src/plugins/finalcutpro/timeline/transitions.lua
|
src/plugins/finalcutpro/timeline/transitions.lua
|
--- === plugins.finalcutpro.timeline.transitions ===
---
--- Controls Final Cut Pro's Transitions.
local require = require
--local log = require "hs.logger".new "transitions"
local timer = require "hs.timer"
local dialog = require "cp.dialog"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local doAfter = timer.doAfter
local mod = {}
--- plugins.finalcutpro.timeline.transitions(action) -> boolean
--- Function
--- Applies the specified action as a transition. Expects action to be a table with the following structure:
---
--- ```lua
--- { name = "XXX", category = "YYY", theme = "ZZZ" }
--- ```
---
--- ...where `"XXX"`, `"YYY"` and `"ZZZ"` are in the current FCPX language. The `category` and `theme` are optional,
--- but if they are known it's recommended to use them, or it will simply execute the first matching transition with that name.
---
--- Alternatively, you can also supply a string with just the name.
---
--- Parameters:
--- * `action` - A table with the name/category/theme for the transition to apply, or a string with just the name.
---
--- Returns:
--- * `true` if a matching transition was found and applied to the timeline.
function mod.apply(action)
--------------------------------------------------------------------------------
-- Get settings:
--------------------------------------------------------------------------------
if type(action) == "string" then
action = { name = action }
end
local name, category = action.name, action.category
if name == nil then
dialog.displayMessage(i18n("noPluginShortcut", {plugin = i18n("transition_group")}))
return false
end
--------------------------------------------------------------------------------
-- Save the Effects Browser layout:
--------------------------------------------------------------------------------
local effects = fcp.effects
local effectsLayout = effects:saveLayout()
--------------------------------------------------------------------------------
-- Get Transitions Browser:
--------------------------------------------------------------------------------
local transitions = fcp.transitions
local transitionsShowing = transitions:isShowing()
local transitionsLayout = transitions:saveLayout()
--------------------------------------------------------------------------------
-- Make sure FCPX is at the front.
--------------------------------------------------------------------------------
fcp:launch()
--------------------------------------------------------------------------------
-- Make sure panel is open:
--------------------------------------------------------------------------------
transitions:show()
--------------------------------------------------------------------------------
-- Make sure "Installed Transitions" is selected:
--------------------------------------------------------------------------------
local group = transitions.group:UI()
local groupValue = group:attributeValue("AXValue")
if groupValue ~= fcp:string("PEMediaBrowserInstalledTransitionsMenuItem") then
transitions:showInstalledTransitions()
end
--------------------------------------------------------------------------------
-- Get original search value:
--------------------------------------------------------------------------------
local originalSearch = transitions.search:value()
--------------------------------------------------------------------------------
-- Make sure there's nothing in the search box:
--------------------------------------------------------------------------------
transitions.search:clear()
--------------------------------------------------------------------------------
-- Click 'All':
--------------------------------------------------------------------------------
if category then
transitions:showTransitionsCategory(category)
else
transitions:showAllTransitions()
end
--------------------------------------------------------------------------------
-- Perform Search:
--------------------------------------------------------------------------------
transitions.search:setValue(name)
--------------------------------------------------------------------------------
-- Get the list of matching transitions:
--------------------------------------------------------------------------------
local matches = transitions:currentItemsUI()
if not matches or #matches == 0 then
dialog.displayErrorMessage(i18n("noPluginFound", {plugin=i18n("transition_group"), name=name}))
return false
end
--------------------------------------------------------------------------------
-- Take into account the Theme if needed:
--------------------------------------------------------------------------------
local transition = matches[1]
local requestedTitle = action.theme .. " - " .. action.name
if #matches > 1 then
for _, ui in pairs(matches) do
local title = ui:attributeValue("AXTitle")
if title == requestedTitle then
transition = ui
break
end
end
end
--------------------------------------------------------------------------------
-- Apply the selected Transition:
--------------------------------------------------------------------------------
transitions:applyItem(transition)
-- TODO: HACK: This timer exists to work around a mouse bug in Hammerspoon Sierra
doAfter(0.1, function()
transitions.search:setValue(originalSearch)
transitions:loadLayout(transitionsLayout)
if effectsLayout then effects:loadLayout(effectsLayout) end
if not transitionsShowing then transitions:hide() end
end)
-- Success!
return true
end
local plugin = {
id = "finalcutpro.timeline.transitions",
group = "finalcutpro",
dependencies = {
}
}
function plugin.init()
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod
end
return plugin
|
--- === plugins.finalcutpro.timeline.transitions ===
---
--- Controls Final Cut Pro's Transitions.
local require = require
--local log = require "hs.logger".new "transitions"
local timer = require "hs.timer"
local dialog = require "cp.dialog"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local doAfter = timer.doAfter
local mod = {}
--- plugins.finalcutpro.timeline.transitions(action) -> boolean
--- Function
--- Applies the specified action as a transition. Expects action to be a table with the following structure:
---
--- ```lua
--- { name = "XXX", category = "YYY", theme = "ZZZ" }
--- ```
---
--- ...where `"XXX"`, `"YYY"` and `"ZZZ"` are in the current FCPX language. The `category` and `theme` are optional,
--- but if they are known it's recommended to use them, or it will simply execute the first matching transition with that name.
---
--- Alternatively, you can also supply a string with just the name.
---
--- Parameters:
--- * `action` - A table with the name/category/theme for the transition to apply, or a string with just the name.
---
--- Returns:
--- * `true` if a matching transition was found and applied to the timeline.
function mod.apply(action)
--------------------------------------------------------------------------------
-- Get settings:
--------------------------------------------------------------------------------
if type(action) == "string" then
action = { name = action }
end
local name, category = action.name, action.category
if name == nil then
dialog.displayMessage(i18n("noPluginShortcut", {plugin = i18n("transition_group")}))
return false
end
--------------------------------------------------------------------------------
-- Save the Effects Browser layout:
--------------------------------------------------------------------------------
local effects = fcp.effects
local effectsLayout = effects:saveLayout()
--------------------------------------------------------------------------------
-- Get Transitions Browser:
--------------------------------------------------------------------------------
local transitions = fcp.transitions
local transitionsShowing = transitions:isShowing()
local transitionsLayout = transitions:saveLayout()
--------------------------------------------------------------------------------
-- Make sure FCPX is at the front.
--------------------------------------------------------------------------------
fcp:launch()
--------------------------------------------------------------------------------
-- Make sure panel is open:
--------------------------------------------------------------------------------
transitions:show()
--------------------------------------------------------------------------------
-- Make sure "Installed Transitions" is selected:
--------------------------------------------------------------------------------
local group = transitions.group:UI()
local groupValue = group:attributeValue("AXValue")
if groupValue ~= fcp:string("PEMediaBrowserInstalledTransitionsMenuItem") then
transitions:showInstalledTransitions()
end
--------------------------------------------------------------------------------
-- Get original search value:
--------------------------------------------------------------------------------
local originalSearch = transitions.search:value()
--------------------------------------------------------------------------------
-- Make sure there's nothing in the search box:
--------------------------------------------------------------------------------
transitions.search:clear()
--------------------------------------------------------------------------------
-- Click 'All':
--------------------------------------------------------------------------------
if category then
transitions:showTransitionsCategory(category)
else
transitions:showAllTransitions()
end
--------------------------------------------------------------------------------
-- Perform Search:
--------------------------------------------------------------------------------
transitions.search:setValue(name)
--------------------------------------------------------------------------------
-- Get the list of matching transitions:
--------------------------------------------------------------------------------
local matches = transitions:currentItemsUI()
if not matches or #matches == 0 then
dialog.displayErrorMessage(i18n("noPluginFound", {plugin=i18n("transition_group"), name=name}))
return false
end
--------------------------------------------------------------------------------
-- Take into account the Theme if needed:
--------------------------------------------------------------------------------
local transition = matches[1]
if action.theme and action.theme ~= "" then
local requestedTitle = action.theme .. " - " .. action.name
if #matches > 1 then
for _, ui in pairs(matches) do
local title = ui:attributeValue("AXTitle")
if title == requestedTitle then
transition = ui
break
end
end
end
end
--------------------------------------------------------------------------------
-- Apply the selected Transition:
--------------------------------------------------------------------------------
transitions:applyItem(transition)
-- TODO: HACK: This timer exists to work around a mouse bug in Hammerspoon Sierra
doAfter(0.1, function()
transitions.search:setValue(originalSearch)
transitions:loadLayout(transitionsLayout)
if effectsLayout then effects:loadLayout(effectsLayout) end
if not transitionsShowing then transitions:hide() end
end)
-- Success!
return true
end
local plugin = {
id = "finalcutpro.timeline.transitions",
group = "finalcutpro",
dependencies = {
}
}
function plugin.init()
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod
end
return plugin
|
Fixed bug when applying transitions
|
Fixed bug when applying transitions
- Closes #2759
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
|
007b82885fbc8f8adf7dfe99c510f2d478e6fa59
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
module/admin-core/src/model/cbi/admin_services/olsrd.lua
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s").isnumber = true
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung").isinteger = true
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße").isinteger = true
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
i:option(Value, "Interface", "Netzwerkschnittstellen")
i:option(Value, "HelloInterval", "Hello-Intervall").isnumber = true
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit").isnumber = true
i:option(Value, "TcInterval", "TC-Intervall").isnumber = true
i:option(Value, "TcValidityTime", "TC-Gültigkeit").isnumber = true
i:option(Value, "MidInterval", "MID-Intervall").isnumber = true
i:option(Value, "MidValidityTime", "MID-Gültigkeit").isnumber = true
i:option(Value, "HnaInterval", "HNA-Intervall").isnumber = true
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit").isnumber = true
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
-- ToDo: Autodetect things, Translate, Add descriptions
require("ffluci.fs")
m = Map("olsr", "OLSR", [[OLSR ist ein flexibles Routingprotokoll,
dass den Aufbau von mobilen Ad-Hoc Netzen unterstützt.]])
s = m:section(NamedSection, "general", "olsr", "Allgemeine Einstellungen")
debug = s:option(ListValue, "DebugLevel", "Debugmodus")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion", "Internet Protokoll")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt", "Start ohne Netzwerk")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate", "Abfragerate (Pollrate)", "s")
tcr = s:option(ListValue, "TcRedundancy", "TC-Redundanz")
tcr:value("0", "MPR-Selektoren")
tcr:value("1", "MPR-Selektoren und MPR")
tcr:value("2", "Alle Nachbarn")
s:option(Value, "MprCoverage", "MPR-Erfassung")
lql = s:option(ListValue, "LinkQualityLevel", "VQ-Level")
lql:value("0", "deaktiviert")
lql:value("1", "MPR-Auswahl")
lql:value("2", "MPR-Auswahl und Routing")
lqfish = s:option(Flag, "LinkQualityFishEye", "VQ-Fisheye")
s:option(Value, "LinkQualityWinSize", "VQ-Fenstergröße")
s:option(Value, "LinkQualityDijkstraLimit", "VQ-Dijkstralimit")
hyst = s:option(Flag, "UseHysteresis", "Hysterese aktivieren")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", "Schnittstellen")
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", "Netzwerkschnittstellen")
network:value("")
for k, v in pairs(ffluci.model.uci.show("network").network) do
if v[".type"] == "interface" and k ~= "loopback" then
network:value(k)
end
end
i:option(Value, "HelloInterval", "Hello-Intervall")
i:option(Value, "HelloValidityTime", "Hello-Gültigkeit")
i:option(Value, "TcInterval", "TC-Intervall")
i:option(Value, "TcValidityTime", "TC-Gültigkeit")
i:option(Value, "MidInterval", "MID-Intervall")
i:option(Value, "MidValidityTime", "MID-Gültigkeit")
i:option(Value, "HnaInterval", "HNA-Intervall")
i:option(Value, "HnaValidityTime", "HNA-Gültigkeit")
p = m:section(TypedSection, "LoadPlugin", "Plugins")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", "Bibliothek")
lib:value("")
for k, v in pairs(ffluci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
return m
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
|
* ffluci.model.cbi.admin_services.olsr: Fixed variable conversion
|
Lua
|
apache-2.0
|
obsy/luci,oyido/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,jorgifumi/luci,daofeng2015/luci,thesabbir/luci,Noltari/luci,ff94315/luci-1,deepak78/new-luci,slayerrensky/luci,palmettos/test,keyidadi/luci,zhaoxx063/luci,kuoruan/luci,Wedmer/luci,palmettos/cnLuCI,jlopenwrtluci/luci,LuttyYang/luci,nmav/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,schidler/ionic-luci,nwf/openwrt-luci,RuiChen1113/luci,schidler/ionic-luci,mumuqz/luci,nmav/luci,MinFu/luci,ollie27/openwrt_luci,lcf258/openwrtcn,nwf/openwrt-luci,kuoruan/luci,forward619/luci,chris5560/openwrt-luci,maxrio/luci981213,slayerrensky/luci,lbthomsen/openwrt-luci,sujeet14108/luci,tobiaswaldvogel/luci,bittorf/luci,bright-things/ionic-luci,opentechinstitute/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,Kyklas/luci-proto-hso,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,Wedmer/luci,remakeelectric/luci,ff94315/luci-1,forward619/luci,palmettos/test,RuiChen1113/luci,thess/OpenWrt-luci,florian-shellfire/luci,Sakura-Winkey/LuCI,sujeet14108/luci,daofeng2015/luci,marcel-sch/luci,florian-shellfire/luci,Wedmer/luci,thess/OpenWrt-luci,bittorf/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,chris5560/openwrt-luci,remakeelectric/luci,maxrio/luci981213,Noltari/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,male-puppies/luci,palmettos/cnLuCI,dismantl/luci-0.12,cshore/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,bittorf/luci,dismantl/luci-0.12,Sakura-Winkey/LuCI,jorgifumi/luci,urueedi/luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,shangjiyu/luci-with-extra,artynet/luci,Kyklas/luci-proto-hso,maxrio/luci981213,RedSnake64/openwrt-luci-packages,urueedi/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,MinFu/luci,palmettos/cnLuCI,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,opentechinstitute/luci,tcatm/luci,Noltari/luci,bright-things/ionic-luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,fkooman/luci,aa65535/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,david-xiao/luci,MinFu/luci,zhaoxx063/luci,rogerpueyo/luci,wongsyrone/luci-1,Hostle/luci,artynet/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,oyido/luci,keyidadi/luci,openwrt/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,cappiewu/luci,nmav/luci,taiha/luci,taiha/luci,joaofvieira/luci,openwrt/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,artynet/luci,Hostle/luci,remakeelectric/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,daofeng2015/luci,taiha/luci,hnyman/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,daofeng2015/luci,schidler/ionic-luci,RuiChen1113/luci,zhaoxx063/luci,keyidadi/luci,schidler/ionic-luci,nwf/openwrt-luci,obsy/luci,obsy/luci,david-xiao/luci,cshore/luci,hnyman/luci,cshore/luci,openwrt/luci,obsy/luci,lcf258/openwrtcn,Wedmer/luci,cappiewu/luci,palmettos/test,jchuang1977/luci-1,oneru/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,deepak78/new-luci,mumuqz/luci,lbthomsen/openwrt-luci,maxrio/luci981213,fkooman/luci,cappiewu/luci,taiha/luci,nmav/luci,ollie27/openwrt_luci,bittorf/luci,shangjiyu/luci-with-extra,urueedi/luci,zhaoxx063/luci,thess/OpenWrt-luci,slayerrensky/luci,jlopenwrtluci/luci,Hostle/luci,marcel-sch/luci,artynet/luci,rogerpueyo/luci,keyidadi/luci,jlopenwrtluci/luci,palmettos/cnLuCI,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,fkooman/luci,thess/OpenWrt-luci,male-puppies/luci,oneru/luci,RuiChen1113/luci,keyidadi/luci,teslamint/luci,bittorf/luci,LuttyYang/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,hnyman/luci,cshore/luci,fkooman/luci,ollie27/openwrt_luci,oyido/luci,MinFu/luci,jlopenwrtluci/luci,palmettos/cnLuCI,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,Wedmer/luci,aa65535/luci,Hostle/luci,maxrio/luci981213,oyido/luci,marcel-sch/luci,marcel-sch/luci,marcel-sch/luci,LuttyYang/luci,schidler/ionic-luci,981213/luci-1,ollie27/openwrt_luci,taiha/luci,lbthomsen/openwrt-luci,aa65535/luci,lcf258/openwrtcn,ff94315/luci-1,joaofvieira/luci,deepak78/new-luci,NeoRaider/luci,lcf258/openwrtcn,remakeelectric/luci,thess/OpenWrt-luci,kuoruan/luci,kuoruan/lede-luci,lcf258/openwrtcn,oneru/luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,NeoRaider/luci,thesabbir/luci,remakeelectric/luci,981213/luci-1,joaofvieira/luci,wongsyrone/luci-1,aa65535/luci,lbthomsen/openwrt-luci,kuoruan/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,dwmw2/luci,palmettos/test,Noltari/luci,bright-things/ionic-luci,lcf258/openwrtcn,openwrt/luci,david-xiao/luci,dismantl/luci-0.12,jlopenwrtluci/luci,MinFu/luci,remakeelectric/luci,marcel-sch/luci,rogerpueyo/luci,tcatm/luci,Hostle/luci,dwmw2/luci,thess/OpenWrt-luci,male-puppies/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,jchuang1977/luci-1,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,ff94315/luci-1,deepak78/new-luci,florian-shellfire/luci,LuttyYang/luci,jlopenwrtluci/luci,palmettos/test,palmettos/cnLuCI,Noltari/luci,daofeng2015/luci,NeoRaider/luci,kuoruan/lede-luci,keyidadi/luci,dwmw2/luci,cshore-firmware/openwrt-luci,thesabbir/luci,nwf/openwrt-luci,thesabbir/luci,teslamint/luci,keyidadi/luci,palmettos/test,harveyhu2012/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,chris5560/openwrt-luci,david-xiao/luci,male-puppies/luci,thess/OpenWrt-luci,MinFu/luci,hnyman/luci,slayerrensky/luci,Noltari/luci,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,Kyklas/luci-proto-hso,male-puppies/luci,oneru/luci,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,tcatm/luci,fkooman/luci,mumuqz/luci,Kyklas/luci-proto-hso,jorgifumi/luci,cappiewu/luci,oneru/luci,kuoruan/lede-luci,rogerpueyo/luci,981213/luci-1,thesabbir/luci,RuiChen1113/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,dwmw2/luci,981213/luci-1,jorgifumi/luci,oyido/luci,ff94315/luci-1,male-puppies/luci,cshore/luci,slayerrensky/luci,keyidadi/luci,openwrt-es/openwrt-luci,sujeet14108/luci,teslamint/luci,shangjiyu/luci-with-extra,teslamint/luci,opentechinstitute/luci,kuoruan/lede-luci,hnyman/luci,RuiChen1113/luci,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,RuiChen1113/luci,bittorf/luci,maxrio/luci981213,LuttyYang/luci,forward619/luci,openwrt-es/openwrt-luci,urueedi/luci,wongsyrone/luci-1,nmav/luci,taiha/luci,teslamint/luci,bright-things/ionic-luci,dwmw2/luci,nmav/luci,tcatm/luci,kuoruan/lede-luci,teslamint/luci,david-xiao/luci,Noltari/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,forward619/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,daofeng2015/luci,fkooman/luci,harveyhu2012/luci,rogerpueyo/luci,slayerrensky/luci,tobiaswaldvogel/luci,NeoRaider/luci,openwrt/luci,shangjiyu/luci-with-extra,mumuqz/luci,openwrt-es/openwrt-luci,oneru/luci,slayerrensky/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,artynet/luci,nmav/luci,sujeet14108/luci,aa65535/luci,dismantl/luci-0.12,fkooman/luci,Sakura-Winkey/LuCI,981213/luci-1,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,chris5560/openwrt-luci,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,RedSnake64/openwrt-luci-packages,jorgifumi/luci,wongsyrone/luci-1,rogerpueyo/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,Hostle/luci,forward619/luci,tcatm/luci,bright-things/ionic-luci,bright-things/ionic-luci,zhaoxx063/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,harveyhu2012/luci,kuoruan/luci,RuiChen1113/luci,cappiewu/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,aa65535/luci,daofeng2015/luci,artynet/luci,cshore/luci,wongsyrone/luci-1,taiha/luci,jchuang1977/luci-1,palmettos/test,Sakura-Winkey/LuCI,ff94315/luci-1,Wedmer/luci,nmav/luci,fkooman/luci,forward619/luci,obsy/luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,cappiewu/luci,david-xiao/luci,taiha/luci,kuoruan/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,openwrt-es/openwrt-luci,obsy/luci,aa65535/luci,openwrt/luci,nmav/luci,lcf258/openwrtcn,florian-shellfire/luci,thesabbir/luci,hnyman/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,ff94315/luci-1,kuoruan/lede-luci,kuoruan/luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,jlopenwrtluci/luci,wongsyrone/luci-1,obsy/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,artynet/luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,forward619/luci,dwmw2/luci,sujeet14108/luci,MinFu/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,ollie27/openwrt_luci,zhaoxx063/luci,oyido/luci,opentechinstitute/luci,florian-shellfire/luci,sujeet14108/luci,ollie27/openwrt_luci,NeoRaider/luci,chris5560/openwrt-luci,jchuang1977/luci-1,tcatm/luci,ff94315/luci-1,palmettos/cnLuCI,opentechinstitute/luci,mumuqz/luci,lcf258/openwrtcn,joaofvieira/luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,cappiewu/luci,Kyklas/luci-proto-hso,deepak78/new-luci,aa65535/luci,NeoRaider/luci,Wedmer/luci,ollie27/openwrt_luci,male-puppies/luci,oneru/luci,teslamint/luci,nwf/openwrt-luci,NeoRaider/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,bittorf/luci,remakeelectric/luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,zhaoxx063/luci,rogerpueyo/luci,dwmw2/luci,tcatm/luci,urueedi/luci,kuoruan/lede-luci,nwf/openwrt-luci,sujeet14108/luci,tobiaswaldvogel/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,Kyklas/luci-proto-hso,marcel-sch/luci,nwf/openwrt-luci,openwrt/luci,chris5560/openwrt-luci,LuttyYang/luci,artynet/luci,shangjiyu/luci-with-extra,oyido/luci,jorgifumi/luci,981213/luci-1,jorgifumi/luci,mumuqz/luci,cappiewu/luci,artynet/luci,LuttyYang/luci,Hostle/luci,cshore/luci,oyido/luci,Sakura-Winkey/LuCI,bittorf/luci,thesabbir/luci,mumuqz/luci
|
00fb7773c7af447ce1d7b2f13d99abd0dff5d6b0
|
helppage.lua
|
helppage.lua
|
require "rendertext"
require "keys"
require "graphics"
require "font"
require "inputbox"
require "selectmenu"
require "commands"
HelpPage = {
-- Other Class vars:
-- spacing between lines
spacing = 25,
-- state buffer
commands = nil,
items = 0,
page = 1,
-- font for displaying keys
fsize = 20,
face = Font:getFace("hpkfont", 20),
-- font for displaying help messages
hfsize = 20,
hface = Font:getFace("hfont", 20),
-- font for paging display
ffsize = 15,
fface = Font:getFace("pgfont", 15)
}
-- Other Class vars:
function HelpPage:show(ypos, height, commands)
self.commands = {}
self.items = 0
local keys = {}
for k,v in pairs(commands.map) do
local key = v.keygroup or v.keydef:display()
--debug("order: "..v.order.." command: "..tostring(v.keydef).." - keygroup:"..(v.keygroup or "nil").." -keys[key]:"..(keys[key] or "nil"))
if keys[key] == nil then
keys[key] = 1
table.insert(self.commands,{shortcut=key,help=v.help,order=v.order})
self.items = self.items + 1
end
end
table.sort(self.commands,function(w1,w2) return w1.order<w2.order end)
local face_height, face_ascender = self.face.ftface:getHeightAndAscender()
--local hface_height, hface_ascender = self.hface.ftface:getHeightAndAscender()
local fface_height, fface_ascender = self.fface.ftface:getHeightAndAscender()
--debug(face_height.."-"..face_ascender)
--debug(fface_height.."-"..fface_ascender)
face_height = math.ceil(face_height)
face_ascender = math.ceil(face_ascender)
fface_height = math.ceil(fface_height)
fface_ascender = math.ceil(fface_ascender)
local spacing = face_height + 5
local perpage = math.floor( (height - ypos - 1 * (fface_height + 5)) / spacing )
local is_pagedirty = true
while true do
if is_pagedirty then
fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0)
local c
local max_x = 0
for c = 1, perpage do
local x = 5
local i = (self.page - 1) * perpage + c
if i <= self.items then
local key = self.commands[i].shortcut
for _k,aMod in pairs(MOD_TABLE) do
local modStart, modEnd = key:find(aMod.v)
debug("key:"..key.." v:"..aMod.v.." d:"..aMod.d.." modstart:"..(modStart or "nil"))
if(modStart ~= nil) then
key = key:sub(1,modStart-1)..key:sub(modEnd+1)
local box = sizeUtf8Text( x, fb.bb:getWidth(), self.face, aMod.d, true)
fb.bb:paintRect(x, ypos + spacing*c - box.y_top, box.x, box.y_top + box.y_bottom, 4)
local pen_x = renderUtf8Text(fb.bb, x, ypos + spacing*c, self.face, aMod.d.." + ", true)
x = x + pen_x
max_x = math.max(max_x, pen_x)
end
end
debug("key:"..key)
local box = sizeUtf8Text( x, fb.bb:getWidth(), self.face, key , true)
fb.bb:paintRect(x, ypos + spacing*c - box.y_top, box.x, box.y_top + box.y_bottom, 4)
local pen_x = renderUtf8Text(fb.bb, x, ypos + spacing*c, self.face, key, true)
x = x + pen_x
max_x = math.max(max_x, x)
end
end
for c = 1, perpage do
local i = (self.page - 1) * perpage + c
if i <= self.items then
renderUtf8Text(fb.bb, max_x + 20, ypos + spacing*c, self.hface, self.commands[i].help, true)
end
end
renderUtf8Text(fb.bb, 5, height - fface_height + fface_ascender - 5, self.fface,
"Page "..self.page.." of "..math.ceil(self.items / perpage).." - Back to close this page", true)
end
if is_pagedirty then
fb:refresh(0, 0, ypos, fb.bb:getWidth(), height)
is_pagedirty = false
end
local ev = input.saveWaitForEvent()
--debug("key code:"..ev.code)
ev.code = adjustKeyEvents(ev)
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
if ev.code == KEY_PGFWD then
if self.page < (self.items / perpage) then
self.page = self.page + 1
is_pagedirty = true
end
elseif ev.code == KEY_PGBCK then
if self.page > 1 then
self.page = self.page - 1
is_pagedirty = true
end
elseif ev.code == KEY_BACK or ev.code == KEY_HOME then
return nil
end
end
end
end
|
require "rendertext"
require "keys"
require "graphics"
require "font"
require "inputbox"
require "selectmenu"
require "commands"
HelpPage = {
-- Other Class vars:
-- spacing between lines
spacing = 25,
-- state buffer
commands = nil,
items = 0,
page = 1,
-- font for displaying keys
fsize = 20,
face = Font:getFace("hpkfont", 20),
-- font for displaying help messages
hfsize = 20,
hface = Font:getFace("hfont", 20),
-- font for paging display
ffsize = 15,
fface = Font:getFace("pgfont", 15)
}
-- Other Class vars:
function HelpPage:show(ypos, height, commands)
self.commands = {}
self.items = 0
local keys = {}
for k,v in pairs(commands.map) do
local key = v.keygroup or v.keydef:display()
--debug("order: "..v.order.." command: "..tostring(v.keydef).." - keygroup:"..(v.keygroup or "nil").." -keys[key]:"..(keys[key] or "nil"))
if keys[key] == nil then
keys[key] = 1
table.insert(self.commands,{shortcut=key,help=v.help,order=v.order})
self.items = self.items + 1
end
end
table.sort(self.commands,function(w1,w2) return w1.order<w2.order end)
local face_height, face_ascender = self.face.ftface:getHeightAndAscender()
--local hface_height, hface_ascender = self.hface.ftface:getHeightAndAscender()
local fface_height, fface_ascender = self.fface.ftface:getHeightAndAscender()
--debug(face_height.."-"..face_ascender)
--debug(fface_height.."-"..fface_ascender)
face_height = math.ceil(face_height)
face_ascender = math.ceil(face_ascender)
fface_height = math.ceil(fface_height)
fface_ascender = math.ceil(fface_ascender)
local spacing = face_height + 5
local perpage = math.floor( (height - ypos - 1 * (fface_height + 5)) / spacing )
local is_pagedirty = true
while true do
if is_pagedirty then
fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0)
local c
local max_x = 0
for c = 1, perpage do
local x = 5
local i = (self.page - 1) * perpage + c
if i <= self.items then
local key = self.commands[i].shortcut
for _k,aMod in pairs(MOD_TABLE) do
local modStart, modEnd = key:find(aMod.v)
debug("key:"..key.." v:"..aMod.v.." d:"..aMod.d.." modstart:"..(modStart or "nil"))
if(modStart ~= nil) then
key = key:sub(1,modStart-1)..key:sub(modEnd+1)
local box = sizeUtf8Text( x, fb.bb:getWidth(), self.face, aMod.d, true)
fb.bb:paintRect(x, ypos + spacing*c - box.y_top, box.x, box.y_top + box.y_bottom, 4)
local pen_x = renderUtf8Text(fb.bb, x, ypos + spacing*c, self.face, aMod.d.." + ", true)
x = x + pen_x
max_x = math.max(max_x, pen_x)
end
end
debug("key:"..key)
local box = sizeUtf8Text( x, fb.bb:getWidth(), self.face, key , true)
fb.bb:paintRect(x, ypos + spacing*c - box.y_top, box.x, box.y_top + box.y_bottom, 4)
local pen_x = renderUtf8Text(fb.bb, x, ypos + spacing*c, self.face, key, true)
x = x + pen_x
max_x = math.max(max_x, x)
end
end
for c = 1, perpage do
local i = (self.page - 1) * perpage + c
if i <= self.items then
renderUtf8Text(fb.bb, max_x + 20, ypos + spacing*c, self.hface, self.commands[i].help, true)
end
end
renderUtf8Text(fb.bb, 5, height - fface_height + fface_ascender - 5, self.fface,
"Page "..self.page.." of "..math.ceil(self.items / perpage).." - Back to close this page", true)
end
if is_pagedirty then
fb:refresh(0, 0, ypos, fb.bb:getWidth(), height)
is_pagedirty = false
end
local ev = input.saveWaitForEvent()
--debug("key code:"..ev.code)
ev.code = adjustKeyEvents(ev)
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
if ev.code == KEY_PGFWD or ev.code == KEY_LPGFWD then
if self.page < (self.items / perpage) then
self.page = self.page + 1
is_pagedirty = true
end
elseif ev.code == KEY_PGBCK or ev.code == KEY_LPGBCK then
if self.page > 1 then
self.page = self.page - 1
is_pagedirty = true
end
elseif ev.code == KEY_BACK or ev.code == KEY_HOME then
return nil
end
end
end
end
|
add fix KEY_LPG{BCK,FWD} listening for helppage
|
add fix KEY_LPG{BCK,FWD} listening for helppage
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader,NiLuJe/koreader,koreader/koreader-base,NiLuJe/koreader-base,noname007/koreader,koreader/koreader-base,mihailim/koreader,poire-z/koreader,Frenzie/koreader-base,mwoz123/koreader,NiLuJe/koreader,koreader/koreader,koreader/koreader,Markismus/koreader,frankyifei/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,apletnev/koreader,ashang/koreader,houqp/koreader,ashhher3/koreader,Frenzie/koreader,Hzj-jie/koreader-base,chrox/koreader,apletnev/koreader-base,robert00s/koreader,NickSavage/koreader,frankyifei/koreader,Hzj-jie/koreader-base,apletnev/koreader-base,houqp/koreader-base,houqp/koreader-base,Frenzie/koreader,Frenzie/koreader-base,chihyang/koreader,poire-z/koreader,pazos/koreader,koreader/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,koreader/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,lgeek/koreader
|
81faff3db4317146aa77651164b4b230cd6ffbfb
|
pkg/torch/argtypes.lua
|
pkg/torch/argtypes.lua
|
torch.argtypes = {}
torch.argtypes["numbers"] = {
vararg = true, -- if needed, one can override it to false
check = function(self)
local idx = self.luaname:match('select%((%d+), %.%.%.%)')
if idx then -- ordered arguments
if self.vararg then -- can be (1, 2, 3) or {1, 2, 3}
return string.format([[
(function(...)
if %d == narg and type(select(%d, ...)) == 'table' then
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
else
%s = {}
for i=%d,narg do
local z = select(i, ...)
if type(z) ~= 'number' then
%s = nil
return false
end
table.insert(%s, z)
end
end
return true
end)(...) ]], idx, idx, self.name, idx, self.name, self.name, self.name, self.name, self.name, idx, self.name, self.name)
else -- can only be {1, 2, 3}
return string.format([[
(function(...)
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
return true
end)(...) ]], self.name, idx, self.name, self.name, self.name, self.name)
end
else -- named arguments
return string.format(
[[
(function(...)
if not %s then
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
return false
end
end
return true
end)(...) ]], self.luaname, self.luaname)
end
end,
read = function(self)
end
}
torch.argtypes["number"] = {
check = function(self)
return string.format("type(%s) == 'number'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["boolean"] = {
check = function(self)
return string.format("type(%s) == 'boolean'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["string"] = {
check = function(self)
assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name))
return string.format("type(%s) == 'string'", self.luaname)
end,
initdefault = function(self)
return string.format('"%s"', self.default)
end
}
for _,Tensor in ipairs{'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.LongTensor',
'torch.FloatTensor',
'torch.DoubleTensor'} do
torch.argtypes[Tensor] = {
check = function(self)
if self.dim then
return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim)
else
return string.format("type(%s) == '" .. Tensor .. "'", self.luaname)
end
end,
initdefault = function(self)
return Tensor .. "()"
end
}
end
|
torch.argtypes = {}
torch.argtypes["numbers"] = {
vararg = true, -- if needed, one can override it to false
check = function(self)
local idx = self.luaname:match('select%((%d+), %.%.%.%)')
if idx then -- ordered arguments
if self.vararg then -- can be (1, 2, 3) or {1, 2, 3}
return string.format([[
(function(...)
if %d == narg and type(select(%d, ...)) == 'table' then
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
else
%s = {}
for i=%d,narg do
local z = select(i, ...)
if type(z) ~= 'number' then
%s = nil
return false
end
table.insert(%s, z)
end
end
return true
end)(...) ]], idx, idx, self.name, idx, self.name, self.name, self.name, self.name, self.name, idx, self.name, self.name)
else -- can only be {1, 2, 3}
return string.format([[
(function(...)
%s = select(%d, ...)
if type(%s) ~= 'table' then
%s = nil
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
%s = nil
return false
end
end
return true
end)(...) ]], self.name, idx, self.name, self.name, self.name, self.name)
end
else -- named arguments
return string.format(
[[
(function(...)
if not %s then
return false
end
for _,z in ipairs(%s) do
if type(z) ~= 'number' then
return false
end
end
%s = %s
return true
end)(...) ]], self.luaname, self.luaname, self.name, self.luaname)
end
end,
read = function(self)
end
}
torch.argtypes["number"] = {
check = function(self)
return string.format("type(%s) == 'number'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'number', string.format('argument <%s> default should be a number', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["boolean"] = {
check = function(self)
return string.format("type(%s) == 'boolean'", self.luaname)
end,
initdefault = function(self)
assert(type(self.default) == 'boolean', string.format('argument <%s> default should be a boolean', self.name))
return string.format('%s', self.default)
end
}
torch.argtypes["string"] = {
check = function(self)
assert(type(self.default) == 'string', string.format('argument <%s> default should be a string', self.name))
return string.format("type(%s) == 'string'", self.luaname)
end,
initdefault = function(self)
return string.format('"%s"', self.default)
end
}
for _,Tensor in ipairs{'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.LongTensor',
'torch.FloatTensor',
'torch.DoubleTensor'} do
torch.argtypes[Tensor] = {
check = function(self)
if self.dim then
return string.format("type(%s) == '" .. Tensor .. "' and (%s).__nDimension == %d", self.luaname, self.luaname, self.dim)
else
return string.format("type(%s) == '" .. Tensor .. "'", self.luaname)
end
end,
initdefault = function(self)
return Tensor .. "()"
end
}
end
|
bug correction for named numbers
|
bug correction for named numbers
|
Lua
|
bsd-3-clause
|
torch/argcheck
|
f7979de1e6aaa03d14d93227a4c81acf03bccd48
|
test_scripts/Polices/App_Permissions/ATF_P_DISALLOWED_App_Which_Name_Does_Not_Match_With_Nickname_In_PT.lua
|
test_scripts/Polices/App_Permissions/ATF_P_DISALLOWED_App_Which_Name_Does_Not_Match_With_Nickname_In_PT.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] DISALLOWED app`s nickname does not match ones listed in Policy Table
--
-- Description:
-- PoliciesManager must disallow the app`s registration IN CASE the app`s nickname does not match those listed in Policy Table under the appID this app registers with
-- 1. Used preconditions:
-- a) First SDL life cycle with loaded permissions for specific appId and nickname for it
-- 2. Performed steps
-- a) Register app with appName which not present nickNames list
--
-- Expected result:
-- a) SDL->app: RegisterAppInterface(DISALLOWED, success:false)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
local mobile_session = require('mobile_session')
--[[ Local Functions ]]
local function BackupPreloaded()
os.execute('cp ' .. config.pathToSDL .. 'sdl_preloaded_pt.json' .. ' ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json')
os.execute('rm ' .. config.pathToSDL .. 'policy.sqlite')
end
local function RestorePreloadedPT()
os.execute('rm ' .. config.pathToSDL .. 'sdl_preloaded_pt.json')
os.execute('cp ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json' .. ' ' .. config.pathToSDL .. 'sdl_preloaded_pt.json')
end
local function SetNickNameForSpecificApp()
local pathToFile = config.pathToSDL .. 'sdl_preloaded_pt.json'
local file = io.open(pathToFile, "r")
local json_data = file:read("*all") -- may be abbreviated to "*a";
file:close()
local json = require("modules/json")
local data = json.decode(json_data)
if data.policy_table.functional_groupings["DataConsent-2"] then
data.policy_table.functional_groupings["DataConsent-2"] = nil
end
data.policy_table.app_policies["1234567"] = {
keep_context = false,
steal_focus = false,
priority = "NONE",
default_hmi = "NONE",
groups = {"Base-4"},
nicknames = {"SPT"}
}
data = json.encode(data)
file = io.open(pathToFile, "w")
file:write(data)
file:close()
end
--[[ Preconditions ]]
function Test:Precondition_StopSDL()
StopSDL()
end
function Test:Precondition_DeleteLogsAndPolicyTable()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
end
function Test:Precondition_Backup_sdl_preloaded_pt()
BackupPreloaded()
end
function Test:Precondition_Set_NickName_Permissions_For_Specific_AppId()
SetNickNameForSpecificApp()
end
function Test:Precondition_StartSDL_FirstLifeCycle()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI_FirstLifeCycle()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady_FirstLifeCycle()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile_FirstLifeCycle()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
function Test:Precondition_RestorePreloadedPT()
RestorePreloadedPT()
end
--[[ Test ]]
function Test:TestStep_Register_App_Which_Name_Not_Listad_In_PT_DISALLOWED()
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface",
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "AnotherAppName",
isMediaApplication = true,
languageDesired = "EN-US",
hmiDisplayLanguageDesired = "EN-US",
appID = "1234567",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
})
EXPECT_RESPONSE(CorIdRAI, { success = false, resultCode = "DISALLOWED"})
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
StopSDL()
end
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [RegisterAppInterface] DISALLOWED app`s nickname does not match ones listed in Policy Table
--
-- Description:
-- PoliciesManager must disallow the app`s registration IN CASE the app`s nickname does not match those listed in Policy Table under the appID this app registers with
-- 1. Used preconditions:
-- a) First SDL life cycle with loaded permissions for specific appId and nickname for it
-- 2. Performed steps
-- a) Register app with appName which not present nickNames list
--
-- Expected result:
-- a) SDL->app: RegisterAppInterface(DISALLOWED, success:false)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
local mobile_session = require('mobile_session')
--[[ Local Functions ]]
local function BackupPreloaded()
os.execute('cp ' .. config.pathToSDL .. 'sdl_preloaded_pt.json' .. ' ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json')
end
local function RestorePreloadedPT()
os.execute('rm ' .. config.pathToSDL .. 'sdl_preloaded_pt.json')
os.execute('cp ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json' .. ' ' .. config.pathToSDL .. 'sdl_preloaded_pt.json')
os.execute('rm ' .. config.pathToSDL .. 'backup_sdl_preloaded_pt.json')
end
local function SetNickNameForSpecificApp()
local pathToFile = config.pathToSDL .. 'sdl_preloaded_pt.json'
local file = io.open(pathToFile, "r")
local json_data = file:read("*all") -- may be abbreviated to "*a";
file:close()
local json = require("modules/json")
local data = json.decode(json_data)
if data.policy_table.functional_groupings["DataConsent-2"] then
data.policy_table.functional_groupings["DataConsent-2"] = nil
end
data.policy_table.app_policies["1234567"] = {
keep_context = false,
steal_focus = false,
priority = "NONE",
default_hmi = "NONE",
groups = {"Base-4"},
nicknames = {"SPT"}
}
data = json.encode(data)
file = io.open(pathToFile, "w")
file:write(data)
file:close()
end
--[[ Preconditions ]]
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_DeleteLogsAndPolicyTable()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
end
function Test.Precondition_Backup_sdl_preloaded_pt()
BackupPreloaded()
end
function Test.Precondition_Set_NickName_Permissions_For_Specific_AppId()
SetNickNameForSpecificApp()
end
function Test.Precondition_StartSDL_FirstLifeCycle()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI_FirstLifeCycle()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady_FirstLifeCycle()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile_FirstLifeCycle()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
function Test.Precondition_RestorePreloadedPT()
RestorePreloadedPT()
end
--[[ Test ]]
function Test:TestStep_Register_DefaultApp()
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"})
end
function Test:Precondition_StartSession()
self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
end
function Test:TestStep_Register_App_Which_Name_Not_Listad_In_PT_DISALLOWED()
local CorIdRAI = self.mobileSession2:SendRPC("RegisterAppInterface",
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "AnotherAppName",
isMediaApplication = true,
languageDesired = "EN-US",
hmiDisplayLanguageDesired = "EN-US",
appID = "1234567",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
})
self.mobileSession2:ExpectResponse(CorIdRAI, { success = false, resultCode = "DISALLOWED"})
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
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
|
93d8e1f745a08592a5b769ab0055091d89bbde2d
|
data/sentenceset.lua
|
data/sentenceset.lua
|
------------------------------------------------------------------------
--[[ SentenceSet ]]--
-- Inherits DataSet
-- Used for Language Modeling
-- Takes a sequence of words stored as a tensor of word ids,
-- and a tensor holding the start index of the sentence of its
-- commensurate word id (the one at the same index).
-- Unlike DataSet, for memory efficiency reasons,
-- this class does not store its data in Views.
-- However, the outputs of batch(), sub(), index() are dp.Batches
-- containing ClassViews of inputs and targets.
-- The returned batch:inputs() are filled according to
-- https://code.google.com/p/1-billion-word-language-modeling-benchmark/source/browse/trunk/README.perplexity_and_such
------------------------------------------------------------------------
local SentenceSet, parent = torch.class("dp.SentenceSet", "dp.DataSet")
SentenceSet.isSentenceSet = true
function SentenceSet:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, which_set, data, context_size, end_id, start_id,
words = xlua.unpack(
{config},
'SentenceSet',
'Stores a sequence of sentences. Each sentence is a sequence '..
'words. Each word is represented as an integer.',
{arg='which_set', type='string',
help='"train", "valid" or "test" set'},
{arg='data', type='torch.Tensor',
help='A torch.tensor with 2 columns. First col is for storing '..
'start indices of sentences. Second col is for storing the '..
'sequence of words as shuffled sentences. Sentences are '..
'only seperated by the sentence_end delimiter.', req=true},
{arg='context_size', type='number', req=true,
help='number of previous words to be used to predict the next.'},
{arg='end_id', type='number', req=true,
help='word_id of the sentence end delimiter : "</S>"'},
{arg='start_id', type='number', req=true,
help='word_id of the sentence start delimiter : "<S>"'},
{arg='words', type='table',
help='A table mapping word_ids to the original word strings'}
)
self:setWhichSet(which_set)
self._data = data
self._context_size = context_size
self._start_id = start_id
self._end_id = end_id
self._words = words
end
function SentenceSet:nSample()
return self._data:size(1)
end
function SentenceSet:setInputs(inputs)
error"Not Implemented"
end
function SentenceSet:setTargets(targets)
error"Not Implemented"
end
function SentenceSet:inputs()
error"Not Implemented"
end
function SentenceSet:targets()
error"Not Implemented"
end
-- We assume that preprocessing has already been applied
function SentenceSet:preprocess()
error"Not Implemented"
end
function SentenceSet:batch(batch_size)
return self:sub(1, batch_size)
end
function SentenceSet:sub(batch, start, stop)
local input_v, inputs, target_v, targets
if (not batch) or (not stop) then
if batch then
stop = start
start = batch
batch = nil
end
inputs = torch.IntTensor()
targets = torch.IntTensor()
input_v = dp.ClassView()
target_v = dp.ClassView()
else
input_v = batch:inputs()
inputs = input_v:input()
target_v = batch:targets()
targets = target_v:input()
end
local data = self._data:sub(start, stop)
inputs:resize(data:size(1), self._context_size)
targets:resize(data:size(1))
local words = self._data:select(2, 2)
-- fill tensor with sentence end tags : </S>
inputs:fill(self._end_id)
for i=1,data:size(1) do
local sample = data:select(1, i)
-- add input
local sample_stop = start+i-2
local sentence_start = self._context_size
if sample[1] <= sample_stop then
local sample_start = math.max(sample[1], sample_stop-self._context_size+1)
local context = words:sub(sample_start, sample_stop)
sentence_start = self._context_size-context:size(1)
inputs:select(1, i):narrow(
1, sentence_start+1, context:size(1)
):copy(context)
end
-- add sentence start tag : <S> (after sentence end tags)
if sentence_start > 0 then
inputs:select(1,i):narrow(1, sentence_start, 1):fill(self._start_id)
end
end
-- targets
targets:copy(data:select(2,2))
-- encapsulate in dp.ClassViews
input_v:forward('bt', inputs)
input_v:setClasses(self._words)
target_v:forward('b', targets)
target_v:setClasses(self._words)
return batch or dp.Batch{
which_set=self:whichSet(), epoch_size=self:nSample(),
inputs=input_v, targets=target_v
}
end
function SentenceSet:index(batch, indices)
local inputs, targets, input_v, target_v
if (not batch) or (not indices) then
indices = indices or batch
batch = nil
inputs = torch.IntTensor(indices:size(1), self._context_size)
targets = torch.IntTensor(indices:size(1))
input_v = dp.ClassView()
target_v = dp.ClassView()
else
input_v = batch:inputs()
inputs = input_v:input()
inputs:resize(indices:size(1), self._context_size)
target_v = batch:targets()
targets = target_v:input()
targets:resize(indices:size(1))
end
-- fill tensor with sentence end tags : <S>
inputs:fill(self._end_id)
-- indexSelect the data and reuse memory (optimization)
self.__index_mem = self.__index_mem or torch.IntTensor()
self.__index_mem:index(self._data, 1, indices)
local data = self.__index_mem
local words = self._data:select(2, 2)
for i=1,data:size(1) do
local sample = data:select(1, i)
-- add input
local sample_stop = indices[i]-1
local sentence_start = self._context_size
if sample[1] <= sample_stop then
local sample_start = math.max(sample[1], sample_stop-self._context_size+1)
local context = words:sub(sample_start, sample_stop)
sentence_start = self._context_size-context:size(1)
inputs:select(1, i):narrow(
1, self._context_size-context:size(1)+1, context:size(1)
):copy(context)
end
-- add sentence start tag : <S> (after sentence end tags)
if sentence_start > 0 then
inputs:select(1,i):narrow(1, sentence_start, 1):fill(self._start_id)
end
end
-- targets
targets:copy(data:select(2,2))
-- encapsulate in dp.Views
input_v:forward('bt', inputs)
input_v:setClasses(self._words)
target_v:forward('b', targets)
target_v:setClasses(self._words)
return batch or dp.Batch{
which_set=self:whichSet(), epoch_size=self:nSample(),
inputs=input_v, targets=target_v
}
end
|
------------------------------------------------------------------------
--[[ SentenceSet ]]--
-- Inherits DataSet
-- Used for Language Modeling
-- Takes a sequence of words stored as a tensor of word ids,
-- and a tensor holding the start index of the sentence of its
-- commensurate word id (the one at the same index).
-- Unlike DataSet, for memory efficiency reasons,
-- this class does not store its data in Views.
-- However, the outputs of batch(), sub(), index() are dp.Batches
-- containing ClassViews of inputs and targets.
-- The returned batch:inputs() are filled according to
-- https://code.google.com/p/1-billion-word-language-modeling-benchmark/source/browse/trunk/README.perplexity_and_such
------------------------------------------------------------------------
local SentenceSet, parent = torch.class("dp.SentenceSet", "dp.DataSet")
SentenceSet.isSentenceSet = true
function SentenceSet:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, which_set, data, context_size, end_id, start_id,
words = xlua.unpack(
{config},
'SentenceSet',
'Stores a sequence of sentences. Each sentence is a sequence '..
'words. Each word is represented as an integer.',
{arg='which_set', type='string',
help='"train", "valid" or "test" set'},
{arg='data', type='torch.Tensor',
help='A torch.tensor with 2 columns. First col is for storing '..
'start indices of sentences. Second col is for storing the '..
'sequence of words as shuffled sentences. Sentences are '..
'only seperated by the sentence_end delimiter.', req=true},
{arg='context_size', type='number', req=true,
help='number of previous words to be used to predict the next.'},
{arg='end_id', type='number', req=true,
help='word_id of the sentence end delimiter : "</S>"'},
{arg='start_id', type='number', req=true,
help='word_id of the sentence start delimiter : "<S>"'},
{arg='words', type='table',
help='A table mapping word_ids to the original word strings'}
)
self:setWhichSet(which_set)
self._data = data
self._context_size = context_size
self._start_id = start_id
self._end_id = end_id
self._words = words
end
function SentenceSet:nSample()
return self._data:size(1)
end
function SentenceSet:setInputs(inputs)
error"Not Implemented"
end
function SentenceSet:setTargets(targets)
error"Not Implemented"
end
function SentenceSet:inputs()
error"Not Implemented"
end
function SentenceSet:targets()
error"Not Implemented"
end
-- We assume that preprocessing has already been applied
function SentenceSet:preprocess()
error"Not Implemented"
end
function SentenceSet:batch(batch_size)
return self:sub(1, batch_size)
end
function SentenceSet:sub(batch, start, stop)
local input_v, inputs, target_v, targets
if (not batch) or (not stop) then
if batch then
stop = start
start = batch
batch = nil
end
inputs = torch.IntTensor()
targets = torch.IntTensor()
input_v = dp.ClassView()
target_v = dp.ClassView()
else
input_v = batch:inputs()
inputs = input_v:input()
target_v = batch:targets()
targets = target_v:input()
end
local data = self._data:sub(start, stop)
inputs:resize(data:size(1), self._context_size)
targets:resize(data:size(1))
local words = self._data:select(2, 2)
-- fill tensor with sentence end tags : </S>
inputs:fill(self._end_id)
for i=1,data:size(1) do
local sample = data:select(1, i)
-- add input
local sample_stop = start+i-2
local sentence_start = self._context_size
if sample[1] <= sample_stop then
local sample_start = math.max(sample[1], sample_stop-self._context_size+1)
local context = words:sub(sample_start, sample_stop)
sentence_start = self._context_size-context:size(1)
inputs:select(1, i):narrow(
1, sentence_start+1, context:size(1)
):copy(context)
end
-- add sentence start tag : <S> (after sentence end tags)
if sentence_start > 0 then
inputs:select(1,i):narrow(1, sentence_start, 1):fill(self._start_id)
end
end
-- targets
targets:copy(data:select(2,2))
-- encapsulate in dp.ClassViews
input_v:forward('bt', inputs)
input_v:setClasses(self._words)
target_v:forward('b', targets)
target_v:setClasses(self._words)
--print(input_v:forward('bt'))
--print(target_v:forward('b'))
return batch or dp.Batch{
which_set=self:whichSet(), epoch_size=self:nSample(),
inputs=input_v, targets=target_v
}
end
function SentenceSet:index(batch, indices)
local inputs, targets, input_v, target_v
if (not batch) or (not indices) then
indices = indices or batch
batch = nil
inputs = torch.IntTensor(indices:size(1), self._context_size)
targets = torch.IntTensor(indices:size(1))
input_v = dp.ClassView()
target_v = dp.ClassView()
else
input_v = batch:inputs()
inputs = input_v:input()
inputs:resize(indices:size(1), self._context_size)
target_v = batch:targets()
targets = target_v:input()
targets:resize(indices:size(1))
end
-- fill tensor with sentence end tags : <S>
inputs:fill(self._end_id)
-- indexSelect the data and reuse memory (optimization)
self.__index_mem = self.__index_mem or torch.LongTensor()
self.__index_mem:index(self._data, 1, indices)
local data = self.__index_mem
local words = self._data:select(2, 2)
for i=1,data:size(1) do
local sample = data:select(1, i)
-- add input
local sample_stop = indices[i]-1
local sentence_start = self._context_size
if sample[1] <= sample_stop then
local sample_start = math.max(sample[1], sample_stop-self._context_size+1)
local context = words:sub(sample_start, sample_stop)
sentence_start = self._context_size-context:size(1)
inputs:select(1, i):narrow(
1, self._context_size-context:size(1)+1, context:size(1)
):copy(context)
end
-- add sentence start tag : <S> (after sentence end tags)
if sentence_start > 0 then
inputs:select(1,i):narrow(1, sentence_start, 1):fill(self._start_id)
end
end
-- targets
targets:copy(data:select(2,2))
-- encapsulate in dp.Views
input_v:forward('bt', inputs)
input_v:setClasses(self._words)
target_v:forward('b', targets)
target_v:setClasses(self._words)
return batch or dp.Batch{
which_set=self:whichSet(), epoch_size=self:nSample(),
inputs=input_v, targets=target_v
}
end
|
Fix Int vs Long tensor issue
|
Fix Int vs Long tensor issue
|
Lua
|
bsd-3-clause
|
fiskio/dp
|
b0bc31e14b5eabd334ba78d26e69c32eefece72f
|
src_trunk/resources/job-system/trucker/c_trucker_job.lua
|
src_trunk/resources/job-system/trucker/c_trucker_job.lua
|
local blip
local jobstate = 0
local route = 0
local marker
local colshape
local routescompleted = 0
routes = { }
routes[1] = { 2648.64453125, 846.005859375, 6.1870636940002 }
routes[2] = { 2119.5634765625, 950.6748046875, 10.519774436951 }
routes[3] = { 2372.2021484375, 2548.2451171875, 10.526019096375 }
routes[4] = { 2288.5732421875, 2418.6533203125, 10.458553314209 }
routes[5] = { 2090.205078125, 2086.9130859375, 10.526629447937 }
routes[6] = { 1946.015625, 2054.931640625, 10.527263641357 }
routes[7] = { 1630.2587890625, 1797.3447265625, 10.526601791382 }
routes[8] = { 1144.14453125, 1368.0986328125, 10.434799194336 }
routes[9] = { 635.9775390625, 1252.9892578125, 11.357774734497 }
routes[10] = { 261.623046875, 1412.3564453125, 10.20871925354 }
routes[11] = { 2830.3095703125, 954.38671875, 10.75 }
function resetTruckerJob()
jobstate = 0
if (isElement(marker)) then
destroyElement(marker)
end
if (isElement(colshape)) then
destroyElement(colshape)
end
if (isElement(blip)) then
destroyElement(blip)
end
if (isElement(endmarker)) then
destroyElement(endmarker)
end
if (isElement(endcolshape)) then
destroyElement(endcolshape)
end
if (isElement(endblip)) then
destroyElement(endblip)
end
endblip = nil
end
function displayTruckerJob()
if (jobstate==0) then
jobstate = 1
blip = createBlip(2821.806640625, 954.4755859375, 10.75, 0, 4, 255, 127, 255)
outputChatBox("#FF9933Approach the #FF66CCblip#FF9933 on your radar and enter the van to start your job.", 255, 194, 15, true)
outputChatBox("#FF9933Type /startjob once you are in the van.", 255, 194, 15, true)
end
end
addCommandHandler("job", displayTruckerJob)
function startTruckerJob()
if (jobstate==1) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You must be in a van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
routescompleted = 0
outputChatBox("#FF9933Drive to the #FF66CCblip#FF9933 on the radar and use /dumpload.", 255, 194, 15, true)
destroyElement(blip)
local rand = math.random(11, 11)
route = routes[rand]
local x, y, z = routes[rand][1], routes[rand][2], routes[rand][3]
blip = createBlip(x, y, z, 0, 4, 255, 127, 255)
marker = createMarker(x, y, z, "cylinder", 4, 255, 127, 255, 150)
colshape = createColCircle(x, y, z, 4)
jobstate = 2
else
outputChatBox("You are not in a van.", 255, 0, 0)
end
end
end
end
addCommandHandler("startjob", startTruckerJob)
function dumpTruckLoad()
if (jobstate==2 or jobstate==3) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You are not in the van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
if (isElementWithinColShape(vehicle, colshape)) then
destroyElement(colshape)
destroyElement(marker)
destroyElement(blip)
outputChatBox("You completed your trucking run.", 0, 255, 0)
routescompleted = routescompleted + 1
outputChatBox("#FF9933You can now either return to the #00CC00warehouse #FF9933and obtain your wage", 0, 0, 0, true)
outputChatBox("#FF9933or continue onto the next #FF66CCdrop off point#FF9933 and increase your wage.", 0, 0, 0, true)
-- next drop off
local rand = math.random(11, 11)
route = routes[rand]
local x, y, z = routes[rand][1], routes[rand][2], routes[rand][3]
blip = createBlip(x, y, z, 0, 4, 255, 127, 255)
marker = createMarker(x, y, z, "cylinder", 4, 255, 127, 255, 150)
colshape = createColCircle(x, y, z, 4)
if not(endblip)then
-- end marker
endblip = createBlip(2836, 975, 9.75, 0, 4, 0, 255, 0)
endmarker = createMarker(2836, 975, 9.75, "cylinder", 4, 0, 255, 0, 150)
endcolshape = createColCircle(2836, 975, 9.75, 4)
addEventHandler("onClientColShapeHit", endcolshape, endTruckJob, false)
end
jobstate = 3
else
outputChatBox("#FF0066You are not at your #FF66CCdrop off point#FF0066.", 255, 0, 0, true)
end
else
outputChatBox("You are not in a van.", 255, 0, 0)
end
end
end
end
addCommandHandler("dumpload", dumpTruckLoad)
function endTruckJob(theElement)
if (theElement==localPlayer) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You are not in the van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
if (jobstate==3) then
local wage = 50*routescompleted
outputChatBox("You earned $" .. wage .. " on your trucking runs.", 255, 194, 15)
triggerServerEvent("giveTruckingMoney", localPlayer, wage)
end
triggerServerEvent("respawnTruck", localPlayer, vehicle)
outputChatBox("Thank you for your services to RS Haul.", 0, 255, 0)
destroyElement(colshape)
destroyElement(marker)
destroyElement(blip)
destroyElement(endblip)
destroyElement(endmarker)
destroyElement(endcolshape)
endblip = nil
routescompleted = 0
jobstate = 0
displayTruckerJob()
else
outputChatBox("You are not in the van.", 255, 0, 0)
end
end
end
end
|
local blip
local jobstate = 0
local route = 0
local marker
local colshape
local routescompleted = 0
routes = { }
routes[1] = { 2648.64453125, 846.005859375, 6.1870636940002 }
routes[2] = { 2119.5634765625, 950.6748046875, 10.519774436951 }
routes[3] = { 2372.2021484375, 2548.2451171875, 10.526019096375 }
routes[4] = { 2288.5732421875, 2418.6533203125, 10.458553314209 }
routes[5] = { 2090.205078125, 2086.9130859375, 10.526629447937 }
routes[6] = { 1946.015625, 2054.931640625, 10.527263641357 }
routes[7] = { 1630.2587890625, 1797.3447265625, 10.526601791382 }
routes[8] = { 1144.14453125, 1368.0986328125, 10.434799194336 }
routes[9] = { 635.9775390625, 1252.9892578125, 11.357774734497 }
routes[10] = { 261.623046875, 1412.3564453125, 10.20871925354 }
function resetTruckerJob()
jobstate = 0
if (isElement(marker)) then
destroyElement(marker)
end
if (isElement(colshape)) then
destroyElement(colshape)
end
if (isElement(blip)) then
destroyElement(blip)
end
if (isElement(endmarker)) then
destroyElement(endmarker)
end
if (isElement(endcolshape)) then
destroyElement(endcolshape)
end
if (isElement(endblip)) then
destroyElement(endblip)
end
endblip = nil
end
function displayTruckerJob()
if (jobstate==0) then
jobstate = 1
blip = createBlip(2821.806640625, 954.4755859375, 10.75, 0, 4, 255, 127, 255)
outputChatBox("#FF9933Approach the #FF66CCblip#FF9933 on your radar and enter the van to start your job.", 255, 194, 15, true)
outputChatBox("#FF9933Type /startjob once you are in the van.", 255, 194, 15, true)
end
end
addCommandHandler("job", displayTruckerJob)
function startTruckerJob()
if (jobstate==1) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You must be in a van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
routescompleted = 0
outputChatBox("#FF9933Drive to the #FF66CCblip#FF9933 on the radar and use /dumpload.", 255, 194, 15, true)
destroyElement(blip)
local rand = math.random(1, 10)
route = routes[rand]
local x, y, z = routes[rand][1], routes[rand][2], routes[rand][3]
blip = createBlip(x, y, z, 0, 4, 255, 127, 255)
marker = createMarker(x, y, z, "cylinder", 4, 255, 127, 255, 150)
colshape = createColCircle(x, y, z, 4)
jobstate = 2
else
outputChatBox("You are not in a van.", 255, 0, 0)
end
end
end
end
addCommandHandler("startjob", startTruckerJob)
function dumpTruckLoad()
if (jobstate==2 or jobstate==3) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You are not in the van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
if (isElementWithinColShape(vehicle, colshape)) then
destroyElement(colshape)
destroyElement(marker)
destroyElement(blip)
outputChatBox("You completed your trucking run.", 0, 255, 0)
routescompleted = routescompleted + 1
outputChatBox("#FF9933You can now either return to the #00CC00warehouse #FF9933and obtain your wage", 0, 0, 0, true)
outputChatBox("#FF9933or continue onto the next #FF66CCdrop off point#FF9933 and increase your wage.", 0, 0, 0, true)
-- next drop off
local rand = math.random(11, 11)
route = routes[rand]
local x, y, z = routes[rand][1], routes[rand][2], routes[rand][3]
blip = createBlip(x, y, z, 0, 4, 255, 127, 255)
marker = createMarker(x, y, z, "cylinder", 4, 255, 127, 255, 150)
colshape = createColCircle(x, y, z, 4)
if not(endblip)then
-- end marker
endblip = createBlip(2836, 975, 9.75, 0, 4, 0, 255, 0)
endmarker = createMarker(2836, 975, 9.75, "cylinder", 4, 0, 255, 0, 150)
endcolshape = createColCircle(2836, 975, 9.75, 4)
addEventHandler("onClientColShapeHit", endcolshape, endTruckJob, false)
end
jobstate = 3
else
outputChatBox("#FF0066You are not at your #FF66CCdrop off point#FF0066.", 255, 0, 0, true)
end
else
outputChatBox("You are not in a van.", 255, 0, 0)
end
end
end
end
addCommandHandler("dumpload", dumpTruckLoad)
function endTruckJob(theElement)
if (theElement==localPlayer) then
local vehicle = getPedOccupiedVehicle(localPlayer)
if not (vehicle) then
outputChatBox("You are not in the van.", 255, 0, 0)
else
local model = getElementModel(vehicle)
if (model==414) then -- MULE
if (jobstate==3) then
local wage = 50*routescompleted
outputChatBox("You earned $" .. wage .. " on your trucking runs.", 255, 194, 15)
triggerServerEvent("giveTruckingMoney", localPlayer, wage)
end
triggerServerEvent("respawnTruck", localPlayer, vehicle)
outputChatBox("Thank you for your services to RS Haul.", 0, 255, 0)
destroyElement(colshape)
destroyElement(marker)
destroyElement(blip)
destroyElement(endblip)
destroyElement(endmarker)
destroyElement(endcolshape)
endblip = nil
routescompleted = 0
jobstate = 0
displayTruckerJob()
else
outputChatBox("You are not in the van.", 255, 0, 0)
end
end
end
end
|
Fixed trucker job
|
Fixed trucker job
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@697 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
5c7d0f9409d53c0dce4ae5f1ee783ce84c26ea38
|
Knapsack/Lua/Yonaba/knapsack.lua
|
Knapsack/Lua/Yonaba/knapsack.lua
|
-- Knapsack problem algorithm implementation
-- See: http://en.wikipedia.org/wiki/Knapsack_problem
-- Pops value at the head of an array
local function pop(s)
local head = s[1]
table.remove(s, 1)
return head
end
-- Note: the items to be passed should be represented this way
-- items = {
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- ...
-- }
-- In the returned output, each item will receive a new attribute 'p'
-- referring to how much (percentage) of the item has been added into
-- the knapsack.
-- Performs fractional Knapsack. Fractional here means we can
-- select a portion of a item. With that respect, this implementation
-- is greedy.
-- items : an array of items (see note before). This array will be
-- sorted regarding their benefits in decreasing order.
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function fractionalKnapsack(items, capacity)
table.sort(items, function(a, b) return a.b > b.b end)
local inKnapsack, profit = {}, 0
while capacity > 0 do
local max_item = pop(items)
max_item.p = max_item.w > capacity and capacity/max_item.w or 1
max_item.b = max_item.p * max_item.b
max_item.w = max_item.p * max_item.w
capacity = capacity - max_item.w
table.insert(inKnapsack, max_item)
profit = profit + max_item.b
end
return inKnapsack, profit
end
-- Performs standard 0/1 Knapsack, meaning that an item is either
-- picked or not. This implementation uses dynamic programming.
-- items : an array of items (see note before).
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function integerKnapsack(items, capacity
-- Get the count of items
local numOfItems = #items
-- Auxiliary tables for dynamic search and selected items tracking
local V, K = {}, {}
-- Inits auxiliary tables with 0's. Note that although
-- Lua's arrays start at 1, we start looping at 0
for i = 0, numOfItems do
V[i], K[i] = {}, {}
for w = 0, capacity do
V[i][w], K[i][w] = 0, 0
end
end
-- Dynamic search
for i = 1, numOfItems do
local item = items[i]
for w = 0, capacity do
if item.w < w
and (item.b + V[i - 1][w - item.w] > V[i - 1][w]) then
V[i][w] = item.b + V[i-1][w - item.w]
K[i][w] = 1
else
V[i][w] = V[i - 1][w]
K[i][w] = 0
end
end
end
-- Process auxiliary tables to identify
-- selected items and evaluate the profit
local inKnapsack, profit = {}, 0
for i = numOfItems, 1, -1 do
local item = items[i]
if K[i][capacity] == 1 then
table.insert(inKnapsack, item)
capacity = capacity - item.w
profit = profit + item.b
end
end
return inKnapsack, profit
end
return {
fractional = fractionalKnapsack,
integer = integerKnapsack
}
|
-- Knapsack problem algorithm implementation
-- See: http://en.wikipedia.org/wiki/Knapsack_problem
-- Pops value at the head of an array
local function pop(s)
local head = s[1]
table.remove(s, 1)
return head
end
-- Note: the items to be passed should be represented this way
-- items = {
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- ...
-- }
-- In the returned output, each item will receive a new attribute 'p'
-- referring to how much (percentage) of the item has been added into
-- the knapsack.
-- Performs fractional Knapsack. Fractional here means we can
-- select a portion of a item. With that respect, this implementation
-- is greedy.
-- items : an array of items (see note before). This array will be
-- sorted regarding their benefits in decreasing order.
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function fractionalKnapsack(items, capacity)
table.sort(items, function(a, b) return a.b > b.b end)
local inKnapsack, profit = {}, 0
while capacity > 0 do
local max_item = pop(items)
max_item.p = max_item.w > capacity and capacity/max_item.w or 1
max_item.b = max_item.p * max_item.b
max_item.w = max_item.p * max_item.w
capacity = capacity - max_item.w
table.insert(inKnapsack, max_item)
profit = profit + max_item.b
end
return inKnapsack, profit
end
-- Performs standard 0/1 Knapsack, meaning that an item is either
-- picked or not. This implementation uses dynamic programming.
-- items : an array of items (see note before).
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function integerKnapsack(items, capacity)
-- Get the count of items
local numOfItems = #items
-- Auxiliary tables for dynamic search and selected items tracking
local V, K = {}, {}
-- Inits auxiliary tables with 0's. Note that although
-- Lua's arrays start at 1, we start looping at 0
for i = 0, numOfItems do
V[i], K[i] = {}, {}
for w = 0, capacity do
V[i][w], K[i][w] = 0, 0
end
end
-- Dynamic search
for i = 1, numOfItems do
local item = items[i]
for w = 0, capacity do
if item.w < w
and (item.b + V[i - 1][w - item.w] > V[i - 1][w]) then
V[i][w] = item.b + V[i-1][w - item.w]
K[i][w] = 1
else
V[i][w] = V[i - 1][w]
K[i][w] = 0
end
end
end
-- Process auxiliary tables to identify
-- selected items and evaluate the profit
local inKnapsack, profit = {}, 0
for i = numOfItems, 1, -1 do
local item = items[i]
if K[i][capacity] == 1 then
table.insert(inKnapsack, item)
capacity = capacity - item.w
profit = profit + item.b
end
end
return inKnapsack, profit
end
return {
fractional = fractionalKnapsack,
integer = integerKnapsack
}
|
Fixed indentation (tabs to 2-spaces)
|
Fixed indentation (tabs to 2-spaces)
|
Lua
|
mit
|
kidaa/Algorithm-Implementations,Endika/Algorithm-Implementations,kennyledet/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,movb/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,warreee/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jiang42/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Etiene/Algorithm-Implementations,girishramnani/Algorithm-Implementations,rohanp/Algorithm-Implementations,imanmafi/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,joshimoo/Algorithm-Implementations,rohanp/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jb1717/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imanmafi/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,vikas17a/Algorithm-Implementations,movb/Algorithm-Implementations,mishin/Algorithm-Implementations,girishramnani/Algorithm-Implementations,mishin/Algorithm-Implementations,Endika/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,jiang42/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,jb1717/Algorithm-Implementations,pravsingh/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kidaa/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jb1717/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Etiene/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,joshimoo/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,rohanp/Algorithm-Implementations,mishin/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,warreee/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Etiene/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,joshimoo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,warreee/Algorithm-Implementations,Endika/Algorithm-Implementations,Yonaba/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jb1717/Algorithm-Implementations,Endika/Algorithm-Implementations,mishin/Algorithm-Implementations,kidaa/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Yonaba/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kennyledet/Algorithm-Implementations,girishramnani/Algorithm-Implementations,rohanp/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,mishin/Algorithm-Implementations,joshimoo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,isalnikov/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,warreee/Algorithm-Implementations,rohanp/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,mishin/Algorithm-Implementations,kidaa/Algorithm-Implementations,pravsingh/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kidaa/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Etiene/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Etiene/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,isalnikov/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Endika/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imanmafi/Algorithm-Implementations,mishin/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Yonaba/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,jiang42/Algorithm-Implementations,Etiene/Algorithm-Implementations,jiang42/Algorithm-Implementations,kidaa/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,kidaa/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kennyledet/Algorithm-Implementations,rohanp/Algorithm-Implementations,isalnikov/Algorithm-Implementations,isalnikov/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jiang42/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,warreee/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,jb1717/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,warreee/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,pravsingh/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jb1717/Algorithm-Implementations,isalnikov/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,vikas17a/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,movb/Algorithm-Implementations,isalnikov/Algorithm-Implementations,kidaa/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,rohanp/Algorithm-Implementations,kidaa/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Endika/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,movb/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,isalnikov/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jiang42/Algorithm-Implementations,Endika/Algorithm-Implementations,rohanp/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Etiene/Algorithm-Implementations,girishramnani/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,warreee/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Yonaba/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,joshimoo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,movb/Algorithm-Implementations,isalnikov/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,jb1717/Algorithm-Implementations,isalnikov/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Endika/Algorithm-Implementations,Endika/Algorithm-Implementations,joshimoo/Algorithm-Implementations,warreee/Algorithm-Implementations,Yonaba/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,kennyledet/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,jb1717/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imanmafi/Algorithm-Implementations,mishin/Algorithm-Implementations,jiang42/Algorithm-Implementations,jiang42/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,movb/Algorithm-Implementations,jiang42/Algorithm-Implementations,kidaa/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,mishin/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,vikas17a/Algorithm-Implementations,joshimoo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kidaa/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imanmafi/Algorithm-Implementations,warreee/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,joshimoo/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,girishramnani/Algorithm-Implementations,warreee/Algorithm-Implementations,warreee/Algorithm-Implementations,vikas17a/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,jb1717/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,movb/Algorithm-Implementations,kennyledet/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imanmafi/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,rohanp/Algorithm-Implementations,kennyledet/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jb1717/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,Etiene/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,movb/Algorithm-Implementations,jb1717/Algorithm-Implementations,pravsingh/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,movb/Algorithm-Implementations,joshimoo/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,mishin/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,Etiene/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,rohanp/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,kidaa/Algorithm-Implementations,Endika/Algorithm-Implementations,mishin/Algorithm-Implementations,jiang42/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,warreee/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,mishin/Algorithm-Implementations,jb1717/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,movb/Algorithm-Implementations,movb/Algorithm-Implementations,rohanp/Algorithm-Implementations,rohanp/Algorithm-Implementations,varunparkhe/Algorithm-Implementations
|
d19119bb89d91225b3b6bc7fe9d537a05bf6495d
|
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 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
local os_time = os.time
local nodeprep = require "util.encodings".stringprep.nodeprep
module:depends("http")
module:set_global()
-- Pick up configuration.
local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted")
local base_path = module:get_option_string("reg_servlet_base", "/register_account/")
local throttle_time = module:get_option_number("reg_servlet_ttime", nil)
local whitelist = module:get_option_set("reg_servlet_wl", {})
local blacklist = module:get_option_set("reg_servlet_bl", {})
local recent_ips = {}
-- Begin
local function http_response(event, code, message, headers)
local response = event.response
if headers then
for header, data in pairs(headers) do response.headers[header] = data end
end
response.headers.content_type = "application/json"
response.status_code = code
response:send(message)
end
local function handle_req(event)
local request = event.request
local body = request.body
if request.method ~= "POST" then
return http_response(event, 405, "Bad method...", {["Allow"] = "POST"})
end
if not request.headers["authorization"] then
return http_response(event, 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(event, 400, "What's this..?") end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(event, 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(event, 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(event, 400, "JSON Decoding failed.")
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body)
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user)
return http_response(event, 400, "Invalid syntax.")
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(event, 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:contains(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:contains(req_body["ip"]) then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = os_time()
else
if os_time() - recent_ips[req_body["ip"]] < throttle_time then
recent_ips[req_body["ip"]] = 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
recent_ips[req_body["ip"]] = os_time()
end
end
-- We first check if the supplied username for registration is already there.
-- And nodeprep the username
local username = nodeprep(req_body["username"])
if not usermanager.user_exists(username, req_body["host"]) then
if not username then
module:log("debug", "%s supplied an username containing invalid characters: %s", user, username)
return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.")
else
local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"])
if ok then
hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } })
module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"])
return http_response(event, 200, "Done.")
else
module:log("error", "user creation failed: "..error)
return http_response(event 500, "Encountered server error while creating the user: "..error)
end
end
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username)
return http_response(event, 409, "User already exists.")
end
end
end
end
-- Set it up!
module:provides("http", {
default_path = base_path,
route = {
["GET /"] = handle_req,
["POST /"] = handle_req
}
})
|
-- 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
local os_time = os.time
local nodeprep = require "util.encodings".stringprep.nodeprep
module:depends("http")
module:set_global()
-- Pick up configuration.
local secure = module:get_option_boolean("reg_servlet_secure", true)
local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted")
local base_path = module:get_option_string("reg_servlet_base", "/register_account/")
local throttle_time = module:get_option_number("reg_servlet_ttime", nil)
local whitelist = module:get_option_set("reg_servlet_wl", {})
local blacklist = module:get_option_set("reg_servlet_bl", {})
local recent_ips = {}
-- Begin
local function http_response(event, code, message, headers)
local response = event.response
if headers then
for header, data in pairs(headers) do response.headers[header] = data end
end
response.headers.content_type = "application/json"
response.status_code = code
response:send(message)
end
local function handle_req(event)
local request = event.request
local body = request.body
if request.method ~= "POST" then
return http_response(event, 405, "Bad method...", {["Allow"] = "POST"})
end
if not request.headers["authorization"] then
return http_response(event, 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(event, 400, "What's this..?") end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(event, 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(event, 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(event, 400, "JSON Decoding failed.")
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body)
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user)
return http_response(event, 400, "Invalid syntax.")
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(event, 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:contains(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:contains(req_body["ip"]) then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = os_time()
else
if os_time() - recent_ips[req_body["ip"]] < throttle_time then
recent_ips[req_body["ip"]] = 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
recent_ips[req_body["ip"]] = os_time()
end
end
-- We first check if the supplied username for registration is already there.
-- And nodeprep the username
local username = nodeprep(req_body["username"])
if not usermanager.user_exists(username, req_body["host"]) then
if not username then
module:log("debug", "%s supplied an username containing invalid characters: %s", user, username)
return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.")
else
local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"])
if ok then
hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } })
module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"])
return http_response(event, 200, "Done.")
else
module:log("error", "user creation failed: "..error)
return http_response(event, 500, "Encountered server error while creating the user: "..error)
end
end
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username)
return http_response(event, 409, "User already exists.")
end
end
end
end
-- Set it up!
module:provides((secure and "https" or "http"), {
default_path = base_path,
route = {
["GET /"] = handle_req,
["POST /"] = handle_req
}
})
|
mod_register_json: fixed typo, added https/http switch and default value to it.
|
mod_register_json: fixed typo, added https/http switch and default value to it.
|
Lua
|
mit
|
drdownload/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,heysion/prosody-modules,either1/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,joewalker/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,prosody-modules/import,mmusial/prosody-modules,mmusial/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,apung/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,heysion/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,either1/prosody-modules,iamliqiang/prosody-modules,softer/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules
|
216ccfd52cb0f0ef3c2f9135bc198fd6ab7cfb0d
|
mods/00_bt_mobs/mobs_animal/penguin.lua
|
mods/00_bt_mobs/mobs_animal/penguin.lua
|
local S = mobs.intllib
-- Penguin by D00Med
mobs:register_mob("mobs_animal:penguin", {
type = "animal",
passive = true,
reach = 1,
hp_min = 5,
hp_max = 10,
armor = 200,
collisionbox = {-0.2, -0.0, -0.2, 0.2, 0.5, 0.2},
visual = "mesh",
mesh = "mobs_penguin.b3d",
visual_size = {x = 0.25, y = 0.25},
textures = {
{"mobs_penguin.png"},
},
sounds = {},
makes_footstep_sound = true,
walk_velocity = 1,
run_velocity = 2,
runaway = true,
jump = false,
stepheight = 1.1,
drops = {
{name = "mobs:meat_raw", chance = 3, min = 1, max = 1},
},
water_damage = 0,
lava_damage = 4,
light_damage = 0,
fear_height = 2,
animation = {
speed_normal = 15,
stand_start = 1,
stand_end = 20,
walk_start = 25,
walk_end = 45,
fly_start = 75, -- swim animation
fly_end = 95,
-- 50-70 is slide/water idle
},
fly_in = "default:water_source",
floats = 0,
follow = {"ethereal:fish_raw"},
view_range = 5,
on_rightclick = function(self, clicker)
-- feed or tame
if mobs:feed_tame(self, clicker, 4, false, true) then
return
end
mobs:protect(self, clicker)
mobs:capture_mob(self, clicker, 5, 50, 80, false, nil)
end,
})
mobs:spawn({
name = "mobs_animal:penguin",
nodes = {"default:snowblock"},
min_light = 10,
chance = 400000,
min_height = 0,
day_toggle = true,
})
mobs:register_egg("mobs_animal:penguin", S("Penguin"), "default_snow.png", 1)
|
local S = mobs.intllib
-- Penguin by D00Med
mobs:register_mob("mobs_animal:penguin", {
type = "animal",
passive = true,
reach = 1,
hp_min = 5,
hp_max = 10,
armor = 200,
collisionbox = {-0.2, -0.0, -0.2, 0.2, 0.5, 0.2},
visual = "mesh",
mesh = "mobs_penguin.b3d",
visual_size = {x = 0.25, y = 0.25},
textures = {
{"mobs_penguin.png"},
},
sounds = {},
makes_footstep_sound = true,
walk_velocity = 1,
run_velocity = 2,
runaway = true,
jump = false,
stepheight = 1.1,
drops = {
{name = "mobs:meat_raw", chance = 3, min = 1, max = 1},
},
water_damage = 0,
lava_damage = 4,
light_damage = 0,
fear_height = 2,
animation = {
speed_normal = 15,
stand_start = 1,
stand_end = 20,
walk_start = 25,
walk_end = 45,
fly_start = 75, -- swim animation
fly_end = 95,
-- 50-70 is slide/water idle
},
fly_in = "default:water_source",
floats = 0,
follow = {"mobs_animal:rat", "fishing:bluewhite_raw", "fishing:carp_raw", "fishing:catfish_raw", "fishing:clownfish_raw", "fishing:exoticfish_raw",
"fishing:fish_cooked", "fishing:fish_raw", "fishing:perch_raw", "fishing:pike_cooked", "fishing:pike_raw"},
view_range = 5,
on_rightclick = function(self, clicker)
-- feed or tame
if mobs:feed_tame(self, clicker, 4, false, true) then
return
end
mobs:protect(self, clicker)
mobs:capture_mob(self, clicker, 5, 50, 80, false, nil)
end,
})
mobs:spawn({
name = "mobs_animal:penguin",
nodes = {"default:snowblock"},
min_light = 10,
chance = 400000,
min_height = 0,
day_toggle = true,
})
mobs:register_egg("mobs_animal:penguin", S("Penguin"), "default_snow.png", 1)
|
Fixed pengiuns to now follow fishing mod fish instead of ethereal
|
Fixed pengiuns to now follow fishing mod fish instead of ethereal
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
837036f51eda102e4d5e33f677f6a928ba328c4a
|
lib/resty/kafka/broker.lua
|
lib/resty/kafka/broker.lua
|
-- Copyright (C) Dejiang Zhu(doujiang24)
local response = require "resty.kafka.response"
local to_int32 = response.to_int32
local setmetatable = setmetatable
local tcp = ngx.socket.tcp
local _M = { _VERSION = "0.01" }
local mt = { __index = _M }
function _M.new(self, host, port, socket_config)
return setmetatable({
host = host,
port = port,
config = socket_config,
}, mt)
end
function _M.send_receive(self, request)
local sock, err = tcp()
if not sock then
return nil, err, true
end
local ok, err = sock:connect(self.host, self.port)
if not ok then
return nil, err, true
end
sock:settimeout(self.config.socket_timeout)
local bytes, err = sock:send(request:package())
if not bytes then
return nil, err
end
local data, err = sock:receive(4)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
local len = to_int32(data)
local data, err = sock:receive(len)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
sock:setkeepalive(self.config.keepalive_timeout, self.config.keepalive_size)
return response:new(data), nil, true
end
return _M
|
-- Copyright (C) Dejiang Zhu(doujiang24)
local response = require "resty.kafka.response"
local to_int32 = response.to_int32
local setmetatable = setmetatable
local tcp = ngx.socket.tcp
local _M = { _VERSION = "0.01" }
local mt = { __index = _M }
function _M.new(self, host, port, socket_config)
return setmetatable({
host = host,
port = port,
config = socket_config,
}, mt)
end
function _M.send_receive(self, request)
local sock, err = tcp()
if not sock then
return nil, err, true
end
sock:settimeout(self.config.socket_timeout)
local ok, err = sock:connect(self.host, self.port)
if not ok then
return nil, err, true
end
local bytes, err = sock:send(request:package())
if not bytes then
return nil, err
end
local data, err = sock:receive(4)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
local len = to_int32(data)
local data, err = sock:receive(len)
if not data then
if err == "timeout" then
sock:close()
end
return nil, err
end
sock:setkeepalive(self.config.keepalive_timeout, self.config.keepalive_size)
return response:new(data), nil, true
end
return _M
|
bugfix: should settimeout before connect
|
bugfix: should settimeout before connect
|
Lua
|
bsd-3-clause
|
doujiang24/lua-resty-kafka,wzb56/lua-resty-kafka,wangfakang/lua-resty-kafka
|
71e37fa5df286eb189fd1c2ae87089cb355fb25e
|
lua/decoders/json_decoder.lua
|
lua/decoders/json_decoder.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Parses a payload containing JSON. Does not modify any Heka message
attributes, only adds to the `Fields`.
Config:
- type (string, optional, default json):
Sets the message 'Type' header to the specified value
- strict (boolean, optional, default true):
Should we assume that the entire payload is json parsable. When set to
`false` non-json string in the payload are added to `_prefix` and `_postfix`
fields respectively.
*Example Heka Configuration*
.. code-block:: ini
[LogInput]
type = "LogstreamerInput"
log_directory = "/var/log"
file_match = 'application\.json'
decoder = "JsonDecoder"
[JsonDecoder]
type = "SandboxDecoder"
filename = "lua_decoders/json_decoder.lua"
[JsonDecoder.config]
type = "json"
strict = true
--]]
require "cjson"
require "string"
local msg_type = read_config("type") or 'json'
local strict_parsing = read_config("strict")
if strict_parsing == nil or strict_parsing == '' then
strict_parsing = true
end
function process_message()
local payload = read_message("Payload")
local ok, json = pcall(cjson.decode, payload)
local prefix = ''
local postfix = ''
if strict_parsing and not ok then
return -1
elseif not ok then
-- try parsing once more by stripping extra content on beg and end
local json_start = string.find(payload, "{")
local json_end = string.match(payload, '^.*()}')
if json_start == nil or json_end == nil then
return -1
end
prefix = string.sub(payload, 0, json_start-1)
postfix = string.sub(payload, json_end+1)
ok, json = pcall(cjson.decode, string.sub(payload, json_start, json_end))
end
if not ok then return -1 end
if type(json) ~= "table" then return -1 end
write_message("Fields[_prefix]", prefix)
write_message("Fields[_postfix]", postfix)
for k, v in pairs(json) do
-- nested json strings are not supported, stringify them
if type(v) == "table" then
v = json.encode(v)
end
write_message("Fields[" .. k .. "]", v)
end
write_message("Type", msg_type)
return 0
end
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Parses a payload containing JSON. Does not modify any Heka message
attributes, only adds to the `Fields`.
Config:
- type (string, optional, default json):
Sets the message 'Type' header to the specified value
- strict (boolean, optional, default true):
Should we assume that the entire payload is json parsable. When set to
`false` non-json string in the payload are added to `_prefix` and `_postfix`
fields respectively.
*Example Heka Configuration*
.. code-block:: ini
[LogInput]
type = "LogstreamerInput"
log_directory = "/var/log"
file_match = 'application\.json'
decoder = "JsonDecoder"
[JsonDecoder]
type = "SandboxDecoder"
filename = "lua_decoders/json_decoder.lua"
[JsonDecoder.config]
type = "json"
strict = true
--]]
require "cjson"
require "string"
local msg_type = read_config("type") or 'json'
local strict_parsing = read_config("strict")
if strict_parsing == nil or strict_parsing == '' then
strict_parsing = true
end
function process_message()
local payload = read_message("Payload")
local ok, json = pcall(cjson.decode, payload)
local prefix = ''
local postfix = ''
if strict_parsing and not ok then
return -1
elseif not ok then
-- try parsing once more by stripping extra content on beg and end
local json_start = string.find(payload, "{")
local json_end = string.match(payload, '^.*()}')
if json_start == nil or json_end == nil then
return -1
end
prefix = string.sub(payload, 0, json_start-1)
postfix = string.sub(payload, json_end+1)
ok, json = pcall(cjson.decode, string.sub(payload, json_start, json_end))
end
if not ok then return -1 end
if type(json) ~= "table" then return -1 end
write_message("Payload", cjson.encode(json))
write_message("Fields[_prefix]", prefix)
write_message("Fields[_postfix]", postfix)
for k, v in pairs(json) do
-- nested json strings are not supported, stringify them
if type(v) == "table" then
write_message("Fields[" .. k .. "]", cjson.encode(v))
else
write_message("Fields[" .. k .. "]", v)
end
end
write_message("Type", msg_type)
return 0
end
|
modify payload, also fix nested objects
|
modify payload, also fix nested objects
|
Lua
|
apache-2.0
|
wxdublin/heka-clever-plugins
|
ffda2bd2587543f7083740713a3083b9922dd991
|
lua/entities/gmod_wire_turret.lua
|
lua/entities/gmod_wire_turret.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if ( CLIENT ) then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if ( phys:IsValid() ) then
phys:Wake()
end
-- Allocating internal values on initialize
self.NextShot = 0
self.Firing = false
self.spreadvector = Vector()
self.effectdata = EffectData()
self.Inputs = WireLib.CreateSpecialInputs(self,
{ "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" },
{ "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if ( self.sound ) then
self:EmitSound( self.sound )
end
-- Get the muzzle attachment (this is pretty much always 1)
local Attachment = self:GetAttachment( 1 )
-- Get the shot angles and stuff.
local shootOrigin = Attachment.Pos + self:GetVelocity() * engine.TickInterval()
local shootAngles = self:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spreadvector
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
bullet.Callback = function(attacker, traceres, cdamageinfo)
WireLib.TriggerOutput(self, "HitEntity", traceres.Entity)
end
self:FireBullets( bullet )
-- Make a muzzle flash
self.effectdata:SetOrigin( shootOrigin )
self.effectdata:SetAngles( shootAngles )
self.effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", self.effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
BaseClass.Think( self )
if ( self.Firing ) then
self:FireShot()
end
self:NextThink( CurTime() )
return true
end
local ValidTracers = {
["Tracer"] = true,
["AR2Tracer"] = true,
["ToolTracer"] = true,
["GaussTracer"] = true,
["LaserTracer"] = true,
["StriderTracer"] = true,
["GunshipTracer"] = true,
["HelicopterTracer"] = true,
["AirboatGunTracer"] = true,
["AirboatGunHeavyTracer"] = true,
[""] = true
}
function ENT:SetSound( sound )
sound = string.Trim( tostring( sound or "" ) ) -- Remove whitespace ( manual )
local check = string.find( sound, "[\"?]" ) -- Preventing client crashes
self.sound = check == nil and sound ~= "" and sound or nil -- Apply the pattern check
end
function ENT:SetDelay( delay )
local check = game.SinglePlayer() -- clamp delay if it's not single player
local limit = check and 0.01 or 0.05
self.delay = math.Clamp( delay, limit, 1 )
end
function ENT:SetNumBullets( numbullets )
local check = game.SinglePlayer() -- clamp num bullets if it's not single player
local limit = math.floor( math.max( 1, numbullets ) )
self.numbullets = check and limit or math.Clamp( limit, 1, 10 )
end
function ENT:SetTracer( tracer )
local tracer = string.Trim(tracer)
self.tracer = ValidTracers[tracer] and tracer or ""
end
function ENT:SetSpread( spread )
self.spread = math.Clamp( spread, 0, 1 )
self.spreadvector.x = self.spread
self.spreadvector.y = self.spread
end
function ENT:SetDamage( damage )
self.damage = math.Clamp( damage, 0, 100 )
end
function ENT:SetForce( force )
self.force = math.Clamp( force, 0, 500 )
end
function ENT:SetTraceNum( tracernum )
self.tracernum = math.floor( math.max( tracernum or 1 ) )
end
function ENT:TriggerInput( iname, value )
if (iname == "Fire") then
self.Firing = value > 0
elseif (iname == "Force") then
self:SetForce( value )
elseif (iname == "Damage") then
self:SetDamage( value )
elseif (iname == "NumBullets") then
self:SetNumBullets( value )
elseif (iname == "Spread") then
self:SetSpread( value )
elseif (iname == "Delay") then
self:SetDelay( value )
elseif (iname == "Sound") then
self:SetSound( value )
elseif (iname == "Tracer") then
self:SetTracer( value )
end
end
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
self:SetForce(force)
self:SetDelay(delay)
self:SetSound(sound)
self:SetDamage(damage)
self:SetSpread(spread)
self:SetTracer(tracer)
self:SetTraceNum(tracernum)
self:SetNumBullets(numbullets)
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if ( CLIENT ) then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if ( phys:IsValid() ) then
phys:Wake()
end
-- Allocating internal values on initialize
self.NextShot = 0
self.Firing = false
self.spreadvector = Vector()
self.effectdata = EffectData()
self.attachmentPos = phys:WorldToLocal(self:GetAttachment(1).Pos)
self.Inputs = WireLib.CreateSpecialInputs(self,
{ "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" },
{ "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if ( self.sound ) then
self:EmitSound( self.sound )
end
local phys = self:GetPhysicsObject()
local shootOrigin = phys:LocalToWorld(self.attachmentPos)
local shootAngles = phys:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spreadvector
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
bullet.Callback = function(attacker, traceres, cdamageinfo)
WireLib.TriggerOutput(self, "HitEntity", traceres.Entity)
end
self:FireBullets( bullet )
-- Make a muzzle flash
self.effectdata:SetOrigin( shootOrigin )
self.effectdata:SetAngles( shootAngles )
self.effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", self.effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
BaseClass.Think( self )
if ( self.Firing ) then
self:FireShot()
end
self:NextThink( CurTime() )
return true
end
local ValidTracers = {
["Tracer"] = true,
["AR2Tracer"] = true,
["ToolTracer"] = true,
["GaussTracer"] = true,
["LaserTracer"] = true,
["StriderTracer"] = true,
["GunshipTracer"] = true,
["HelicopterTracer"] = true,
["AirboatGunTracer"] = true,
["AirboatGunHeavyTracer"] = true,
[""] = true
}
function ENT:SetSound( sound )
sound = string.Trim( tostring( sound or "" ) ) -- Remove whitespace ( manual )
local check = string.find( sound, "[\"?]" ) -- Preventing client crashes
self.sound = check == nil and sound ~= "" and sound or nil -- Apply the pattern check
end
function ENT:SetDelay( delay )
local check = game.SinglePlayer() -- clamp delay if it's not single player
local limit = check and 0.01 or 0.05
self.delay = math.Clamp( delay, limit, 1 )
end
function ENT:SetNumBullets( numbullets )
local check = game.SinglePlayer() -- clamp num bullets if it's not single player
local limit = math.floor( math.max( 1, numbullets ) )
self.numbullets = check and limit or math.Clamp( limit, 1, 10 )
end
function ENT:SetTracer( tracer )
local tracer = string.Trim(tracer)
self.tracer = ValidTracers[tracer] and tracer or ""
end
function ENT:SetSpread( spread )
self.spread = math.Clamp( spread, 0, 1 )
self.spreadvector.x = self.spread
self.spreadvector.y = self.spread
end
function ENT:SetDamage( damage )
self.damage = math.Clamp( damage, 0, 100 )
end
function ENT:SetForce( force )
self.force = math.Clamp( force, 0, 500 )
end
function ENT:SetTraceNum( tracernum )
self.tracernum = math.floor( math.max( tracernum or 1 ) )
end
function ENT:TriggerInput( iname, value )
if (iname == "Fire") then
self.Firing = value > 0
elseif (iname == "Force") then
self:SetForce( value )
elseif (iname == "Damage") then
self:SetDamage( value )
elseif (iname == "NumBullets") then
self:SetNumBullets( value )
elseif (iname == "Spread") then
self:SetSpread( value )
elseif (iname == "Delay") then
self:SetDelay( value )
elseif (iname == "Sound") then
self:SetSound( value )
elseif (iname == "Tracer") then
self:SetTracer( value )
end
end
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
self:SetForce(force)
self:SetDelay(delay)
self:SetSound(sound)
self:SetDamage(damage)
self:SetSpread(spread)
self:SetTracer(tracer)
self:SetTraceNum(tracernum)
self:SetNumBullets(numbullets)
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
Fix turret shoot positions (#2172)
|
Fix turret shoot positions (#2172)
|
Lua
|
apache-2.0
|
wiremod/wire,dvdvideo1234/wire,Grocel/wire
|
7d4c61f1e335adf2d58c3b537d3ecdbc0156ab07
|
spec/unit/statics_spec.lua
|
spec/unit/statics_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.ROCK_VERSION, extracted_version)
local dash = string.find(extracted_version, "-")
assert.are.same(constants.VERSION, dash and extracted_version:sub(1, dash - 1) or extracted_version)
end)
it("accessing non-existing error code should throw an error", function()
assert.has_no_error(function() local _ = constants.DATABASE_ERROR_TYPES.DATABASE end)
assert.has_error(function() local _ = constants.DATABASE_ERROR_TYPES.ThIs_TyPe_DoEs_NoT_ExIsT end)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
## Available plugins on this server
plugins_available:
- ssl
- jwt
- acl
- cors
- oauth2
- tcp-log
- udp-log
- file-log
- http-log
- key-auth
- hmac-auth
- basic-auth
- ip-restriction
- mashape-analytics
- request-transformer
- response-transformer
- request-size-limiting
- rate-limiting
- response-ratelimiting
## The Kong working directory
## (Make sure you have read and write permissions)
nginx_working_dir: /usr/local/kong/
## Port configuration
proxy_port: 8000
proxy_ssl_port: 8443
admin_api_port: 8001
## Secondary port configuration
dnsmasq_port: 8053
## Specify the DAO to use
database: cassandra
## Databases configuration
databases_available:
cassandra:
properties:
contact_points:
- "localhost:9042"
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# ssl: false
# ssl_verify: false
# ssl_certificate: "/path/to/cluster-ca-certificate.pem"
# user: cassandra
# password: cassandra
## Cassandra cache configuration
database_cache_expiration: 5 # in seconds
## SSL Settings
## (Uncomment the two properties below to set your own certificate)
# ssl_cert_path: /path/to/certificate.pem
# ssl_key_path: /path/to/certificate.key
## Sends anonymous error reports
send_anonymous_reports: true
## In-memory cache size (MB)
memory_cache_size: 128
## Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log error;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}} ipv6=off;
charset UTF-8;
access_log logs/access.log;
access_log off;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 0;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict locks 100k;
lua_shared_dict cache {{memory_cache_size}}m;
lua_socket_log_errors off;
{{lua_ssl_trusted_certificate}}
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
init_worker_by_lua 'kong.exec_plugins_init_worker()';
server {
server_name _;
listen {{proxy_port}};
listen {{proxy_ssl_port}} ssl;
ssl_certificate_by_lua 'kong.exec_plugins_certificate()';
ssl_certificate {{ssl_cert}};
ssl_certificate_key {{ssl_key}};
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# omit SSLv3 because of POODLE (CVE-2014-3566)
location / {
default_type 'text/plain';
# These properties will be used later by proxy_pass
set $backend_host nil;
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
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 $backend_host;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local responses = require "kong.tools.responses"
responses.send_HTTP_INTERNAL_SERVER_ERROR("An unexpected error occurred")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua '
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.exit(204)
end
local lapis = require "lapis"
lapis.serve("kong.api.app")
';
}
location /nginx_status {
internal;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.ROCK_VERSION, extracted_version)
local dash = string.find(extracted_version, "-")
assert.are.same(constants.VERSION, dash and extracted_version:sub(1, dash - 1) or extracted_version)
end)
it("accessing non-existing error code should throw an error", function()
assert.has_no_error(function() local _ = constants.DATABASE_ERROR_TYPES.DATABASE end)
assert.has_error(function() local _ = constants.DATABASE_ERROR_TYPES.ThIs_TyPe_DoEs_NoT_ExIsT end)
end)
end)
describe("Configuration", function()
it("should equal to this template to make sure no errors are pushed in the default config", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
## Available plugins on this server
plugins_available:
- ssl
- jwt
- acl
- cors
- oauth2
- tcp-log
- udp-log
- file-log
- http-log
- key-auth
- hmac-auth
- basic-auth
- ip-restriction
- mashape-analytics
- request-transformer
- response-transformer
- request-size-limiting
- rate-limiting
- response-ratelimiting
## The Kong working directory
## (Make sure you have read and write permissions)
nginx_working_dir: /usr/local/kong/
## Port configuration
proxy_port: 8000
proxy_ssl_port: 8443
admin_api_port: 8001
## Secondary port configuration
dnsmasq_port: 8053
## Specify the DAO to use
database: cassandra
## Databases configuration
databases_available:
cassandra:
properties:
contact_points:
- "localhost:9042"
timeout: 1000
keyspace: kong
keepalive: 60000 # in milliseconds
# ssl: false
# ssl_verify: false
# ssl_certificate: "/path/to/cluster-ca-certificate.pem"
# user: cassandra
# password: cassandra
## Cassandra cache configuration
database_cache_expiration: 5 # in seconds
## SSL Settings
## (Uncomment the two properties below to set your own certificate)
# ssl_cert_path: /path/to/certificate.pem
# ssl_key_path: /path/to/certificate.key
## Sends anonymous error reports
send_anonymous_reports: true
## In-memory cache size (MB)
memory_cache_size: 128
## Nginx configuration
nginx: |
worker_processes auto;
error_log logs/error.log error;
daemon on;
worker_rlimit_nofile {{auto_worker_rlimit_nofile}};
env KONG_CONF;
events {
worker_connections {{auto_worker_connections}};
multi_accept on;
}
http {
resolver {{dns_resolver}} ipv6=off;
charset UTF-8;
access_log logs/access.log;
access_log off;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 0;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict locks 100k;
lua_shared_dict cache {{memory_cache_size}}m;
lua_socket_log_errors off;
{{lua_ssl_trusted_certificate}}
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
init_worker_by_lua 'kong.exec_plugins_init_worker()';
server {
server_name _;
listen {{proxy_port}};
listen {{proxy_ssl_port}} ssl;
ssl_certificate_by_lua 'kong.exec_plugins_certificate()';
ssl_certificate {{ssl_cert}};
ssl_certificate_key {{ssl_key}};
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# omit SSLv3 because of POODLE (CVE-2014-3566)
location / {
default_type 'text/plain';
# These properties will be used later by proxy_pass
set $backend_host nil;
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
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 $backend_host;
proxy_pass $backend_url;
proxy_pass_header Server;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local responses = require "kong.tools.responses"
responses.send_HTTP_INTERNAL_SERVER_ERROR("An unexpected error occurred")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua '
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
local lapis = require "lapis"
lapis.serve("kong.api.app")
';
}
location /nginx_status {
internal;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
fix(tests) fix config test broken because of #580
|
fix(tests) fix config test broken because of #580
|
Lua
|
apache-2.0
|
Mashape/kong,jebenexer/kong,akh00/kong,shiprabehera/kong,Kong/kong,jerizm/kong,icyxp/kong,Kong/kong,beauli/kong,Vermeille/kong,smanolache/kong,li-wl/kong,salazar/kong,xvaara/kong,ajayk/kong,ccyphers/kong,Kong/kong
|
36854c14c128140cff0705cf86604f598757b5e1
|
xmake.lua
|
xmake.lua
|
-- project
set_project("tbox")
-- set xmake minimum version
set_xmakever("2.5.1")
-- set project version
set_version("1.6.6", {build = "%Y%m%d%H%M"})
-- set warning all as error
set_warnings("all", "error")
-- set language: c99
stdc = "c99"
set_languages(stdc)
-- add defines to config.h
set_configvar("_GNU_SOURCE", 1)
set_configvar("_REENTRANT", 1)
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing", "-Wno-error=expansion-to-defined")
add_mxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing", "-Wno-error=expansion-to-defined")
-- add build modes
add_rules("mode.release", "mode.debug", "mode.profile", "mode.coverage")-- TODO, "mode.valgrind", "mode.asan", "mode.tsan", "mode.ubsan") -- for xmake v2.3.3
if is_mode("debug") then
add_defines("__tb_debug__")
end
if is_mode("valgrind") then
add_defines("__tb_valgrind__")
end
if is_mode("asan") then
add_defines("__tb_sanitize_address__")
end
if is_mode("tsan") then
add_defines("__tb_sanitize_thread__")
end
-- small or micro?
if has_config("small", "micro") then
add_defines("__tb_small__")
set_configvar("TB_CONFIG_SMALL", 1)
if is_mode("release", "profile") then
set_optimize("smallest")
end
add_cxflags("-fno-stack-protector")
end
-- for the windows platform (msvc)
if is_plat("windows") then
add_defines("NOCRYPT", "NOGDI")
if is_mode("debug") then
add_cxflags("-Gs", "-RTC1")
set_runtimes("MTd")
else
set_runtimes("MT")
end
add_syslinks("ws2_32")
elseif is_plat("android") then
add_syslinks("m", "c")
elseif is_plat("mingw", "msys", "cygwin") then
add_syslinks("ws2_32", "pthread", "m")
else
add_syslinks("pthread", "dl", "m", "c")
end
-- enable backtrace symbols for linux
if is_plat("linux") and is_mode("debug") then
add_ldflags("-rdynamic")
end
-- include project sources
includes("src")
|
-- project
set_project("tbox")
-- set xmake minimum version
set_xmakever("2.5.1")
-- set project version
set_version("1.6.6", {build = "%Y%m%d%H%M"})
-- set warning all as error
set_warnings("all", "error")
-- set language: c99
stdc = "c99"
set_languages(stdc)
-- add defines to config.h
set_configvar("_GNU_SOURCE", 1)
set_configvar("_REENTRANT", 1)
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing", "-Wno-error=expansion-to-defined")
add_mxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing", "-Wno-error=expansion-to-defined")
-- add build modes
add_rules("mode.release", "mode.debug", "mode.profile", "mode.coverage")-- TODO, "mode.valgrind", "mode.asan", "mode.tsan", "mode.ubsan") -- for xmake v2.3.3
if is_mode("debug") then
add_defines("__tb_debug__")
end
if is_mode("valgrind") then
add_defines("__tb_valgrind__")
end
if is_mode("asan") then
add_defines("__tb_sanitize_address__")
end
if is_mode("tsan") then
add_defines("__tb_sanitize_thread__")
end
-- small or micro?
if has_config("small", "micro") then
add_defines("__tb_small__")
set_configvar("TB_CONFIG_SMALL", 1)
if is_mode("release", "profile") and
-- coroutine maybe crash if we enable lto on windows, we disable small mode.
-- TODO we should fix it in context code later
-- https://github.com/tboox/tbox/issues/175
not is_config("coroutine") then
set_optimize("smallest")
end
add_cxflags("-fno-stack-protector")
end
-- for the windows platform (msvc)
if is_plat("windows") then
add_defines("NOCRYPT", "NOGDI")
if is_mode("debug") then
add_cxflags("-Gs", "-RTC1")
set_runtimes("MTd")
else
set_runtimes("MT")
end
add_syslinks("ws2_32")
elseif is_plat("android") then
add_syslinks("m", "c")
elseif is_plat("mingw", "msys", "cygwin") then
add_syslinks("ws2_32", "pthread", "m")
else
add_syslinks("pthread", "dl", "m", "c")
end
-- enable backtrace symbols for linux
if is_plat("linux") and is_mode("debug") then
add_ldflags("-rdynamic")
end
-- include project sources
includes("src")
|
fix coroutine crash on windows/lto
|
fix coroutine crash on windows/lto
|
Lua
|
apache-2.0
|
tboox/tbox,tboox/tbox,waruqi/tbox,waruqi/tbox
|
10bb7ba540d8f7bad309ede646f901cdc2969683
|
examples/lua/x20.lua
|
examples/lua/x20.lua
|
--[[ $Id$
plimage demo
--]]
-- initialise Lua bindings for PLplot examples.
dofile("plplot_examples.lua")
XDIM = 260
YDIM = 220
dbg = 0
nosombrero = 0
nointeractive = 0
f_name=""
-- Transformation function
function mypltr(x, y)
local x0 = (stretch["xmin"] + stretch["xmax"])*0.5
local y0 = (stretch["ymin"] + stretch["ymax"])*0.5
local dy = (stretch["ymax"]-stretch["ymin"])*0.5
local tx = x0 + (x0-x)*(1 - stretch["stretch"]*math.cos((y-y0)/dy*math.pi*0.5))
local ty = y
return tx, ty
end
-- read image from file in binary ppm format
function read_img(fname)
-- naive grayscale binary ppm reading. If you know how to, improve it
local fp = io.open(fname, "rb")
if fp==nil then
return 1
end
-- version
ver = fp:read("*line")
if ver==nil then -- version
fp:close()
return 1
end
if ver~="P5" then -- I only understand this!
fp:close()
return 1
end
c = fp:read(1)
while c=="#" do
com = fp:read("*line")
if com==nil then -- version
fp:close()
return 1
end
c = fp:read(1)
end
fp:seek("cur", -1)
w, h, num_col = fp:read("*number", "*number", "*number")
if w==nil or h==nil or num_col==nil then -- width, height num colors
fp:close()
return 1
end
img = {}
imf = {}
img = fp:read(w*h)
if string.len(img)~=w*h then
fp:close()
return 1
end
fp:close()
for i = 1, w do
imf[i] = {}
for j = 1, h do
index = (h-j)*w+i
imf[i][j] = img:byte(index) -- flip image up-down
end
end
return 0, imf, w, h, num_col
end
-- save plot
function save_plot(fname)
cur_strm = pl.gstrm() -- get current stream
new_strm = pl.mkstrm() -- create a new one
pl.sdev("psc") -- new device type. Use a known existing driver
pl.sfnam(fname) -- file name
pl.cpstrm(cur_strm, 0) -- copy old stream parameters to new stream
pl.replot() -- do the save
pl.end1() -- close new device
pl.sstrm(cur_strm) -- and return to previous one
end
-- get selection square interactively
function get_clip(xi, xe, yi, ye)
return 0, xi, xe, yi, ye
end
-- set gray colormap
function gray_cmap(num_col)
local r = { 0, 1 }
local g = { 0, 1 }
local b = { 0, 1 }
local pos = { 0, 1 }
pl.scmap1n(num_col)
pl.scmap1l(1, pos, r, g, b)
end
x = {}
y = {}
z = {}
r = {}
img_f = {}
cgrid2 = {}
-- Bugs in plimage():
-- + at high magnifications, the left and right edge are ragged, try
-- ./x20c -dev xwin -wplt 0.3,0.3,0.6,0.6 -ori 0.5
-- Bugs in x20c.c:
-- + if the window is resized after a selection is made on "lena", when
--making a new selection the old one will re-appear.
-- Parse and process command line arguments
pl.parseopts(arg, pl.PL_PARSE_FULL)
-- Initialize plplot
pl.init()
z={}
-- view image border pixels
if dbg~=0 then
pl.env(1, XDIM, 1, YDIM, 1, 1) -- no plot box
-- build a one pixel square border, for diagnostics
for i = 1, XDIM do
z[i] = {}
z[i][1] = 1 -- left
z[i][YDIM] = 1 -- right
end
for i = 1, YDIM do
z[1][i] = 1 -- top
z[XDIM][i] = 1 -- botton
end
pl.lab("...around a blue square."," ","A red border should appear...")
pl.image(z, 1, XDIM, 1, YDIM, 0, 0, 1, XDIM, 1, YDIM)
end
-- sombrero-like demo
if nosombrero==0 then
r = {}
pl.col0(2) -- draw a yellow plot box, useful for diagnostics! :(
pl.env(0, 2*math.pi, 0, 3*math.pi, 1, -1)
for i = 1, XDIM do
x[i] = (i-1)*2*math.pi/(XDIM-1)
end
for i = 1, YDIM do
y[i] = (i-1)*3*math.pi/(YDIM-1)
end
for i = 1, XDIM do
r[i] = {}
z[i] = {}
for j=1, YDIM do
r[i][j] = math.sqrt(x[i]^2+y[j]^2)+1e-3
z[i][j] = math.sin(r[i][j])/r[i][j]
end
end
pl.lab("No, an amplitude clipped \"sombrero\"", "", "Saturn?")
pl.ptex(2, 2, 3, 4, 0, "Transparent image")
pl.image(z, 0, 2*math.pi, 0, 3*math.pi, 0.05, 1, 0, 2*math.pi, 0, 3*math.pi)
-- save the plot
if f_name~="" then
save_plot(f_name)
end
end
-- read Lena image
-- Note we try two different locations to cover the case where this
-- examples is being run from the test_c.sh script
status, img_f, width, height, num_col = read_img("lena.pgm")
if status~=0 then
status, img_f, width, height, num_col = read_img("../lena.pgm")
if status~=0 then
pl.abort("No such file")
pl.plend()
os.exit()
end
end
-- set gray colormap
gray_cmap(num_col)
-- display Lena
pl.env(1, width, 1, height, 1, -1)
if nointeractive==0 then
pl.lab("Set and drag Button 1 to (re)set selection, Button 2 to finish."," ","Lena...")
else
pl.lab(""," ","Lena...")
end
pl.image(img_f, 1, width, 1, height, 0, 0, 1, width, 1, height)
-- selection/expansion demo
if nointeractive==0 then
xi = 200
xe = 330
yi = 280
ye = 220
status, xi, xe, yi, ye = get_clip(xi, xe, yi, ye)
if status~=0 then -- get selection rectangle
pl.plend()
os.exit()
end
pl.spause(0)
pl.adv(0)
-- display selection only
pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi)
pl.spause(1)
-- zoom in selection
pl.env(xi, xe, ye, yi, 1, -1)
pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi)
end
-- Base the dynamic range on the image contents.
img_max, img_min = pl.MinMax2dGrid(img_f)
-- Draw a saturated version of the original image. Only use the middle 50%
-- of the image's full dynamic range.
pl.col0(2)
pl.env(0, width, 0, height, 1, -1)
pl.lab("", "", "Reduced dynamic range image example")
pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min + img_max*0.25, img_max - img_max*0.25)
-- Draw a distorted version of the original image, showing its full dynamic range.
pl.env(0, width, 0, height, 1, -1)
pl.lab("", "", "Distorted image example")
stretch = {}
stretch["xmin"] = 0
stretch["xmax"] = width
stretch["ymin"] = 0
stretch["ymax"] = height
stretch["stretch"] = 0.5
-- In C / C++ the following would work, with plimagefr directly calling
-- mypltr. For compatibilty with other language bindings the same effect
-- can be achieved by generating the transformed grid first and then
-- using pltr2.
-- pl.imagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch)
cgrid2 = {}
cgrid2["xg"] = {}
cgrid2["yg"] = {}
cgrid2["nx"] = width+1
cgrid2["ny"] = height+1
for i = 1, width+1 do
cgrid2["xg"][i] = {}
cgrid2["yg"][i] = {}
for j = 1, height+1 do
xx, yy = mypltr(i, j)
cgrid2["xg"][i][j] = xx
cgrid2["yg"][i][j] = yy
end
end
--pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "pltr2", cgrid2)
pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "mypltr")
pl.plend()
|
--[[ $Id$
plimage demo
--]]
-- initialise Lua bindings for PLplot examples.
dofile("plplot_examples.lua")
XDIM = 260
YDIM = 220
dbg = 0
nosombrero = 0
nointeractive = 0
f_name=""
-- Transformation function
function mypltr(x, y)
local x0 = (stretch["xmin"] + stretch["xmax"])*0.5
local y0 = (stretch["ymin"] + stretch["ymax"])*0.5
local dy = (stretch["ymax"]-stretch["ymin"])*0.5
local tx = x0 + (x0-x)*(1 - stretch["stretch"]*math.cos((y-y0)/dy*math.pi*0.5))
local ty = y
return tx, ty
end
-- read image from file in binary ppm format
function read_img(fname)
-- naive grayscale binary ppm reading. If you know how to, improve it
local fp = io.open(fname, "rb")
if fp==nil then
return 1
end
-- version
ver = fp:read("*line")
if ver==nil then -- version
fp:close()
return 1
end
if ver~="P5" then -- I only understand this!
fp:close()
return 1
end
c = fp:read(1)
while c=="#" do
com = fp:read("*line")
if com==nil then -- version
fp:close()
return 1
end
c = fp:read(1)
end
fp:seek("cur", -1)
w, h, num_col = fp:read("*number", "*number", "*number")
if w==nil or h==nil or num_col==nil then -- width, height, num colors
fp:close()
return 1
end
img = {}
imf = {}
img = fp:read(w*h)
fp:close()
if string.len(img)~=w*h then
return 1
end
for i = 1, w do
imf[i] = {}
for j = 1, h do
imf[i][j] = string.byte(img, (h-j)*w+i) -- flip image up-down
end
end
return 0, imf, w, h, num_col
end
-- save plot
function save_plot(fname)
cur_strm = pl.gstrm() -- get current stream
new_strm = pl.mkstrm() -- create a new one
pl.sdev("psc") -- new device type. Use a known existing driver
pl.sfnam(fname) -- file name
pl.cpstrm(cur_strm, 0) -- copy old stream parameters to new stream
pl.replot() -- do the save
pl.end1() -- close new device
pl.sstrm(cur_strm) -- and return to previous one
end
-- get selection square interactively
function get_clip(xi, xe, yi, ye)
return 0, xi, xe, yi, ye
end
-- set gray colormap
function gray_cmap(num_col)
local r = { 0, 1 }
local g = { 0, 1 }
local b = { 0, 1 }
local pos = { 0, 1 }
pl.scmap1n(num_col)
pl.scmap1l(1, pos, r, g, b)
end
x = {}
y = {}
z = {}
r = {}
img_f = {}
cgrid2 = {}
-- Bugs in plimage():
-- + at high magnifications, the left and right edge are ragged, try
-- ./x20c -dev xwin -wplt 0.3,0.3,0.6,0.6 -ori 0.5
-- Bugs in x20c.c:
-- + if the window is resized after a selection is made on "lena", when
--making a new selection the old one will re-appear.
-- Parse and process command line arguments
pl.parseopts(arg, pl.PL_PARSE_FULL)
-- Initialize plplot
pl.init()
z={}
-- view image border pixels
if dbg~=0 then
pl.env(1, XDIM, 1, YDIM, 1, 1) -- no plot box
-- build a one pixel square border, for diagnostics
for i = 1, XDIM do
z[i] = {}
z[i][1] = 1 -- left
z[i][YDIM] = 1 -- right
end
for i = 1, YDIM do
z[1][i] = 1 -- top
z[XDIM][i] = 1 -- botton
end
pl.lab("...around a blue square."," ","A red border should appear...")
pl.image(z, 1, XDIM, 1, YDIM, 0, 0, 1, XDIM, 1, YDIM)
end
-- sombrero-like demo
if nosombrero==0 then
r = {}
pl.col0(2) -- draw a yellow plot box, useful for diagnostics! :(
pl.env(0, 2*math.pi, 0, 3*math.pi, 1, -1)
for i = 1, XDIM do
x[i] = (i-1)*2*math.pi/(XDIM-1)
end
for i = 1, YDIM do
y[i] = (i-1)*3*math.pi/(YDIM-1)
end
for i = 1, XDIM do
r[i] = {}
z[i] = {}
for j=1, YDIM do
r[i][j] = math.sqrt(x[i]^2+y[j]^2)+1e-3
z[i][j] = math.sin(r[i][j])/r[i][j]
end
end
pl.lab("No, an amplitude clipped \"sombrero\"", "", "Saturn?")
pl.ptex(2, 2, 3, 4, 0, "Transparent image")
pl.image(z, 0, 2*math.pi, 0, 3*math.pi, 0.05, 1, 0, 2*math.pi, 0, 3*math.pi)
-- save the plot
if f_name~="" then
save_plot(f_name)
end
end
-- read Lena image
-- Note we try two different locations to cover the case where this
-- examples is being run from the test_c.sh script
status, img_f, width, height, num_col = read_img("lena.pgm")
if status~=0 then
status, img_f, width, height, num_col = read_img("../lena.pgm")
if status~=0 then
pl.abort("No such file")
pl.plend()
os.exit()
end
end
-- set gray colormap
gray_cmap(num_col)
-- display Lena
pl.env(1, width, 1, height, 1, -1)
if nointeractive==0 then
pl.lab("Set and drag Button 1 to (re)set selection, Button 2 to finish."," ","Lena...")
else
pl.lab(""," ","Lena...")
end
pl.image(img_f, 1, width, 1, height, 0, 0, 1, width, 1, height)
-- selection/expansion demo
if nointeractive==0 then
xi = 200
xe = 330
yi = 280
ye = 220
status, xi, xe, yi, ye = get_clip(xi, xe, yi, ye)
if status~=0 then -- get selection rectangle
pl.plend()
os.exit()
end
pl.spause(0)
pl.adv(0)
-- display selection only
pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi)
pl.spause(1)
-- zoom in selection
pl.env(xi, xe, ye, yi, 1, -1)
pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi)
end
-- Base the dynamic range on the image contents.
img_max, img_min = pl.MinMax2dGrid(img_f)
-- Draw a saturated version of the original image. Only use the middle 50%
-- of the image's full dynamic range.
pl.col0(2)
pl.env(0, width, 0, height, 1, -1)
pl.lab("", "", "Reduced dynamic range image example")
pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min + img_max*0.25, img_max - img_max*0.25)
-- Draw a distorted version of the original image, showing its full dynamic range.
pl.env(0, width, 0, height, 1, -1)
pl.lab("", "", "Distorted image example")
stretch = {}
stretch["xmin"] = 0
stretch["xmax"] = width
stretch["ymin"] = 0
stretch["ymax"] = height
stretch["stretch"] = 0.5
-- In C / C++ the following would work, with plimagefr directly calling
-- mypltr. For compatibilty with other language bindings the same effect
-- can be achieved by generating the transformed grid first and then
-- using pltr2.
-- pl.imagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch)
cgrid2 = {}
cgrid2["xg"] = {}
cgrid2["yg"] = {}
cgrid2["nx"] = width+1
cgrid2["ny"] = height+1
for i = 1, width+1 do
cgrid2["xg"][i] = {}
cgrid2["yg"][i] = {}
for j = 1, height+1 do
xx, yy = mypltr(i, j)
cgrid2["xg"][i][j] = xx
cgrid2["yg"][i][j] = yy
end
end
--pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "pltr2", cgrid2)
pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "mypltr")
pl.plend()
|
Fixes a problem for Lua 5.0.
|
Fixes a problem for Lua 5.0.
svn path=/trunk/; revision=9534
|
Lua
|
lgpl-2.1
|
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
|
846a3cfff907e7f533498db62bafa2fc96a37606
|
xmake/modules/detect/sdks/find_intel.lua
|
xmake/modules/detect/sdks/find_intel.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 find_intel.lua
--
-- imports
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- init vc variables
local iclvars = {"path",
"lib",
"libpath",
"include",
"DevEnvdir",
"VSInstallDir",
"VCInstallDir",
"WindowsSdkDir",
"WindowsLibPath",
"WindowsSDKVersion",
"WindowsSdkBinPath",
"UniversalCRTSdkDir",
"UCRTVersion"}
-- load iclvars_bat environment variables
function _load_iclvars(iclvars_bat, arch, opt)
-- make the geniclvars.bat
opt = opt or {}
local geniclvars_bat = os.tmpfile() .. "_geniclvars.bat"
local geniclvars_dat = os.tmpfile() .. "_geniclvars.txt"
local file = io.open(geniclvars_bat, "w")
file:print("@echo off")
file:print("call \"%s\" -arch %s > nul", iclvars_bat, arch)
for idx, var in ipairs(iclvars) do
file:print("echo " .. var .. " = %%" .. var .. "%% %s %s", idx == 1 and ">" or ">>", geniclvars_dat)
end
file:close()
-- run geniclvars.bat
os.run(geniclvars_bat)
-- load all envirnoment variables
local variables = {}
for _, line in ipairs((io.readfile(geniclvars_dat) or ""):split("\n")) do
local p = line:find('=', 1, true)
if p then
local name = line:sub(1, p - 1):trim()
local value = line:sub(p + 1):trim()
variables[name] = value
end
end
if not variables.path then
return
end
-- remove some empty entries
for _, name in ipairs(iclvars) do
if variables[name] and #variables[name]:trim() == 0 then
variables[name] = nil
end
end
-- convert path/lib/include to PATH/LIB/INCLUDE
variables.PATH = variables.path
variables.LIB = variables.lib
variables.LIBPATH = variables.libpath
variables.INCLUDE = variables.include
variables.path = nil
variables.lib = nil
variables.include = nil
variables.libpath = nil
return variables
end
-- find intel envirnoment on windows
function _find_intel_on_windows(opt)
-- init options
opt = opt or {}
-- find iclvars_bat.bat
local paths = {"$(env ICPP_COMPILER20)"}
local iclvars_bat = find_file("bin/iclvars.bat", paths)
if iclvars_bat then
-- load iclvars_bat
local iclvars_x86 = _load_iclvars(iclvars_bat, "ia32", opt)
local iclvars_x64 = _load_iclvars(iclvars_bat, "intel64", opt)
-- save results
return {iclvars_bat = iclvars_bat, iclvars = {x86 = iclvars_x86, x64 = iclvars_x64}}
end
end
-- find intel envirnoment on linux
function _find_intel_on_linux(opt)
-- attempt to find the sdk directory
local paths = {"/opt/intel/bin", "/usr/local/bin", "/usr/bin"}
local icc = find_file("icc", paths)
if icc then
local sdkdir = path.directory(path.directory(icc))
return {sdkdir = sdkdir, bindir = path.directory(icc), path.join(sdkdir, "include"), libdir = path.join(sdkdir, "lib")}
end
end
-- find intel environment
function main(opt)
if is_host("windows") then
return _find_intel_on_windows(opt)
else
return _find_intel_on_linux(opt)
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-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_intel.lua
--
-- imports
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- init vc variables
local iclvars = {"path",
"lib",
"libpath",
"include",
"DevEnvdir",
"VSInstallDir",
"VCInstallDir",
"WindowsSdkDir",
"WindowsLibPath",
"WindowsSDKVersion",
"WindowsSdkBinPath",
"UniversalCRTSdkDir",
"UCRTVersion"}
-- load iclvars_bat environment variables
function _load_iclvars(iclvars_bat, arch, opt)
-- make the geniclvars.bat
opt = opt or {}
local geniclvars_bat = os.tmpfile() .. "_geniclvars.bat"
local geniclvars_dat = os.tmpfile() .. "_geniclvars.txt"
local file = io.open(geniclvars_bat, "w")
file:print("@echo off")
file:print("call \"%s\" -arch %s > nul", iclvars_bat, arch)
for idx, var in ipairs(iclvars) do
file:print("echo " .. var .. " = %%" .. var .. "%% %s %s", idx == 1 and ">" or ">>", geniclvars_dat)
end
file:close()
-- run geniclvars.bat
os.run(geniclvars_bat)
-- load all envirnoment variables
local variables = {}
for _, line in ipairs((io.readfile(geniclvars_dat) or ""):split("\n")) do
local p = line:find('=', 1, true)
if p then
local name = line:sub(1, p - 1):trim()
local value = line:sub(p + 1):trim()
variables[name] = value
end
end
if not variables.path then
return
end
-- remove some empty entries
for _, name in ipairs(iclvars) do
if variables[name] and #variables[name]:trim() == 0 then
variables[name] = nil
end
end
-- fix bin path for ia32
if variables.path and arch == "ia32" then
variables.path = variables.path:gsub("windows\\bin\\intel64;", "windows\\bin\\intel64_ia32;")
end
-- convert path/lib/include to PATH/LIB/INCLUDE
variables.PATH = variables.path
variables.LIB = variables.lib
variables.LIBPATH = variables.libpath
variables.INCLUDE = variables.include
variables.path = nil
variables.lib = nil
variables.include = nil
variables.libpath = nil
return variables
end
-- find intel envirnoment on windows
function _find_intel_on_windows(opt)
-- init options
opt = opt or {}
-- find iclvars_bat.bat
local paths = {"$(env ICPP_COMPILER20)"}
local iclvars_bat = find_file("bin/iclvars.bat", paths)
if iclvars_bat then
-- load iclvars_bat
local iclvars_x86 = _load_iclvars(iclvars_bat, "ia32", opt)
local iclvars_x64 = _load_iclvars(iclvars_bat, "intel64", opt)
-- save results
return {iclvars_bat = iclvars_bat, iclvars = {x86 = iclvars_x86, x64 = iclvars_x64}}
end
end
-- find intel envirnoment on linux
function _find_intel_on_linux(opt)
-- attempt to find the sdk directory
local paths = {"/opt/intel/bin", "/usr/local/bin", "/usr/bin"}
local icc = find_file("icc", paths)
if icc then
local sdkdir = path.directory(path.directory(icc))
return {sdkdir = sdkdir, bindir = path.directory(icc), path.join(sdkdir, "include"), libdir = path.join(sdkdir, "lib")}
end
end
-- find intel environment
function main(opt)
if is_host("windows") then
return _find_intel_on_windows(opt)
else
return _find_intel_on_linux(opt)
end
end
|
fix bin path for icl/ia32
|
fix bin path for icl/ia32
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
4e657e962e6edefc9351779342065b10b156d73e
|
src/cosy/loader/js.lua
|
src/cosy/loader/js.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (options)
options = options or {}
local loader = {}
for k, v in pairs (options) do
loader [k] = v
end
local global = _G or _ENV
loader.home = "/"
loader.prefix = "/"
loader.js = global.js
loader.window = loader.js.global
loader.document = loader.js.global.document
loader.screen = loader.js.global.screen
local modules = setmetatable ({}, { __mode = "kv" })
loader.request = function (url)
local request = loader.js.new (loader.window.XMLHttpRequest)
request:open ("GET", url, false)
request:send (nil)
if request.status == 200 then
return request.responseText, request.status
else
return nil , request.status
end
end
table.insert (package.searchers, 2, function (name)
local url = "/lua/" .. name
local result, err
result, err = loader.request (url)
if not result then
error (err)
end
return load (result, url)
end)
loader.require = require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.coroutine = loader.require "coroutine.make" ()
loader.logto = true
loader.scheduler = {
_running = nil,
waiting = {},
ready = {},
coroutine = loader.coroutine,
}
function loader.scheduler.running ()
return loader.scheduler._running
end
function loader.scheduler.addthread (f, ...)
local co = loader.scheduler.coroutine.create (f)
loader.scheduler.ready [co] = {
parameters = { ... },
}
end
function loader.scheduler.sleep (time)
time = time or -math.huge
local co = loader.scheduler.running ()
if time > 0 then
loader.window:setTimeout (function ()
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
end, time * 1000)
end
if time ~= 0 then
loader.scheduler.waiting [co] = true
loader.scheduler.ready [co] = nil
loader.scheduler.coroutine.yield ()
end
end
function loader.scheduler.wakeup (co)
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
coroutine.resume (loader.scheduler.co)
end
function loader.scheduler.loop ()
while true do
local to_run, t = next (loader.scheduler.ready)
if to_run then
loader.scheduler._running = to_run
local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters))
if not ok then
loader.window.console:log (err)
end
if loader.scheduler.coroutine.status (to_run) == "dead" then
loader.scheduler.waiting [to_run] = nil
loader.scheduler.ready [to_run] = nil
end
end
if not next (loader.scheduler.ready )
and not next (loader.scheduler.waiting) then
break
elseif not next (loader.scheduler.ready) then
loader.scheduler.co = coroutine.running ()
coroutine.yield ()
end
end
end
local _ = loader.load "cosy.string"
local Value = loader.load "cosy.value"
loader.library = loader.load "cosy.library"
loader.storage = loader.js.global.sessionStorage
local data = loader.storage:getItem "cosy:client"
if data == loader.js.null then
data = nil
else
data = Value.decode (data)
end
loader.client = loader.library.connect (loader.js.global.location.origin, data)
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (options)
options = options or {}
local loader = {}
for k, v in pairs (options) do
loader [k] = v
end
local global = _G or _ENV
loader.home = "/"
loader.prefix = "/"
loader.js = global.js
loader.window = loader.js.global
loader.document = loader.js.global.document
loader.screen = loader.js.global.screen
local modules = setmetatable ({}, { __mode = "kv" })
loader.request = function (url)
local request = loader.js.new (loader.window.XMLHttpRequest)
request:open ("GET", url, false)
request:send (nil)
if request.status == 200 then
return request.responseText, request.status
else
return nil , request.status
end
end
table.insert (package.searchers, 2, function (name)
local url = "/lua/" .. name
local result, err
result, err = loader.request (url)
if not result then
error (err)
end
return load (result, url)
end)
loader.require = require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.coroutine = loader.require "coroutine.make" ()
loader.logto = true
loader.scheduler = {
_running = nil,
waiting = {},
ready = {},
coroutine = loader.coroutine,
}
function loader.scheduler.running ()
return loader.scheduler._running
end
function loader.scheduler.addthread (f, ...)
local co = loader.scheduler.coroutine.create (f)
loader.scheduler.ready [co] = {
parameters = { ... },
}
end
function loader.scheduler.sleep (time)
time = time or -math.huge
local co = loader.scheduler.running ()
if time > 0 then
loader.window:setTimeout (function ()
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
if coroutine.status (loader.scheduler.co) == "suspended" then
coroutine.resume (loader.scheduler.co)
end
end, time * 1000)
end
if time ~= 0 then
loader.scheduler.waiting [co] = true
loader.scheduler.ready [co] = nil
loader.scheduler.coroutine.yield ()
end
end
function loader.scheduler.wakeup (co)
loader.scheduler.waiting [co] = nil
loader.scheduler.ready [co] = true
coroutine.resume (loader.scheduler.co)
end
function loader.scheduler.loop ()
while true do
local to_run, t = next (loader.scheduler.ready)
if to_run then
if loader.scheduler.coroutine.status (to_run) == "suspended" then
loader.scheduler._running = to_run
local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters))
if not ok then
loader.window.console:log (err)
end
end
if loader.scheduler.coroutine.status (to_run) == "dead" then
loader.scheduler.waiting [to_run] = nil
loader.scheduler.ready [to_run] = nil
end
end
if not next (loader.scheduler.ready )
and not next (loader.scheduler.waiting) then
break
elseif not next (loader.scheduler.ready) then
loader.scheduler.co = coroutine.running ()
coroutine.yield ()
end
end
end
local _ = loader.load "cosy.string"
local Value = loader.load "cosy.value"
loader.library = loader.load "cosy.library"
loader.storage = loader.js.global.sessionStorage
local data = loader.storage:getItem "cosy:client"
if data == loader.js.null then
data = nil
else
data = Value.decode (data)
end
loader.client = loader.library.connect (loader.js.global.location.origin, data)
return loader
end
|
Fix js scheduler.
|
Fix js scheduler.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
45e1b8c0d7e339244dce4d81e49a8414f5ae1316
|
src/spy.lua
|
src/spy.lua
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require 'luassert.util'
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
new = function(self, callback)
return setmetatable(
{
calls = {},
callback = callback or function() end,
called = function(self, times)
if times then
return #self.calls == times
end
return #self.calls > 0
end,
called_with = function(self, args)
for _,v in ipairs(self.calls) do
if util.deepcompare(v, args) then
return true
end
end
return false
end
},
{
__call = function(self, ...)
table.insert(self.calls, { ... })
return self.callback(...)
end
})
end,
on = function(self, callback_string)
self[callback_string] = spy:new(self[callback_string])
return self[callback_string]
end
}
local function set_spy(state)
end
local function called_with(state, ...)
if rawget(state, "payload") and rawget(state, "payload").called_with then
return state.payload:called_with({...})
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
local function called(state, num_times)
if state.payload and state.payload.called then
return state.payload:called(num_times)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "called_with", called_with, "Function was not called with arguments")
assert:register("assertion", "called", called, "Function was not called")
return spy
|
-- module will return spy table, and register its assertions with the main assert engine
local assert = require('luassert.assert')
local util = require 'luassert.util'
local spy -- must make local before defining table, because table contents refers to the table (recursion)
spy = {
new = function(self, callback)
return setmetatable(
{
calls = {},
callback = callback or function() end,
called = function(self, times)
if times then
return #self.calls == times
end
return #self.calls > 0
end,
called_with = function(self, args)
for _,v in ipairs(self.calls) do
if util.deepcompare(v, args) then
return true
end
end
return false
end
},
{
__call = function(self, ...)
local arguments = {...}
arguments.n = select('#',...) -- add argument count for trailing nils
table.insert(self.calls, arguments)
return self.callback(...)
end
})
end,
on = function(self, callback_string)
self[callback_string] = spy:new(self[callback_string])
return self[callback_string]
end
}
local function set_spy(state)
end
local function called_with(state, arguments)
if rawget(state, "payload") and rawget(state, "payload").called_with then
return state.payload:called_with(arguments)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
local function called(state, arguments)
local num_times = arguments[1]
if state.payload and state.payload.called then
return state.payload:called(num_times)
else
error("'called_with' must be chained after 'spy(aspy)'")
end
end
assert:register("modifier", "spy", set_spy)
assert:register("assertion", "called_with", called_with, "Function was not called with arguments")
assert:register("assertion", "called", called, "Function was not called")
return spy
|
Fixed the spies, final tests failing on previous changes. Now only the actual bad error message test still fails.
|
Fixed the spies, final tests failing on previous changes. Now only the actual bad error message test still fails.
|
Lua
|
mit
|
tst2005/lua-luassert,o-lim/luassert,mpeterv/luassert,ZyX-I/luassert
|
543b917d1af8aac3d6fd9780061814f3735afcb9
|
mod_listusers/mod_listusers.lua
|
mod_listusers/mod_listusers.lua
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
local banner = config.get("*", "console_banner");
if (
(not banner) or
(
(type(banner) == "string") and
(banner:match("^| (.+)$"))
)
) then
repeat
local rec_banner = conn:receive()
until
rec_banner == "" or
rec_banner == nil; -- skip banner
end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
mod_listusers: fixed banner skipping cycle
|
mod_listusers: fixed banner skipping cycle
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
060a8628cebe4096914c100e297946c65eb6b606
|
resources/prosody-plugins/mod_token_verification.lua
|
resources/prosody-plugins/mod_token_verification.lua
|
-- Token authentication
-- Copyright (C) 2015 Atlassian
local log = module._log;
local host = module.host;
local st = require "util.stanza";
local is_admin = require "core.usermanager".is_admin;
local parentHostName = string.gmatch(tostring(host), "%w+.(%w.+)")();
if parentHostName == nil then
log("error", "Failed to start - unable to get parent hostname");
return;
end
local parentCtx = module:context(parentHostName);
if parentCtx == nil then
log("error",
"Failed to start - unable to get parent context for host: %s",
tostring(parentHostName));
return;
end
local token_util = module:require "token/util".new(parentCtx);
-- no token configuration
if token_util == nil then
return;
end
log("debug",
"%s - starting MUC token verifier app_id: %s app_secret: %s allow empty: %s",
tostring(host), tostring(token_util.appId), tostring(token_util.appSecret),
tostring(token_util.allowEmptyToken));
-- option to disable room modification (sending muc config form) for guest that do not provide token
local require_token_for_moderation;
local function load_config()
require_token_for_moderation = module:get_option_boolean("token_verification_require_token_for_moderation");
end
load_config();
-- verify user and whether he is allowed to join a room based on the token information
local function verify_user(session, stanza)
log("debug", "Session token: %s, session room: %s",
tostring(session.auth_token),
tostring(session.jitsi_meet_room));
-- token not required for admin users
local user_jid = stanza.attr.from;
if is_admin(user_jid) then
log("debug", "Token not required from admin user: %s", user_jid);
return true;
end
log("debug",
"Will verify token for user: %s, room: %s ", user_jid, stanza.attr.to);
if not token_util:verify_room(session, stanza.attr.to) then
log("error", "Token %s not allowed to join: %s",
tostring(session.auth_token), tostring(stanza.attr.to));
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room and token mismatched"));
return false; -- we need to just return non nil
end
log("debug",
"allowed: %s to enter/create room: %s", user_jid, stanza.attr.to);
return true;
end
module:hook("muc-room-pre-create", function(event)
local origin, stanza = event.origin, event.stanza;
log("debug", "pre create: %s %s", tostring(origin), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
module:hook("muc-occupant-pre-join", function(event)
local origin, room, stanza = event.origin, event.room, event.stanza;
log("debug", "pre join: %s %s", tostring(room), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
for event_name, method in pairs {
-- Normal room interactions
["iq-set/bare/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
-- Host room
["iq-set/host/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
} do
module:hook(event_name, function (event)
local session, stanza = event.origin, event.stanza;
-- if we do not require token we pass it through(default behaviour)
-- or the request is coming from admin (focus)
if not require_token_for_moderation or is_admin(stanza.attr.from) then
return;
end
-- jitsi_meet_room is set after the token had been verified
if not session.auth_token or not session.jitsi_meet_room then
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room modification disabled for guests"));
return true;
end
end, -1); -- the default prosody hook is on -2
end
module:hook_global('config-reloaded', load_config);
|
-- Token authentication
-- Copyright (C) 2015 Atlassian
local log = module._log;
local host = module.host;
local st = require "util.stanza";
local um_is_admin = require "core.usermanager".is_admin;
local function is_admin(jid)
return um_is_admin(jid, host);
end
local parentHostName = string.gmatch(tostring(host), "%w+.(%w.+)")();
if parentHostName == nil then
log("error", "Failed to start - unable to get parent hostname");
return;
end
local parentCtx = module:context(parentHostName);
if parentCtx == nil then
log("error",
"Failed to start - unable to get parent context for host: %s",
tostring(parentHostName));
return;
end
local token_util = module:require "token/util".new(parentCtx);
-- no token configuration
if token_util == nil then
return;
end
log("debug",
"%s - starting MUC token verifier app_id: %s app_secret: %s allow empty: %s",
tostring(host), tostring(token_util.appId), tostring(token_util.appSecret),
tostring(token_util.allowEmptyToken));
-- option to disable room modification (sending muc config form) for guest that do not provide token
local require_token_for_moderation;
local function load_config()
require_token_for_moderation = module:get_option_boolean("token_verification_require_token_for_moderation");
end
load_config();
-- verify user and whether he is allowed to join a room based on the token information
local function verify_user(session, stanza)
log("debug", "Session token: %s, session room: %s",
tostring(session.auth_token),
tostring(session.jitsi_meet_room));
-- token not required for admin users
local user_jid = stanza.attr.from;
if is_admin(user_jid) then
log("debug", "Token not required from admin user: %s", user_jid);
return true;
end
log("debug",
"Will verify token for user: %s, room: %s ", user_jid, stanza.attr.to);
if not token_util:verify_room(session, stanza.attr.to) then
log("error", "Token %s not allowed to join: %s",
tostring(session.auth_token), tostring(stanza.attr.to));
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room and token mismatched"));
return false; -- we need to just return non nil
end
log("debug",
"allowed: %s to enter/create room: %s", user_jid, stanza.attr.to);
return true;
end
module:hook("muc-room-pre-create", function(event)
local origin, stanza = event.origin, event.stanza;
log("debug", "pre create: %s %s", tostring(origin), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
module:hook("muc-occupant-pre-join", function(event)
local origin, room, stanza = event.origin, event.room, event.stanza;
log("debug", "pre join: %s %s", tostring(room), tostring(stanza));
if not verify_user(origin, stanza) then
return true; -- Returning any value other than nil will halt processing of the event
end
end);
for event_name, method in pairs {
-- Normal room interactions
["iq-set/bare/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
-- Host room
["iq-set/host/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;
} do
module:hook(event_name, function (event)
local session, stanza = event.origin, event.stanza;
-- if we do not require token we pass it through(default behaviour)
-- or the request is coming from admin (focus)
if not require_token_for_moderation or is_admin(stanza.attr.from) then
return;
end
-- jitsi_meet_room is set after the token had been verified
if not session.auth_token or not session.jitsi_meet_room then
session.send(
st.error_reply(
stanza, "cancel", "not-allowed", "Room modification disabled for guests"));
return true;
end
end, -1); -- the default prosody hook is on -2
end
module:hook_global('config-reloaded', load_config);
|
fixed admin check for token verification
|
fixed admin check for token verification
|
Lua
|
apache-2.0
|
gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
|
54b99c92654c9613d8847707147db9ea207a3b1a
|
test/benchmark-ping-pongs.lua
|
test/benchmark-ping-pongs.lua
|
local uv = require 'couv'
local MSG = "PING\n"
local startTime = uv.hrtime()
function exitCb(process, exitStatus, termSignal)
uv.close(process)
end
uv.spawn{args={uv.exepath(), 'examples/tcp-echo-server.lua'},
flags=uv.PROCESS_DETACHED,
exitCb=exitCb}
coroutine.wrap(function()
local handle = uv.tcp_create()
uv.tcp_bind(handle, uv.ip4addr('0.0.0.0', 0))
uv.tcp_connect(handle, uv.ip4addr('127.0.0.1', 9123))
uv.write(handle, {MSG})
uv.read_start(handle)
local pongCount = 0
repeat
local nread, buf = uv.read(handle)
if nread > 0 then
if buf:toString(1, nread) ~= MSG then
error(string.format("got wrong answer %s", buf:toString(1, nread)))
end
pongCount = pongCount + 1
uv.write(handle, {MSG})
end
until uv.hrtime() - startTime > 5e9
uv.close(handle)
print(string.format("ping_pongs: %d roundtrips/s", pongCount))
end)()
uv.run()
|
local uv = require 'couv'
local MSG = "PING\n"
local startTime = uv.hrtime()
function exitCb(process, exitStatus, termSignal)
uv.close(process)
end
local process = uv.spawn{args={uv.exepath(), 'examples/tcp-echo-server.lua'},
flags=uv.PROCESS_DETACHED,
exitCb=exitCb}
function timerCb()
coroutine.wrap(function()
local ok, err = pcall(function()
local handle = uv.tcp_create()
uv.tcp_bind(handle, uv.ip4addr('0.0.0.0', 0))
uv.tcp_connect(handle, uv.ip4addr('127.0.0.1', 9123))
uv.write(handle, {MSG})
uv.read_start(handle)
local pongCount = 0
repeat
local nread, buf = uv.read(handle)
if nread > 0 then
if buf:toString(1, nread) ~= MSG then
error(string.format("got wrong answer %s", buf:toString(1, nread)))
end
pongCount = pongCount + 1
uv.write(handle, {MSG})
end
until uv.hrtime() - startTime > 5e9
uv.write(handle, {'QUIT'})
uv.close(handle)
print(string.format("ping_pongs: %d roundtrips/s", pongCount))
end)
if err then
print(err)
end
end)()
end
-- We need to use a timer to avoid an error on OSX.
-- test/benchmark-ping-pongs.lua:19: ECONNREFUSED
local timer = uv.timer_create()
uv.timer_start(timer, timerCb, 10)
uv.run()
|
Fix benchmark-ping-pongs to work on OSX too.
|
Fix benchmark-ping-pongs to work on OSX too.
|
Lua
|
mit
|
hnakamur/couv,hnakamur/couv
|
b62337fdc3651478fb67f86fd3f3a2cf62db0d33
|
src/cosy/configuration.lua
|
src/cosy/configuration.lua
|
local loader = require "cosy.loader"
local Value = loader.value
local Logger = loader.logger
local Repository = loader.repository
local repository = Repository.new ()
Repository.options (repository).create = function () return {} end
Repository.options (repository).import = function () return {} end
repository.internal = {
locale = "en",
}
repository.whole = {
[Repository.depends] = {
repository.internal,
repository.default,
repository.etc,
repository.home,
repository.pwd,
},
}
local files = {
default = nil,
etc = "/etc/cosy.conf",
home = os.getenv "HOME" .. "/.cosy/cosy.conf",
pwd = os.getenv "PWD" .. "/cosy.conf",
}
do -- fill the `default` path:
local hotswap = require "hotswap" .new ()
repository.default = hotswap "cosy.configuration.default"
files .default = hotswap.sources ["cosy.configuration.default"]
end
if not _G.js then
local scheduler = loader.scheduler
scheduler.addthread (function ()
local changed = {}
for _, filename in pairs (files) do
changed [filename] = true
end
scheduler.blocking (false)
local co = coroutine.running ()
local ev = require "ev"
local hotswap = require "hotswap" .new ()
hotswap.register = function (filename, f)
ev.Stat.new (function (loop, stat)
if f () then
changed [filename] = true
scheduler.wakeup (co)
end
end, filename):start (scheduler._loop)
end
while true do
for key, filename in pairs (files) do
if changed [filename] then
changed [filename] = false
local ok, err = pcall (function ()
local result, new = hotswap (filename)
if new then
repository [key] = loader.value.decode (result)
end
end)
if ok then
Logger.debug {
_ = "configuration:using",
path = filename,
locale = repository.whole.locale._,
}
else
Logger.warning {
_ = "configuration:skipping",
path = filename,
reason = err,
locale = repository.whole.locale._,
}
end
end
end
scheduler.sleep (-math.huge)
end
end)
scheduler.loop ()
end
return repository.whole
|
local loader = require "cosy.loader"
local Logger = loader.logger
local Repository = loader.repository
local repository = Repository.new ()
Repository.options (repository).create = function () return {} end
Repository.options (repository).import = function () return {} end
repository.internal = {
locale = "en",
}
repository.whole = {
[Repository.depends] = {
repository.internal,
repository.default,
repository.etc,
repository.home,
repository.pwd,
},
}
local files = {
default = nil,
etc = "/etc/cosy.conf",
home = os.getenv "HOME" .. "/.cosy/cosy.conf",
pwd = os.getenv "PWD" .. "/cosy.conf",
}
do -- fill the `default` path:
local hotswap = require "hotswap" .new ()
repository.default = hotswap "cosy.configuration.default"
files .default = hotswap.sources ["cosy.configuration.default"]
end
if not _G.js then
local scheduler = loader.scheduler
scheduler.addthread (function ()
local changed = {}
for _, filename in pairs (files) do
changed [filename] = true
end
scheduler.blocking (false)
local co = coroutine.running ()
local ev = require "ev"
local hotswap = require "hotswap" .new ()
hotswap.register = function (filename, f)
ev.Stat.new (function ()
if f () then
changed [filename] = true
scheduler.wakeup (co)
end
end, filename):start (scheduler._loop)
end
while true do
for key, filename in pairs (files) do
if changed [filename] then
changed [filename] = false
local ok, err = pcall (function ()
local result, new = hotswap (filename)
if new then
repository [key] = loader.value.decode (result)
end
end)
if ok then
Logger.debug {
_ = "configuration:using",
path = filename,
locale = repository.whole.locale._,
}
else
Logger.warning {
_ = "configuration:skipping",
path = filename,
reason = err,
locale = repository.whole.locale._,
}
end
end
end
scheduler.sleep (-math.huge)
end
end)
scheduler.loop ()
end
return repository.whole
|
Fix warnings.
|
Fix warnings.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
647cbac0c60847bd89eaa8de82de4a91713d9d49
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.send;
function session.send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fix to reply to stream for s2s sessions
|
mod_smacks: Fix to reply to stream for s2s sessions
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
1f0fc79359bc5fa1043119ef1caa62b2bd7ecb8b
|
src/lua/xml.lua
|
src/lua/xml.lua
|
-- © 2013 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local coroutine_yield = coroutine.yield
local coroutine_wrap = coroutine.wrap
local writeu8 = wg.writeu8
--- Tokenises XML.
-- Given an XML string, this function returns an iterator which streams
-- tokens from it.
--
-- @param xml XML string to tokenise
-- @return iterator
function TokeniseXML(xml)
local PROCESSING = '^<%?([%w_-]+)%s*(.-)%?>'
local COMMENT = '^<!%-%-(.-)%-%->'
local CDATA = '^<%!%[CDATA%[(.-)%]%]>'
local OPENTAG = '^<%s*([%w_-]+)(:?)([%w+-]*)%s*(.-)(/?)>'
local TAGATTR1 = '^%s*([%w_-]+)(:?)([%w+-]*)%s*=%s*"(.-)"'
local TAGATTR2 = "^%s*([%w_-]+)(:?)([%w+-]*)%s*=%s*'(.-)'"
local CLOSETAG = '^</%s*([%w_-]+)(:?)([%w+-]*)%s*>'
local TEXT = '^([^&<]+)'
local DECIMALENTITY = '&#(%d+);'
local HEXENTITY = '&#x(%x+);'
local NAMEDENTITY = '&(%w+);'
local EOF = '^%s*$'
local entities =
{
["amp"] = "&",
["lt"] = "<",
["gt"] = ">",
["quot"] = '"',
["apos"] = "'"
}
-- Collapse whitespace.
xml = xml:gsub("\r", "")
xml = xml:gsub("\t", " ")
xml = xml:gsub(" *\n", "\n")
xml = xml:gsub("\n *", "\n")
xml = xml:gsub(" +", " ")
xml = xml:gsub("\n+", "\n")
xml = xml:gsub("([^>])\n([^<])", "%1 %2")
xml = xml:gsub("\n", "")
xml = xml:gsub("> +<", "><")
local offset = 1
local function parse_attributes(scope, data)
local attrs = {}
local offset = 1
local _, e, s1, s2, s3, s4
while true do
while true do
_, e, s1, s2, s3, s4 = data:find(TAGATTR1, offset)
if not e then
_, e, s1, s2, s3, s4 = data:find(TAGATTR2, offset)
end
if e then
local namespace = ""
local name
if (s2 ~= "") then
namespace = s1
name = s3
else
name = s1
end
if (namespace == "xmlns") then
scope[name] = s4
elseif (namespace == "") and (name == "xmlns") then
scope[""] = s4
else
attrs[#attrs+1] =
{
namespace = namespace,
name = name,
value = s4
}
end
break
end
for _, a in ipairs(attrs) do
a.namespace = scope[a.namespace] or a.namespace
end
return attrs
end
offset = e + 1
end
end
local parse_tag
local function parse_tag_contents(scope)
local _, e, s1, s2, s3, s4, s5
while true do
while true do
_, e, s1, s2 = xml:find(PROCESSING, offset)
if s1 then
coroutine_yield(
{
event = "processing",
name = s1,
attrs = parse_attributes({}, s2)
}
)
offset = e + 1
break
end
_, e = xml:find(OPENTAG, offset)
if e then
parse_tag(scope)
break
end
_, e = xml:find(CLOSETAG, offset)
if e then
offset = e + 1
return
end
_, e, s1 = xml:find(TEXT, offset)
if e then
coroutine_yield(
{
event = "text",
text = s1
}
)
offset = e + 1
break
end
_, e, s1 = xml:find(DECIMALENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = writeu8(tonumber(s1))
}
)
offset = e + 1
break
end
_, e, s1 = xml:find(HEXENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = writeu8(tonumber("0x"..s1))
}
)
offset = e + 1
break
end
_, e, s1 = xml:find(NAMEDENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = entities[s1] or "invalidentity"
}
)
offset = e + 1
break
end
_, e = xml:find(EOF, offset)
if e then
return
end
coroutine_yield(
{
event = "error",
text = xml:sub(offset, offset+100)
}
)
return
end
end
end
parse_tag = function(scope)
local _, e, s1, s2, s3, s4, s5 = xml:find(OPENTAG, offset)
local newscope = {}
for k, v in pairs(scope) do
newscope[k] = v
end
local tag = {
event = "opentag",
attrs = parse_attributes(newscope, s4)
}
if (s2 ~= "") then
tag.namespace = newscope[s1] or s1
tag.name = s3
else
tag.namespace = newscope[""] or s1
tag.name = s1
end
coroutine_yield(tag)
offset = e + 1
if (s5 == "") then
parse_tag_contents(newscope)
end
coroutine_yield(
{
event = "closetag",
namespace = tag.namespace,
name = tag.name
}
)
end
local function parser()
parse_tag_contents({})
end
return coroutine_wrap(parser)
end
--- Parses an XML string into a DOM-ish tree.
--
-- @param xml XML string to parse
-- @return tree
function ParseXML(xml)
local nextToken = TokeniseXML(xml)
local function parse_tag(token)
local n = token.name
if (token.namespace ~= "") then
n = token.namespace .. " " .. n
end
local t = {
_name = n
}
for _, a in ipairs(token.attrs) do
n = a.name
if (a.namespace ~= "") then
n = a.namespace .. " " .. n
end
t[n] = a.value
end
while true do
token = nextToken()
if (token.event == "opentag") then
t[#t+1] = parse_tag(token)
elseif (token.event == "text") then
t[#t+1] = token.text
elseif (token.event == "closetag") then
return t
end
end
end
-- Find and parse the first element.
while true do
local token = nextToken()
if (token.event == "opentag") then
return parse_tag(token)
end
if not token then
return {}
end
end
end
|
-- © 2013 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local coroutine_yield = coroutine.yield
local coroutine_wrap = coroutine.wrap
local writeu8 = wg.writeu8
local string_find = string.find
local function cowcopy(t)
return setmetatable({},
{
__index = t
}
)
end
--- Tokenises XML.
-- Given an XML string, this function returns an iterator which streams
-- tokens from it.
--
-- @param xml XML string to tokenise
-- @return iterator
function TokeniseXML(xml)
local PROCESSING = '^<%?([%w_-]+)%s*(.-)%?>'
local COMMENT = '^<!%-%-(.-)%-%->'
local CDATA = '^<%!%[CDATA%[(.-)%]%]>'
local OPENTAG = '^<%s*([%w_-]+)(:?)([%w+-]*)%s*(.-)(/?)>'
local TAGATTR1 = '^%s*([%w_-]+)(:?)([%w+-]*)%s*=%s*"([^"]*)"'
local TAGATTR2 = "^%s*([%w_-]+)(:?)([%w+-]*)%s*=%s*'([^']*)'"
local CLOSETAG = '^</%s*([%w_-]+)(:?)([%w+-]*)%s*>'
local TEXT = '^([^&<]+)'
local DECIMALENTITY = '^&#(%d+);'
local HEXENTITY = '^&#x(%x+);'
local NAMEDENTITY = '^&(%w+);'
local EOF = '^%s*$'
local entities =
{
["amp"] = "&",
["lt"] = "<",
["gt"] = ">",
["quot"] = '"',
["apos"] = "'"
}
-- Collapse whitespace.
xml = xml:gsub("\r", "")
xml = xml:gsub("\t", " ")
xml = xml:gsub(" *\n", "\n")
xml = xml:gsub("\n *", "\n")
xml = xml:gsub(" +", " ")
xml = xml:gsub("\n+", "\n")
xml = xml:gsub("([^>])\n([^<])", "%1 %2")
xml = xml:gsub("\n", "")
xml = xml:gsub("> +<", "><")
local offset = 1
local function parse_attributes(scope, data)
local attrs = {}
local offset = 1
local _, e, s1, s2, s3, s4
while true do
while true do
_, e, s1, s2, s3, s4 = string_find(data, TAGATTR1, offset)
if not e then
_, e, s1, s2, s3, s4 = string_find(data, TAGATTR2, offset)
end
if e then
local namespace = ""
local name
if (s2 ~= "") then
namespace = s1
name = s3
else
name = s1
end
if (namespace == "xmlns") then
scope[name] = s4
elseif (namespace == "") and (name == "xmlns") then
scope[""] = s4
else
attrs[#attrs+1] =
{
namespace = namespace,
name = name,
value = s4
}
end
break
end
for _, a in ipairs(attrs) do
a.namespace = scope[a.namespace] or a.namespace
end
return attrs
end
offset = e + 1
end
end
local parse_tag
local function parse_tag_contents(scope)
local _, e, s1, s2, s3, s4, s5
while true do
while true do
_, e = string_find(xml, OPENTAG, offset)
if e then
parse_tag(scope)
break
end
_, e = string_find(xml, CLOSETAG, offset)
if e then
offset = e + 1
return
end
_, e, s1 = string_find(xml, TEXT, offset)
if e then
coroutine_yield(
{
event = "text",
text = s1
}
)
offset = e + 1
break
end
_, e, s1 = string_find(xml, DECIMALENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = writeu8(tonumber(s1))
}
)
offset = e + 1
break
end
_, e, s1 = string_find(xml, HEXENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = writeu8(tonumber("0x"..s1))
}
)
offset = e + 1
break
end
_, e, s1 = string_find(xml, NAMEDENTITY, offset)
if e then
coroutine_yield(
{
event = "text",
text = entities[s1] or "invalidentity"
}
)
offset = e + 1
break
end
_, e, s1, s2 = string_find(xml, PROCESSING, offset)
if s1 then
coroutine_yield(
{
event = "processing",
name = s1,
attrs = parse_attributes({}, s2)
}
)
offset = e + 1
break
end
_, e = string_find(xml, EOF, offset)
if e then
return
end
coroutine_yield(
{
event = "error",
text = xml:sub(offset, offset+100)
}
)
return
end
end
end
parse_tag = function(scope)
local _, e, s1, s2, s3, s4, s5 = string_find(xml, OPENTAG, offset)
local newscope = cowcopy(scope)
local tag = {
event = "opentag",
attrs = parse_attributes(newscope, s4)
}
if (s2 ~= "") then
tag.namespace = newscope[s1] or s1
tag.name = s3
else
tag.namespace = newscope[""] or s1
tag.name = s1
end
coroutine_yield(tag)
offset = e + 1
if (s5 == "") then
parse_tag_contents(newscope)
end
coroutine_yield(
{
event = "closetag",
namespace = tag.namespace,
name = tag.name
}
)
end
local function parser()
parse_tag_contents({})
end
return coroutine_wrap(parser)
end
--- Parses an XML string into a DOM-ish tree.
--
-- @param xml XML string to parse
-- @return tree
function ParseXML(xml)
local nextToken = TokeniseXML(xml)
local function parse_tag(token)
local n = token.name
if (token.namespace ~= "") then
n = token.namespace .. " " .. n
end
local t = {
_name = n
}
for _, a in ipairs(token.attrs) do
n = a.name
if (a.namespace ~= "") then
n = a.namespace .. " " .. n
end
t[n] = a.value
end
while true do
token = nextToken()
if (token.event == "opentag") then
t[#t+1] = parse_tag(token)
elseif (token.event == "text") then
t[#t+1] = token.text
elseif (token.event == "closetag") then
return t
end
end
end
-- Find and parse the first element.
while true do
local token = nextToken()
if (token.event == "opentag") then
return parse_tag(token)
end
if not token then
return {}
end
end
end
|
Improved the XML parsing performance no end by fixing some hideous bugs.
|
Improved the XML parsing performance no end by fixing some hideous bugs.
|
Lua
|
mit
|
rodoviario/wordgrinder,NRauh/wordgrinder,rodoviario/wordgrinder,NRauh/wordgrinder,Munchotaur/wordgrinder,Munchotaur/wordgrinder
|
3fa4087fe23f055694c7dce2e0c1e46daba667bd
|
platform/android/llapp_main.lua
|
platform/android/llapp_main.lua
|
local android = require("android")
android.dl.library_path = android.dl.library_path .. ":" .. android.dir .. "/libs"
local ffi = require("ffi")
local dummy = require("ffi/posix_h")
local C = ffi.C
-- check uri of the intent that starts this application
local file = android.getIntent()
if file ~= nil then
android.LOGI("intent file path " .. file)
end
-- run koreader patch before koreader startup
pcall(dofile, "/sdcard/koreader/patch.lua")
-- set TESSDATA_PREFIX env var
C.setenv("TESSDATA_PREFIX", "/sdcard/koreader/data", 1)
-- create fake command-line arguments
-- luacheck: ignore 121
if android.isDebuggable() then
arg = {"-d", file or "/sdcard"}
else
arg = {file or "/sdcard"}
end
dofile(android.dir.."/reader.lua")
|
local android = require("android")
android.dl.library_path = android.dl.library_path .. ":" .. android.dir .. "/libs"
local ffi = require("ffi")
local dummy = require("ffi/posix_h")
local C = ffi.C
-- check uri of the intent that starts this application
local file = android.getIntent()
if file ~= nil then
android.LOGI("intent file path " .. file)
end
-- run koreader patch before koreader startup
pcall(dofile, "/sdcard/koreader/patch.lua")
-- Set proper permission for binaries.
--- @todo Take care of this on extraction instead.
-- Cf. <https://github.com/koreader/koreader/issues/5347#issuecomment-529476693>.
android.execute("chmod", "755", "./sdcv")
android.execute("chmod", "755", "./tar")
android.execute("chmod", "755", "./zsync")
-- set TESSDATA_PREFIX env var
C.setenv("TESSDATA_PREFIX", "/sdcard/koreader/data", 1)
-- create fake command-line arguments
-- luacheck: ignore 121
if android.isDebuggable() then
arg = {"-d", file or "/sdcard"}
else
arg = {file or "/sdcard"}
end
dofile(android.dir.."/reader.lua")
|
[fix, Android] Set executable bit (#5349)
|
[fix, Android] Set executable bit (#5349)
Partially reverts d2536d8b7e9474bd7748b199d1f01a53f332942a.
Fixes <https://github.com/koreader/koreader/issues/5347>.
|
Lua
|
agpl-3.0
|
Markismus/koreader,NiLuJe/koreader,pazos/koreader,Hzj-jie/koreader,mihailim/koreader,Frenzie/koreader,mwoz123/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader
|
603510d2266ad5584c2247049babdcc429c72a48
|
Modules/Geometry/TouchingParts/PartTouchingCalculator.lua
|
Modules/Geometry/TouchingParts/PartTouchingCalculator.lua
|
--- Determines if parts are touching or not
-- @classmod PartTouchingCalculator
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local BoundingBox = require("BoundingBox")
local CharacterUtil = require("CharacterUtil")
local PartTouchingCalculator = {}
PartTouchingCalculator.__index = PartTouchingCalculator
PartTouchingCalculator.ClassName = "PartTouchingCalculator"
function PartTouchingCalculator.new()
local self = setmetatable({}, PartTouchingCalculator)
return self
end
function PartTouchingCalculator:CheckIfTouchingHumanoid(humanoid, parts)
assert(humanoid)
assert(parts, "Must have parts")
local humanoidParts = {}
for _, item in pairs(humanoid:GetDesendants()) do
if item:IsA("BasePart") then
table.insert(humanoidParts, item)
end
end
if #humanoidParts == 0 then
warn("[BoatPlacer][CheckIfTouchingHumanoid] - #parts == 0, retrieved from humanoid")
return false
end
local dummyPart = self:GetCollidingPartFromParts(humanoidParts)
local previousProperties = {}
local toSet = {
CanCollide = true;
Anchored = false;
}
local partSet = {}
for _, part in pairs(parts) do
previousProperties[part] = {}
for name, value in pairs(toSet) do
previousProperties[part][name] = part[name]
part[name] = value
end
partSet[part] = true
end
local touching = dummyPart:GetTouchingParts()
dummyPart:Destroy()
local returnValue = false
for _, part in pairs(touching) do
if partSet[part] then
returnValue = true
break
end
end
for part, properties in pairs(previousProperties) do
for name, value in pairs(properties) do
part[name] = value
end
end
return returnValue
end
function PartTouchingCalculator:GetCollidingPartFromParts(parts, relativeTo, padding)
relativeTo = relativeTo or CFrame.new()
local size, rotation = BoundingBox.GetPartsBoundingBox(parts, relativeTo)
if padding then
size = size + Vector3.new(padding, padding, padding)
end
local dummyPart = Instance.new("Part")
dummyPart.Name = "CollisionDetection"
dummyPart.Size = size
dummyPart.CFrame = rotation
dummyPart.Anchored = false
dummyPart.CanCollide = true
dummyPart.Parent = Workspace
return dummyPart
end
function PartTouchingCalculator:GetTouchingBoundingBox(parts, relativeTo, padding)
local dummy = self:GetCollidingPartFromParts(parts, relativeTo, padding)
local touching = dummy:GetTouchingParts()
dummy:Destroy()
return touching
end
--- Expensive hull check on a list of parts (aggregating each parts touching list)
function PartTouchingCalculator:GetTouchingHull(parts, padding)
local hitParts = {}
for _, part in pairs(parts) do
for _, TouchingPart in pairs(self:GetTouching(part, padding)) do
hitParts[TouchingPart] = true
end
end
local touching = {}
for part, _ in pairs(hitParts) do
table.insert(touching, part)
end
return touching
end
--- Retrieves parts touching a base part
-- @param basePart item to identify touching. Geometry matters
-- @param padding studs of padding around the part
function PartTouchingCalculator:GetTouching(basePart, padding)
padding = padding or 2
local part
if basePart:IsA("TrussPart") then
-- Truss parts can't be resized
part = Instance.new("Part")
else
-- Clone part
part = basePart:Clone()
-- Remove all tags
for _, Tag in pairs(CollectionService:GetTags(part)) do
CollectionService:RemoveTag(part, Tag)
end
end
part:ClearAllChildren()
part.Size = basePart.Size + Vector3.new(padding, padding, padding)
part.CFrame = basePart.CFrame
part.Anchored = false
part.CanCollide = true
part.Transparency = 0.1
part.Material = Enum.Material.SmoothPlastic
part.Parent = Workspace
local touching = part:GetTouchingParts()
part:Destroy()
return touching
end
function PartTouchingCalculator:GetTouchingHumanoids(touchingList)
local touchingHumanoids = {}
for _, part in pairs(touchingList) do
local humanoid = part.Parent:FindFirstChildOfClass("humanoid")
if humanoid then
if not touchingHumanoids[humanoid] then
local player = CharacterUtil.GetPlayerFromCharacter(humanoid)
touchingHumanoids[humanoid] = {
Humanoid = humanoid;
Character = player.Character;
Player = player;
Touching = {part}
}
else
table.insert(touchingHumanoids[humanoid].Touching, part)
end
end
end
local list = {}
for _, data in pairs(touchingHumanoids) do
table.insert(list, data)
end
return list
end
return PartTouchingCalculator
|
--- Determines if parts are touching or not
-- @classmod PartTouchingCalculator
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local BoundingBox = require("BoundingBox")
local CharacterUtil = require("CharacterUtil")
local PartTouchingCalculator = {}
PartTouchingCalculator.__index = PartTouchingCalculator
PartTouchingCalculator.ClassName = "PartTouchingCalculator"
function PartTouchingCalculator.new()
local self = setmetatable({}, PartTouchingCalculator)
return self
end
function PartTouchingCalculator:CheckIfTouchingHumanoid(humanoid, parts)
assert(humanoid)
assert(parts, "Must have parts")
local humanoidParts = {}
for _, item in pairs(humanoid.Parent:GetDescendants()) do
if item:IsA("BasePart") then
table.insert(humanoidParts, item)
end
end
if #humanoidParts == 0 then
warn("[PartTouchingCalculator.CheckIfTouchingHumanoid] - #humanoidParts == 0!")
return false
end
local dummyPart = self:GetCollidingPartFromParts(humanoidParts)
local previousProperties = {}
local toSet = {
CanCollide = true;
Anchored = false;
}
local partSet = {}
for _, part in pairs(parts) do
previousProperties[part] = {}
for name, value in pairs(toSet) do
previousProperties[part][name] = part[name]
part[name] = value
end
partSet[part] = true
end
local touching = dummyPart:GetTouchingParts()
dummyPart:Destroy()
local returnValue = false
for _, part in pairs(touching) do
if partSet[part] then
returnValue = true
break
end
end
for part, properties in pairs(previousProperties) do
for name, value in pairs(properties) do
part[name] = value
end
end
return returnValue
end
function PartTouchingCalculator:GetCollidingPartFromParts(parts, relativeTo, padding)
relativeTo = relativeTo or CFrame.new()
local size, rotation = BoundingBox.GetPartsBoundingBox(parts, relativeTo)
if padding then
size = size + Vector3.new(padding, padding, padding)
end
local dummyPart = Instance.new("Part")
dummyPart.Name = "CollisionDetection"
dummyPart.Size = size
dummyPart.CFrame = rotation
dummyPart.Anchored = false
dummyPart.CanCollide = true
dummyPart.Parent = Workspace
return dummyPart
end
function PartTouchingCalculator:GetTouchingBoundingBox(parts, relativeTo, padding)
local dummy = self:GetCollidingPartFromParts(parts, relativeTo, padding)
local touching = dummy:GetTouchingParts()
dummy:Destroy()
return touching
end
--- Expensive hull check on a list of parts (aggregating each parts touching list)
function PartTouchingCalculator:GetTouchingHull(parts, padding)
local hitParts = {}
for _, part in pairs(parts) do
for _, TouchingPart in pairs(self:GetTouching(part, padding)) do
hitParts[TouchingPart] = true
end
end
local touching = {}
for part, _ in pairs(hitParts) do
table.insert(touching, part)
end
return touching
end
--- Retrieves parts touching a base part
-- @param basePart item to identify touching. Geometry matters
-- @param padding studs of padding around the part
function PartTouchingCalculator:GetTouching(basePart, padding)
padding = padding or 2
local part
if basePart:IsA("TrussPart") then
-- Truss parts can't be resized
part = Instance.new("Part")
else
-- Clone part
part = basePart:Clone()
-- Remove all tags
for _, Tag in pairs(CollectionService:GetTags(part)) do
CollectionService:RemoveTag(part, Tag)
end
end
part:ClearAllChildren()
part.Size = basePart.Size + Vector3.new(padding, padding, padding)
part.CFrame = basePart.CFrame
part.Anchored = false
part.CanCollide = true
part.Transparency = 0.1
part.Material = Enum.Material.SmoothPlastic
part.Parent = Workspace
local touching = part:GetTouchingParts()
part:Destroy()
return touching
end
function PartTouchingCalculator:GetTouchingHumanoids(touchingList)
local touchingHumanoids = {}
for _, part in pairs(touchingList) do
local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
if not touchingHumanoids[humanoid] then
local player = CharacterUtil.GetPlayerFromCharacter(humanoid)
touchingHumanoids[humanoid] = {
Humanoid = humanoid;
Character = player.Character;
Player = player;
Touching = {part}
}
else
table.insert(touchingHumanoids[humanoid].Touching, part)
end
end
end
local list = {}
for _, data in pairs(touchingHumanoids) do
table.insert(list, data)
end
return list
end
return PartTouchingCalculator
|
Fix CheckIfTouchingHumanoid
|
Fix CheckIfTouchingHumanoid
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
540c7050ee8b480875b60869a58bb2ae0d4d427d
|
units.tests.lua
|
units.tests.lua
|
require "tundra.syntax.glob"
require "tundra.path"
require "tundra.util"
-----------------------------------------------------------------------------------------------------------------------
local function Test(params)
Program {
Name = params.Name,
Env = {
CPPPATH = {
"api/include",
"src/external/foundation_lib",
"src/external/minifb/include",
"src/external/imgui",
"src/external/cmocka/include",
"src/prodbg",
},
PROGCOM = {
{ "-lstdc++", "-coverage"; Config = "macosx_test-clang-*" },
{ "-lstdc++"; Config = { "macosx-clang-*", "linux-gcc-*" } },
{ "-lm -lpthread -ldl"; Config = "linux-*-*" },
},
},
Sources = {
params.Source,
},
Depends = params.Depends,
Libs = { { "Ws2_32.lib", "shell32.lib", "psapi.lib", "iphlpapi.lib", "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = { "win32-*-*", "win64-*-*" } } },
Frameworks = { "Cocoa" },
IdeGenerationHints = { Msvc = { SolutionFolder = "Tests" } },
}
end
-----------------------------------------------------------------------------------------------------------------------
local all_depends = { "uv", "api", "core", "script", "stb", "remote_api", "cmocka", "session", "ui", "bgfx", "jansson", "lua", "imgui", "minifb", "scintilla", "tinyxml2" }
-----------------------------------------------------------------------------------------------------------------------
Test({ Name = "core_tests", Source = "src/prodbg/tests/core_tests.cpp", Depends = { "core", "stb", "uv", "cmocka"} })
Test({ Name = "lldb_tests", Source = "src/prodbg/tests/lldb_tests.cpp", Depends = all_depends})
Test({ Name = "readwrite_tests", Source = "src/prodbg/tests/readwrite_tests.cpp", Depends = all_depends})
Test({ Name = "remote_api_tests", Source = "src/prodbg/tests/remote_api_tests.cpp", Depends = all_depends})
Test({ Name = "session_tests", Source = "src/prodbg/tests/session_tests.cpp", Depends = all_depends})
Test({ Name = "script_tests", Source = "src/prodbg/tests/script_tests.cpp", Depends = { "core", "script", "lua", "cmocka" }})
Test({ Name = "ui_docking_tests", Source = "src/prodbg/tests/ui_docking_tests.cpp", Depends = all_depends})
Test({ Name = "ui_tests", Source = "src/prodbg/tests/ui_tests.cpp", Depends = all_depends})
Test({ Name = "dbgeng_tests", Source = "src/prodbg/tests/dbgeng_tests.cpp" })
-----------------------------------------------------------------------------------------------------------------------
Default "core_tests"
Default "lldb_tests"
Default "readwrite_tests"
Default "remote_api_tests"
Default "dbgeng_tests"
Default "session_tests"
Default "script_tests"
Default "ui_docking_tests"
Default "ui_tests"
|
require "tundra.syntax.glob"
require "tundra.path"
require "tundra.util"
-----------------------------------------------------------------------------------------------------------------------
local function Test(params)
Program {
Name = params.Name,
Env = {
CPPPATH = {
"api/include",
"src/external/foundation_lib",
"src/external/minifb/include",
"src/external/imgui",
"src/external/cmocka/include",
"src/prodbg",
},
PROGCOM = {
{ "-lstdc++", "-coverage"; Config = "macosx_test-clang-*" },
{ "-lstdc++"; Config = { "macosx-clang-*", "linux-gcc-*" } },
{ "-lm -lpthread -ldl"; Config = "linux-*-*" },
},
},
Sources = {
params.Source,
},
Depends = params.Depends,
Libs = { { "Ws2_32.lib", "shell32.lib", "psapi.lib", "iphlpapi.lib", "wsock32.lib", "kernel32.lib", "user32.lib", "gdi32.lib", "Comdlg32.lib", "Advapi32.lib" ; Config = { "win32-*-*", "win64-*-*" } } },
Frameworks = { "Cocoa" },
IdeGenerationHints = { Msvc = { SolutionFolder = "Tests" } },
}
end
-----------------------------------------------------------------------------------------------------------------------
local all_depends = { "uv", "api", "core", "script", "stb", "remote_api", "cmocka", "session", "ui", "bgfx", "jansson", "lua", "imgui", "minifb", "scintilla", "tinyxml2" }
-----------------------------------------------------------------------------------------------------------------------
Test({ Name = "core_tests", Source = "src/prodbg/tests/core_tests.cpp", Depends = { "core", "stb", "uv", "cmocka"} })
Test({ Name = "lldb_tests", Source = "src/prodbg/tests/lldb_tests.cpp", Depends = all_depends})
Test({ Name = "readwrite_tests", Source = "src/prodbg/tests/readwrite_tests.cpp", Depends = all_depends})
Test({ Name = "remote_api_tests", Source = "src/prodbg/tests/remote_api_tests.cpp", Depends = all_depends})
Test({ Name = "session_tests", Source = "src/prodbg/tests/session_tests.cpp", Depends = all_depends})
Test({ Name = "script_tests", Source = "src/prodbg/tests/script_tests.cpp", Depends = { "core", "script", "lua", "cmocka" }})
Test({ Name = "ui_docking_tests", Source = "src/prodbg/tests/ui_docking_tests.cpp", Depends = all_depends})
Test({ Name = "ui_tests", Source = "src/prodbg/tests/ui_tests.cpp", Depends = all_depends})
Test({ Name = "dbgeng_tests", Source = "src/prodbg/tests/dbgeng_tests.cpp", Depends = all_depends })
-----------------------------------------------------------------------------------------------------------------------
Default "core_tests"
Default "lldb_tests"
Default "readwrite_tests"
Default "remote_api_tests"
Default "session_tests"
Default "script_tests"
Default "ui_docking_tests"
Default "ui_tests"
Default "dbgeng_tests"
|
Fixed link errors in dbgeng_test
|
Fixed link errors in dbgeng_test
|
Lua
|
mit
|
emoon/ProDBG,v3n/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,v3n/ProDBG,v3n/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,ashemedai/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,ashemedai/ProDBG,v3n/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,emoon/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG
|
8b7a4994717eca80d1ea0e11680ad295e9b6e6bd
|
plugins/lua/init.lua
|
plugins/lua/init.lua
|
ENV = {}
require "superstring"
local tostring = require "stostring"
local scall = require "scall"
EOF = "\x00"
HEADERSTART = '['
HEADEREND = ']'
writepacket = io.write
-- Redefine io.write/print to save output to a per-user buffer for PMs.
-- See g_write in liolib.c
local stdoutbuf = ""
function io.write( ... )
local args = { ... }
stdoutbuf = stdoutbuf .. table.concat( args )
end
-- See luaB_print in lbaselib.c
function print( ... )
local args = { ... }
for k, v in pairs(args) do
v = tostring(v)
stdoutbuf = stdoutbuf .. v .. "\t"
end
stdoutbuf = stdoutbuf .. "\n"
end
require "env"
require "user_modules/gmod_defines"
function ParseHeader(data)
local header = {}
data = data:sub( 2, -2 ) -- Remove the header markers
local headers = string.Explode( ":", data )
if ( #headers ~= 5 ) then
io.stderr:write( "ParseHeader called with invalid data: \"" .. data .. "\"\n" )
io.stderr:flush()
else
header.crc = tonumber(headers[1]) or 0
header.sandbox = headers[2] and headers[2]:sub(1, 1):lower() == "t" or false
header.showerror = headers[3] and headers[3]:sub(1, 1):lower() == "t" or false
header.steamid = tonumber(headers[4]) or 0
header.groupid = tonumber(headers[5]) or 0
end
return header
end
function PacketSafe(str, argnum)
str = tostring(str);
local exchanges = {
[1] = {
[","] = "\\,",
["\x00"] = "\\x00",
},
[2] = {
[":"] = "\\:",
["\x00"] = "\\x00",
},
[3] = {
["\x00"] = "\\x00",
--["]"] = "\\]",
},
[4] = {
["\x00"] = "\\x00",
--["]"] = "\\]",
},
}
return str:gsub(".", exchanges[argnum] or {});
end
function CreatePacket( crc, data, validlua )
local header = HEADERSTART .. "Lua," .. tostring(crc) .. ":"
header = header .. (validlua and "1" or "0") .. HEADEREND
data = string.gsub(PacketSafe(data, 4), "\x00", "")
return header .. PacketSafe(data, 4)
end
::start::
stdoutbuf = ""
--
-- Indicate that we are ready to receive a packet
--
writepacket( EOF ); io.flush()
--
-- Read until EOF marker
--
local expectheader = true -- Should the next line read be the code header
local header = nil -- The header metadata for this code
local code = "" -- The string of code to execute
local codecrc = 0 -- The CRC of the code and epoch seed. Used in the return packet.
local showerror = false -- Should any error data be returned to the user
local sandboxcode = true -- Should this code run in our sandbox
local steamid = 0 -- STEAM64 of the user that executed this, 0 if internal.
local groupid = 0 -- Group ID that this code originated from. User SID if PM.
while( true ) do
local data = io.read() -- Read single line
--io.stderr:write(data);
if ( expectheader ) then
if ( data:sub( 1, 1 ) == HEADERSTART and data:sub( -1 ) == HEADEREND ) then
header = ParseHeader(data)
showerror = header.showerror == true -- Default to false
sandboxcode = header.sandbox ~= false -- Default to true
steamid = header.steamid or 0
groupid = header.groupid or 0
codecrc = header.crc or 0
expectheader = false
else
io.stderr:write( "io.read expected header, got \"" .. data .. "\" instead!\n" )
io.stderr:flush()
end
else
if ( data:sub( -1 ) == EOF ) then
code = code .. data:sub( 0, -2 ) -- Remove the EOF
break
else
code = code .. data .. "\n" -- Put the newline back
end
end
end
-- Returns true if this call is not being executed by a user
function IsInternal()
return (steamid == 0) and (groupid == 0)
end
-- Return true if this code is being executed inside the sandbox
function IsSandboxed()
return sandboxcode
end
-- Set the environment to the sandbox
local LOAD_ENV = ENV
local CALL_FUNC = scall
-- Use the un-sandboxed the environment if the header says so
if ( not IsSandboxed() ) then
--io.stderr:write("no sandbox: \"" .. code .. "\"\n"); io.stderr:flush();
LOAD_ENV = _ENV
CALL_FUNC = pcall
end
--
-- Try our code with "return " prepended first
--
local f, err = load( "return " .. code, "eval", "t", LOAD_ENV )
if err then
f, err = load( code, "eval", "t", LOAD_ENV )
end
--
-- We've been passed invalid Lua
--
if err then
writepacket( CreatePacket( codecrc, err, false ) )
io.flush()
goto start
end
--
-- Try to run our function
--
local ret = { CALL_FUNC( f, code ) }
local success, err = ret[ 1 ], ret[ 2 ]
--
-- Our function has failed
--
if not success then
writepacket( CreatePacket( codecrc, err, false ) )
io.flush()
goto start
end
--
-- Remove scall success success bool
--
table.remove( ret, 1 )
if ( #ret > 0 ) then -- Code returned something
-- Transform our ret values in to strings
for k, v in ipairs( ret ) do
ret[ k ] = tostring( v )
end
local data = table.concat( ret, "\t" )
writepacket( CreatePacket( codecrc, stdoutbuf .. data, true ) )
else -- Code returned nil, check if its `return lol` 'valid' or actually lua.
local isphrase = code:match( "^[%w ]+$" ) -- Match alphanumeric and space
if ( isphrase ) then
writepacket( CreatePacket( codecrc, stdoutbuf, false ) )
else
writepacket( CreatePacket( codecrc, stdoutbuf, true ) )
end
end
io.flush()
--
-- repeat
---
goto start
|
ENV = {}
require "superstring"
local tostring = require "stostring"
local scall = require "scall"
EOF = "\x00"
HEADERSTART = '['
HEADEREND = ']'
writepacket = io.write
-- Redefine io.write/print to save output to a per-user buffer for PMs.
-- See g_write in liolib.c
local stdoutbuf = ""
function io.write( ... )
local args = { ... }
stdoutbuf = stdoutbuf .. table.concat( args )
end
-- See luaB_print in lbaselib.c
function print( ... )
local args = { ... }
for k, v in pairs(args) do
v = tostring(v)
stdoutbuf = stdoutbuf .. v .. "\t"
end
stdoutbuf = stdoutbuf .. "\n"
end
require "env"
require "user_modules/gmod_defines"
function ParseHeader(data)
local header = {}
data = data:sub( 2, -2 ) -- Remove the header markers
local headers = string.Explode( ":", data )
if ( #headers ~= 5 ) then
io.stderr:write( "ParseHeader called with invalid data: \"" .. data .. "\"\n" )
io.stderr:flush()
else
header.crc = tonumber(headers[1]) or 0
header.sandbox = headers[2] and headers[2]:sub(1, 1):lower() == "t" or false
header.showerror = headers[3] and headers[3]:sub(1, 1):lower() == "t" or false
header.steamid = tonumber(headers[4]) or 0
header.groupid = tonumber(headers[5]) or 0
end
return header
end
function PacketSafe(str, argnum)
str = tostring(str);
local exchanges = {
[1] = {
[","] = "\\,",
["\x00"] = "\\x00",
},
[2] = {
[":"] = "\\:",
["\x00"] = "\\x00",
},
[3] = {
["\x00"] = "\\x00",
--["]"] = "\\]",
},
[4] = {
["\x00"] = "\\x00",
--["]"] = "\\]",
},
}
return str:gsub(".", exchanges[argnum] or {});
end
function CreatePacket( crc, data, validlua )
local header = HEADERSTART .. "Lua," .. tostring(crc) .. ":"
header = header .. (validlua and "1" or "0") .. HEADEREND
data = string.gsub(PacketSafe(data, 4), "\x00", "")
return header .. PacketSafe(data, 4)
end
::start::
stdoutbuf = ""
--
-- Indicate that we are ready to receive a packet
--
writepacket( EOF ); io.flush()
--
-- Read until EOF marker
--
local expectheader = true -- Should the next line read be the code header
local header = nil -- The header metadata for this code
local code = "" -- The string of code to execute
local codecrc = 0 -- The CRC of the code and epoch seed. Used in the return packet.
local showerror = false -- Should any error data be returned to the user
local sandboxcode = true -- Should this code run in our sandbox
local steamid = 0 -- STEAM64 of the user that executed this, 0 if internal.
local groupid = 0 -- Group ID that this code originated from. User SID if PM.
while( true ) do
local data = io.read() -- Read single line
--io.stderr:write(data);
if ( expectheader ) then
if ( data:sub( 1, 1 ) == HEADERSTART and data:sub( -1 ) == HEADEREND ) then
header = ParseHeader(data)
showerror = header.showerror == true -- Default to false
sandboxcode = header.sandbox ~= false -- Default to true
steamid = header.steamid or 0
groupid = header.groupid or 0
codecrc = header.crc or 0
expectheader = false
else
io.stderr:write( "io.read expected header, got \"" .. data .. "\" instead!\n" )
io.stderr:flush()
end
else
if ( data:sub( -1 ) == EOF ) then
code = code .. data:sub( 0, -2 ) -- Remove the EOF
break
else
code = code .. data .. "\n" -- Put the newline back
end
end
end
-- Returns true if this call is not being executed by a user
function IsInternal()
return (steamid == 0) and (groupid == 0)
end
-- Return true if this code is being executed inside the sandbox
function IsSandboxed()
return sandboxcode
end
-- Set the RNG seed for this run
-- note: sandboxed applications can predict this seed,
-- but there's no point in obscuring the seed any more
-- than it is now by also using microseconds or whatever,
-- because the sandbox has math.randomseed exposed anyway.
math.randomseed( os.time() )
-- Set the environment to the sandbox
local LOAD_ENV = ENV
local CALL_FUNC = scall
-- Use the un-sandboxed the environment if the header says so
if ( not IsSandboxed() ) then
--io.stderr:write("no sandbox: \"" .. code .. "\"\n"); io.stderr:flush();
LOAD_ENV = _ENV
CALL_FUNC = pcall
end
--
-- Try our code with "return " prepended first
--
local f, err = load( "return " .. code, "eval", "t", LOAD_ENV )
if err then
f, err = load( code, "eval", "t", LOAD_ENV )
end
--
-- We've been passed invalid Lua
--
if err then
writepacket( CreatePacket( codecrc, err, false ) )
io.flush()
goto start
end
--
-- Try to run our function
--
local ret = { CALL_FUNC( f, code ) }
local success, err = ret[ 1 ], ret[ 2 ]
--
-- Our function has failed
--
if not success then
writepacket( CreatePacket( codecrc, err, false ) )
io.flush()
goto start
end
--
-- Remove scall success success bool
--
table.remove( ret, 1 )
if ( #ret > 0 ) then -- Code returned something
-- Transform our ret values in to strings
for k, v in ipairs( ret ) do
ret[ k ] = tostring( v )
end
local data = table.concat( ret, "\t" )
writepacket( CreatePacket( codecrc, stdoutbuf .. data, true ) )
else -- Code returned nil, check if its `return lol` 'valid' or actually lua.
local isphrase = code:match( "^[%w ]+$" ) -- Match alphanumeric and space
if ( isphrase ) then
writepacket( CreatePacket( codecrc, stdoutbuf, false ) )
else
writepacket( CreatePacket( codecrc, stdoutbuf, true ) )
end
end
io.flush()
--
-- repeat
---
goto start
|
Set the RNG seed for each run through scall/pcall
|
Set the RNG seed for each run through scall/pcall
valve pls fix
|
Lua
|
cc0-1.0
|
meepdarknessmeep/hash.js,SwadicalRag/hash.js
|
f4dcf9befb2d7c2ebd60a4f5b2200f283e61c50b
|
home/config/nvim/lua/plugins/nvim-lspconfig.lua
|
home/config/nvim/lua/plugins/nvim-lspconfig.lua
|
local wk = require('which-key')
local lspinstaller = require('nvim-lsp-installer')
local lspconfig = require('lspconfig')
local illum = require('illuminate')
local aerial = require('aerial')
local lsp = vim.lsp
local diag = vim.diagnostic
wk.register(
{
l = {
name = 'LSP',
a = { '<Cmd>AerialToggle<Cr>', 'Toggle Aerial' } ,
e = { '<Cmd>lua vim.lsp.buf.code_action()<Cr>', 'Code Actions' },
f = { function() lsp.buf.formatting() end, 'Format' },
i = { function() lsp.buf.implementation() end, 'Implementation' },
k = { function() lsp.buf.hover() end, 'Hover' },
l = { function() diag.open_float() end, 'Show Line Diagnostics' },
q = { function() diag.setloclist() end, 'Set Location List' },
R = { '<Cmd>LspRestart<Cr>', 'Restart LSP' },
m = { function() lsp.buf.rename() end, 'Rename' },
y = { function() lsp.buf.type_definition() end, 'Type Definition' },
-- Telescope lsp maps
D = { '<Cmd>Telescope lsp_document_diagnostics<Cr>', 'Diagnostics' },
I = { '<Cmd>Telescope lsp_implementations<Cr>', 'Implementations' },
d = { '<Cmd>Telescope lsp_definitions<Cr>', 'Definitions' },
r = { '<Cmd>Telescope lsp_references<Cr>', 'References' },
s = { '<Cmd>Telescope lsp_document_symbols<Cr>', 'Symbols' },
-- nvim-lsp-installer maps
L = { '<Cmd>LspInstallInfo<Cr>', 'nvim-lsp-installer UI' },
},
},
{
prefix = '<Leader>',
}
)
wk.register(
{
['[d'] = { function() diag.goto_prev() end, 'Previous Diagnostic' },
[']d'] = { function() diag.goto_next() end, 'Next Diagnostic' },
-- vim-illuminate maps
[']i'] = { function() illum.next_reference({ wrap = true }) end, 'Move to next doc highlight' },
['[i'] = { function() illum.next_reference({ wrap = true, reverse = true }) end, 'Move to prev doc highlight' },
}
)
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
local function disable_formatting(client)
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
end
local enhance_server_opts = {
['tsserver'] = function(opts, client)
-- Prefer prettier formatting over null-ls
disable_formatting(client)
end,
['jsonls'] = function(opts, client)
-- Prefer prettier formatting over null-ls
disable_formatting(client)
end,
}
lspinstaller.setup()
local servers = { 'tsserver', 'jsonls', 'eslint', 'prismals' }
for _, server in ipairs(servers) do
lspconfig[server].setup({
capabilities = capabilities,
on_attach = function(client, bufnr)
if enhance_server_opts[server] then
-- Enhance the default opts with the server-specific ones
enhance_server_opts[server](opts, client)
end
-- Automatically format for servers which support it
if client.resolved_capabilities.document_formatting then
vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()")
end
-- Attach vim-illuminate
illum.on_attach(client)
-- Attach aerial.nvim
aerial.on_attach(client, bufnr)
end,
})
end
-- Disable illuminate in fugitiveblame
vim.g.Illuminate_ftblacklist = { 'fugitiveblame' }
|
local wk = require('which-key')
local lspinstaller = require('nvim-lsp-installer')
local lspconfig = require('lspconfig')
local illum = require('illuminate')
local aerial = require('aerial')
local lsp = vim.lsp
local diag = vim.diagnostic
wk.register(
{
l = {
name = 'LSP',
a = { '<Cmd>AerialToggle<Cr>', 'Toggle Aerial' } ,
e = { '<Cmd>lua vim.lsp.buf.code_action()<Cr>', 'Code Actions' },
f = { function() lsp.buf.formatting() end, 'Format' },
i = { function() lsp.buf.implementation() end, 'Implementation' },
k = { function() lsp.buf.hover() end, 'Hover' },
l = { function() diag.open_float() end, 'Show Line Diagnostics' },
q = { function() diag.setloclist() end, 'Set Location List' },
R = { '<Cmd>LspRestart<Cr>', 'Restart LSP' },
m = { function() lsp.buf.rename() end, 'Rename' },
y = { function() lsp.buf.type_definition() end, 'Type Definition' },
-- Telescope lsp maps
D = { '<Cmd>Telescope lsp_document_diagnostics<Cr>', 'Diagnostics' },
I = { '<Cmd>Telescope lsp_implementations<Cr>', 'Implementations' },
d = { '<Cmd>Telescope lsp_definitions<Cr>', 'Definitions' },
r = { '<Cmd>Telescope lsp_references<Cr>', 'References' },
s = { '<Cmd>Telescope lsp_document_symbols<Cr>', 'Symbols' },
-- nvim-lsp-installer maps
L = { '<Cmd>LspInstallInfo<Cr>', 'nvim-lsp-installer UI' },
},
},
{
prefix = '<Leader>',
}
)
wk.register(
{
['[d'] = { function() diag.goto_prev() end, 'Previous Diagnostic' },
[']d'] = { function() diag.goto_next() end, 'Next Diagnostic' },
-- vim-illuminate maps
[']i'] = { function() illum.next_reference({ wrap = true }) end, 'Move to next doc highlight' },
['[i'] = { function() illum.next_reference({ wrap = true, reverse = true }) end, 'Move to prev doc highlight' },
}
)
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
local function disable_formatting(client)
client.server_capabilities.documentFormattingProvider = nil
client.server_capabilities.documentFormattingProvider = nil
end
local enhance_server_opts = {
['tsserver'] = function(opts, client)
-- Prefer prettier formatting over null-ls
disable_formatting(client)
end,
['jsonls'] = function(opts, client)
-- Prefer prettier formatting over null-ls
disable_formatting(client)
end,
}
lspinstaller.setup()
local servers = { 'tsserver', 'jsonls', 'eslint', 'prismals' }
for _, server in ipairs(servers) do
lspconfig[server].setup({
capabilities = capabilities,
on_attach = function(client, bufnr)
if enhance_server_opts[server] then
-- Enhance the default opts with the server-specific ones
enhance_server_opts[server](opts, client)
end
-- Automatically format for servers which support it
if client.server_capabilities.documentFormattingProvider then
vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()")
end
-- Attach vim-illuminate
illum.on_attach(client)
-- Attach aerial.nvim
aerial.on_attach(client, bufnr)
end,
})
end
-- Disable illuminate in fugitiveblame
vim.g.Illuminate_ftblacklist = { 'fugitiveblame' }
|
fix(nvim): disable formatting using new 0.8 api
|
fix(nvim): disable formatting using new 0.8 api
|
Lua
|
unlicense
|
knpwrs/dotfiles
|
6bedf02d3de1913f91dc0cb2c80eed056ddc226f
|
test_scripts/RC/SetInteriorVehicleData/011_Cut-off_read-only_parameters_in_case_request_with_read-only_and_not_read-only_parameters.lua
|
test_scripts/RC/SetInteriorVehicleData/011_Cut-off_read-only_parameters_in_case_request_with_read-only_and_not_read-only_parameters.lua
|
---------------------------------------------------------------------------------------------------
-- Description
-- In case:
-- 1) Application sends valid SetInteriorVehicleData with read-only parameters
-- 2) and one or more settable parameters in "radioControlData" struct, for moduleType: RADIO,
-- SDL must:
-- 1) Cut the read-only parameters off and process this RPC as assigned
-- (that is, check policies, send to HMI, and etc. per existing requirements)
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local commonRC = require('test_scripts/RC/commonRC')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
--[[ Local Variables ]]
local modules = { "CLIMATE", "RADIO" }
local function setVehicleData(pModuleType, pParams, self)
local moduleDataReadOnly = commonRC.getReadOnlyParamsByModule(pModuleType)
local moduleDataCombined = commonFunctions:cloneTable(moduleDataReadOnly)
for k, v in pairs(pParams) do
commonRC.getModuleParams(moduleDataCombined)[k] = v
end
local cid = self.mobileSession:SendRPC("SetInteriorVehicleData", {
moduleData = moduleDataCombined
})
EXPECT_HMICALL("RC.SetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleData = moduleDataReadOnly
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = moduleDataReadOnly
})
end)
:ValidIf(function(_, data)
local isFalse = false
for param_readonly, _ in pairs(commonRC.getModuleParams(commonRC.getReadOnlyParamsByModule(pModuleType))) do
for param_actual, _ in pairs(commonRC.getModuleParams(data.params.moduleData)) do
if param_readonly == param_actual then
isFalse = true
commonFunctions:userPrint(36, "Unexpected read-only parameter: " .. param_readonly)
end
end
end
if isFalse then
return false, "Test step failed, see prints"
end
return true
end)
self.mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonRC.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start)
runner.Step("RAI, PTU", commonRC.rai_ptu)
runner.Title("Test")
-- one settable parameter
for _, mod in pairs(modules) do
local settableParams = commonRC.getModuleParams(commonRC.getSettableModuleControlData(mod))
for param, value in pairs(settableParams) do
runner.Step("SetInteriorVehicleData " .. mod .. "_one_settable_param_" .. param, setVehicleData, { mod, { [param] = value } })
end
end
-- all settable parameters
for _, mod in pairs(modules) do
local settableParams = commonRC.getModuleParams(commonRC.getSettableModuleControlData(mod))
runner.Step("SetInteriorVehicleData " .. mod .. "_all_settable_params", setVehicleData, { mod, settableParams })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", commonRC.postconditions)
|
---------------------------------------------------------------------------------------------------
-- Description
-- In case:
-- 1) Application sends valid SetInteriorVehicleData with read-only parameters
-- 2) and one or more settable parameters in "radioControlData" struct, for moduleType: RADIO,
-- SDL must:
-- 1) Cut the read-only parameters off and process this RPC as assigned
-- (that is, check policies, send to HMI, and etc. per existing requirements)
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local commonRC = require('test_scripts/RC/commonRC')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
--[[ Local Variables ]]
local modules = { "CLIMATE", "RADIO" }
local function isModuleDataCorrect(pModuleType, actualModuleData)
local isFalse = false
for param_readonly, _ in pairs(commonRC.getModuleParams(commonRC.getReadOnlyParamsByModule(pModuleType))) do
for param_actual, _ in pairs(commonRC.getModuleParams(actualModuleData)) do
if param_readonly == param_actual then
isFalse = true
commonFunctions:userPrint(36, "Unexpected read-only parameter: " .. param_readonly)
end
end
end
if isFalse then
return false
end
return true
end
local function setVehicleData(pModuleType, pParams, self)
local moduleDataCombined = commonRC.getReadOnlyParamsByModule(pModuleType)
local moduleDataSettable = { moduleType = pModuleType }
for k, v in pairs(pParams) do
commonRC.getModuleParams(moduleDataCombined)[k] = v
commonRC.getModuleParams(moduleDataSettable)[k] = v
end
local cid = self.mobileSession:SendRPC("SetInteriorVehicleData", {
moduleData = moduleDataCombined
})
EXPECT_HMICALL("RC.SetInteriorVehicleData", { appID = self.applications["Test Application"] })
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = moduleDataSettable
})
end)
:ValidIf(function(_, data)
if not isModuleDataCorrect(pModuleType, data.params.moduleData) then
return false, "Test step failed, see prints"
end
return true
end)
self.mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
:ValidIf(function(_, data)
if not isModuleDataCorrect(pModuleType, data.payload.moduleData) then
return false, "Test step failed, see prints"
end
return true
end)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonRC.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start)
runner.Step("RAI, PTU", commonRC.rai_ptu)
runner.Title("Test")
-- one settable parameter
for _, mod in pairs(modules) do
local settableParams = commonRC.getModuleParams(commonRC.getSettableModuleControlData(mod))
for param, value in pairs(settableParams) do
runner.Step("SetInteriorVehicleData " .. mod .. "_one_settable_param_" .. param, setVehicleData, { mod, { [param] = value } })
end
end
-- all settable parameters
for _, mod in pairs(modules) do
local settableParams = commonRC.getModuleParams(commonRC.getSettableModuleControlData(mod))
runner.Step("SetInteriorVehicleData " .. mod .. "_all_settable_params", setVehicleData, { mod, settableParams })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", commonRC.postconditions)
|
SetInteriorVehicleData: fix issues in script
|
SetInteriorVehicleData: fix issues in script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
4df92ab81ab3e6fa7e9070ea6a8a18b84fc2e20d
|
config/init.lua
|
config/init.lua
|
-- Lua configration file for way-cooler. Ran at startup and when restarted.
-- Programs that Way Cooler can run
way_cooler.programs = {
-- Name of the window that will be the bar window.
-- This is a hack to get X11 bars and non-Way Cooler supported bars working.
--
-- Make sure you set your bar program to spawn at startup!
x11_bar = "lemonbar",
-- The path to the lock screen program used by Way Cooler.
-- Once this program has been launched by Way Cooler
-- via the lock_screen keybinding, the screen is locked and all input goes
-- to the lock screen program. Once the program closes, all input is restored.
lock_screen = "wc-lock"
}
-- Registering programs to run at startup
-- These programs are only ran once util.program.spawn_programs is called.
util.program.spawn_at_startup("wc-bg")
-- These options are applied to all windows.
way_cooler.windows = {
gaps = { -- Options for gaps
size = 0, -- The width of gaps between windows in pixels
},
borders = { -- Options for borders
size = 20, -- The width of the borders between windows in pixels
inactive_color = 0x386890, -- Color of the borders for inactive containers
active_color = 0x57beb9 -- Color of active container borders
},
title_bar = { -- Options for title bar above windows
size = 20, -- Size of the title bar
background_color = 0x386690, -- Color of inactive title bar
active_background_color = 0x57beb9, -- Color of active title bar
font_color = 0x0, -- Color of the font for an inactive title bar
active_font_color = 0xffffff -- Color of font for active title bar
}
}
-- Options that change how the mouse behaves.
way_cooler.mouse = {
-- Locks the mouse to the corner of the window the user is resizing.
lock_to_corner_on_resize = false
}
--
-- Keybindings
--
-- Create an array of keybindings and call way_cooler.register_keys()
-- to register them.
-- Declaring a keybinding:
-- key(<modifiers list>, <key>, <function or name>, [repeat])
-- <modifiers list>: Modifiers (mod4, shift, control) to be used
-- <key>: Name of the key to be pressed. See xkbcommon keysym names.
-- <function or name> If a string, the way-cooler command to be run.
-- If a function, a Lua function to run on the keypress. The function takes
-- a list of key names as input (i.e. { "mod4", "shift", "a" }) if needed.
-- [repeat]: Optional boolean defaults to true - if false, the command will
-- will not follow "hold down key to repeat" rules, and will only run once,
-- waiting until the keys are released to run again.
-- Modifier key used in keybindings. Mod3 = Alt, Mod4 = Super/Logo key
mod = "Alt"
-- Aliases to save on typing
local key = way_cooler.key
local keys = {
-- Open dmenu
key({ mod }, "d", util.program.spawn_once("dmenu_run")),
-- Open terminal
key({ mod }, "return", util.program.spawn_once("weston-terminal")),
-- lock screen
key({ mod, "Shift" }, "l", "lock_screen"),
-- Lua methods can be bound as well
key({ mod, "Shift" }, "h", function () print("Hello world!") end),
-- Some Lua dmenu stuff
key({ mod }, "l", "dmenu_eval"),
-- Move focus
key({ mod }, "left", "focus_left"),
key({ mod }, "right", "focus_right"),
key({ mod }, "up", "focus_up"),
key({ mod }, "down", "focus_down"),
-- Move active container
key({ mod, "Shift" }, "left", "move_active_left"),
key({ mod, "Shift" }, "right", "move_active_right"),
key({ mod, "Shift" }, "up", "move_active_up"),
key({ mod, "Shift" }, "down", "move_active_down"),
-- Split containers
key({ mod }, "h", "split_horizontal"),
key({ mod }, "v", "split_vertical"),
key({ mod }, "e", "horizontal_vertical_switch"),
key({ mod }, "s", "tile_stacked"),
key({ mod }, "w", "tile_tabbed"),
key({ mod }, "f", "fullscreen_toggle"),
key({ mod, "Shift" }, "q", "close_window"),
key({ mod, "Shift" }, "space", "toggle_float_active"),
key({ mod }, "space", "toggle_float_focus"),
key({ mod, "Shift" }, "r", "way_cooler_restart"),
-- Quitting way-cooler is hardcoded to Alt+Shift+Esc.
-- If rebound, then this keybinding is cleared.
--key({ mod, "Shift" }, "escape", "way_cooler_quit"),
}
-- Add Mod + X bindings to switch to workspace X, Mod+Shift+X send active to X
for i = 1, 9 do
table.insert(keys,
key({ mod }, tostring(i), "switch_workspace_" .. i))
table.insert(keys,
key({ mod, "Shift" }, tostring(i), "move_to_workspace_" .. i))
end
-- Register the keybindings.
for _, key in pairs(keys) do
way_cooler.register_key(key)
end
-- Register the mod key to also be the mod key for mouse commands
way_cooler.register_mouse_modifier(mod)
-- Execute some code after Way Cooler is finished initializing
way_cooler.on_init = function()
util.program.spawn_startup_programs()
end
--- Execute some code when Way Cooler restarts
way_cooler.on_restart = function()
util.program.restart_startup_programs()
end
--- Execute some code when Way Cooler terminates
way_cooler.on_terminate = function()
util.program.terminate_startup_programs()
end
|
-- Lua configration file for way-cooler. Ran at startup and when restarted.
-- Programs that Way Cooler can run
way_cooler.programs = {
-- Name of the window that will be the bar window.
-- This is a hack to get X11 bars and non-Way Cooler supported bars working.
--
-- Make sure you set your bar program to spawn at startup!
x11_bar = "lemonbar",
}
-- Registering programs to run at startup
-- These programs are only ran once util.program.spawn_programs is called.
util.program.spawn_at_startup("wc-bg")
-- These options are applied to all windows.
way_cooler.windows = {
gaps = { -- Options for gaps
size = 0, -- The width of gaps between windows in pixels
},
borders = { -- Options for borders
size = 20, -- The width of the borders between windows in pixels
inactive_color = 0x386890, -- Color of the borders for inactive containers
active_color = 0x57beb9 -- Color of active container borders
},
title_bar = { -- Options for title bar above windows
size = 20, -- Size of the title bar
background_color = 0x386690, -- Color of inactive title bar
active_background_color = 0x57beb9, -- Color of active title bar
font_color = 0x0, -- Color of the font for an inactive title bar
active_font_color = 0xffffff -- Color of font for active title bar
}
}
-- Options that change how the mouse behaves.
way_cooler.mouse = {
-- Locks the mouse to the corner of the window the user is resizing.
lock_to_corner_on_resize = false
}
--
-- Keybindings
--
-- Create an array of keybindings and call way_cooler.register_keys()
-- to register them.
-- Declaring a keybinding:
-- key(<modifiers list>, <key>, <function or name>, [repeat])
-- <modifiers list>: Modifiers (mod4, shift, control) to be used
-- <key>: Name of the key to be pressed. See xkbcommon keysym names.
-- <function or name> If a string, the way-cooler command to be run.
-- If a function, a Lua function to run on the keypress. The function takes
-- a list of key names as input (i.e. { "mod4", "shift", "a" }) if needed.
-- [repeat]: Optional boolean defaults to true - if false, the command will
-- will not follow "hold down key to repeat" rules, and will only run once,
-- waiting until the keys are released to run again.
-- Modifier key used in keybindings. Mod3 = Alt, Mod4 = Super/Logo key
mod = "Alt"
-- Aliases to save on typing
local key = way_cooler.key
local keys = {
-- Open dmenu
key({ mod }, "d", util.program.spawn_once("dmenu_run")),
-- Open terminal
key({ mod }, "return", util.program.spawn_once("weston-terminal")),
-- lock screen
key({ mod, "Shift" }, "l", util.program.spawn_once("wc-lock")),
-- Lua methods can be bound as well
key({ mod, "Shift" }, "h", function () print("Hello world!") end),
-- Some Lua dmenu stuff
key({ mod }, "l", "dmenu_eval"),
-- Move focus
key({ mod }, "left", "focus_left"),
key({ mod }, "right", "focus_right"),
key({ mod }, "up", "focus_up"),
key({ mod }, "down", "focus_down"),
-- Move active container
key({ mod, "Shift" }, "left", "move_active_left"),
key({ mod, "Shift" }, "right", "move_active_right"),
key({ mod, "Shift" }, "up", "move_active_up"),
key({ mod, "Shift" }, "down", "move_active_down"),
-- Split containers
key({ mod }, "h", "split_horizontal"),
key({ mod }, "v", "split_vertical"),
key({ mod }, "e", "horizontal_vertical_switch"),
key({ mod }, "s", "tile_stacked"),
key({ mod }, "w", "tile_tabbed"),
key({ mod }, "f", "fullscreen_toggle"),
key({ mod, "Shift" }, "q", "close_window"),
key({ mod, "Shift" }, "space", "toggle_float_active"),
key({ mod }, "space", "toggle_float_focus"),
key({ mod, "Shift" }, "r", "way_cooler_restart"),
-- Quitting way-cooler is hardcoded to Alt+Shift+Esc.
-- If rebound, then this keybinding is cleared.
--key({ mod, "Shift" }, "escape", "way_cooler_quit"),
}
-- Add Mod + X bindings to switch to workspace X, Mod+Shift+X send active to X
for i = 1, 9 do
table.insert(keys,
key({ mod }, tostring(i), "switch_workspace_" .. i))
table.insert(keys,
key({ mod, "Shift" }, tostring(i), "move_to_workspace_" .. i))
end
-- Register the keybindings.
for _, key in pairs(keys) do
way_cooler.register_key(key)
end
-- Register the mod key to also be the mod key for mouse commands
way_cooler.register_mouse_modifier(mod)
-- Execute some code after Way Cooler is finished initializing
way_cooler.on_init = function()
util.program.spawn_startup_programs()
end
--- Execute some code when Way Cooler restarts
way_cooler.on_restart = function()
util.program.restart_startup_programs()
end
--- Execute some code when Way Cooler terminates
way_cooler.on_terminate = function()
util.program.terminate_startup_programs()
end
|
Fixed accidental bad rebase
|
Fixed accidental bad rebase
|
Lua
|
mit
|
Immington-Industries/way-cooler,way-cooler/way-cooler,way-cooler/way-cooler,Immington-Industries/way-cooler,way-cooler/way-cooler,Immington-Industries/way-cooler
|
07fb7c841c98a9cb2858f4dd046a4eabc279606f
|
cgi-bin/highscore.lua
|
cgi-bin/highscore.lua
|
#!/usr/bin/env lua
local json = require("dkjson")
local config = require("config")
function template(body, title)
local template = [===[Content-type: text/html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{title}}</title>
<style>
html, body {s
/* From bootstrap */
color: #333;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 1.42857143;
font-size: 14px;
}
.highscore {
margin-top: 10px;
width: 100%;
border: 1px solid #ddd;
}
.highscore > tbody > tr {
height: 2em;
}
.highscore > tbody > tr > th {
border-bottom: 1px solid #ddd;
text-align: left;
padding-left: 0.5em;
}
.highscore > tbody > tr > td {
padding-left: 1em;
}
</style>
</head>
<body>
{{body}}
</body>
</html>
]===]
if type(title) == "string" then
return (template:gsub("{{title}}", "Balloons - " .. title):gsub("{{body}}", "\n" .. body .. "\n"))
else
return (template:gsub("{{title}}", "Balloons"):gsub("{{body}}", "\n" .. body .. "\n"))
end
end
if config.logfile then
function log(...)
local logfile = io.open(config.path .. config.logfile, "a")
if logfile then
local t = {}
for k,v in pairs({...}) do
t[tonumber(k)] = tostring(v)
end
logfile:write(os.date() .. " - " .. table.concat(t, "\t"), "\n")
logfile:close()
end
end
function logf(str, ...)
log(str:format(...))
end
else
function log(...) end
logf = log
end
function htmlescape(str)
if type(str) == "string" then
str = str:gsub("&", "&")
for k,v in pairs({
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["Ä"] = "Ä",
["ä"] = "ä",
["Ö"] = "Ö",
["ö"] = "ö",
["Ü"] = "Ü",
["ü"] = "ü"
}) do
str = str:gsub(k,v)
end
return str
else
return ""
end
end
function unescape (str)
str = string.gsub(str, "+", " ")
str = string.gsub(str, "%%(%x%x)", function (h)
return string.char(tonumber(h, 16))
end)
return str
end
function urldecode(str)
local parms = {}
for name, value in str:gmatch("([^&=]+)=([^&=]+)") do
local name = unescape(name)
local value = unescape(value)
parms[name] = value
end
return parms
end
function urlencode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])", function (c)
return string.format ("%%%02X", string.byte(c))
end)
str = string.gsub (str, " ", "+")
end
return str
end
function httperror(title, str)
local title = tostring(title)
if str then
log("ERROR: " .. title .. " :" .. tostring(str))
-- return ("Content-type: text/html\n\n<h1>%s</h1>\n<p>%s</p>\n"):format(title, str)
return template(("<h1>Error: %s</h1>\n<pre>%s</pre>\n"):format(htmlescape(title), htmlescape(str)),htmlescape(title))
else
log("ERROR: " .. title)
return template(("<h1>Error</h1>\n<pre>%s</pre>\n"):format(htmlescape(title)))
end
end
function addEntry(name, game_config, game_state)
assert(type(name) == "string", "Name not a string")
assert(type(game_config) == "table", "Invalid game config!")
assert(type(game_state) == "table", "Invalid game state!")
assert(tonumber(game_state.total_popped), "Invalid game state! (Missing total_popped)")
local scorefile = assert(io.open(config.path .. config.scorefile, "a"), "Can't open score file!")
scorefile:write(urlencode(name) .. "!" .. os.time() .. "!" .. game_state.total_popped .. "\n")
scorefile:close()
logf("Added highscore entry for %s (score: %d)", name, tonumber(game_state.total_popped))
return true
end
function getEntrys()
local entrys = {}
for line in io.lines(config.path .. config.scorefile) do
if line and #line >= 1 then
local name,time,popped = line:match("(.*)!(%d*)!(%d*)")
if name and tonumber(time) and tonumber(popped) then
entrys[#entrys + 1] = {name=unescape(name), time=tonumber(time), popped=tonumber(popped)}
end
end
end
return entrys
end
function getEntrysTime()
entrys = getEntrys()
table.sort(entrys, function(a, b)
if a.time > b.time then
return true
end
end)
return entrys
end
function getEntrysScore()
entrys = getEntrys()
table.sort(entrys, function(a, b)
if tonumber(a.popped) > tonumber(b.popped) then
return true
end
end)
return entrys
end
function http_GET(parms)
log("GET")
local entrys
local sortby = "score"
if parms.sort == "time" then
sortby = "time"
entrys = getEntrysTime()
else
entrys = getEntrysScore()
end
local str = "<h1>Highscore(1-10) by " .. sortby .. "</h1>\n<table class=\"highscore\">\n\t<tr>\n\t\t<th><b>Name</b></th>\n\t\t<th><b>Date</b></th>\n\t\t<th><b>Score</b></th>\n\t</tr>\n"
for i=1, 10 do
local centry = entrys[i]
if centry then
log("!!!", centry.name, centry.time, centry.popped)
str = str .. ("\t<tr>\n\t\t<td>%s</td>\n\t\t<td>%s</td>\n\t\t<td>%d</td>\n\t</tr>\n"):format(htmlescape(centry.name), os.date("%c", centry.time), centry.popped)
else
break
end
end
str = str .. "</table>\n<p>\n\ttotal entrys: <b>" .. #entrys .. "</b> | <a href=\"/balloons/score.txt\">complete highscore dump</a>\n</p>\n"
return template(str, "highscore")
end
function http_POST(parms, body)
log("POST")
local valid_config, config = pcall(json.decode, body.config)
local valid_state, state = pcall(json.decode, body.state)
if valid_config and valid_state then
local ok, ret = pcall(addEntry, body.name, config, state)
if ok then
return http_GET(parms)
else
return httperror("Bad Entry! Error: " .. tostring(ret))
end
else
return httperror("Invalid JSON!")
end
end
log(("="):rep(40))
log("Started!")
if _G["http_" .. tostring(os.getenv("REQUEST_METHOD"))] then
-- Diabolic...
io.write((_G["http_" .. os.getenv("REQUEST_METHOD"):upper()](urldecode(os.getenv("QUERY_STRING") or ""), urldecode(io.read("*a") or ""))))
else
io.write("Content-type: text/html\n\n<h1>Unknown method!</h1>")
end
io.close()
|
#!/usr/bin/env lua
local json = require("dkjson")
local config = require("config")
function template(body, title)
-- TODO: Make sure here are no pattern-characters!
local body = tostring(body):gsub("%%", "%%%%")
local title = tostring(title):gsub("%%", "%%%%")
local template = [===[Content-type: text/html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{title}}</title>
<style>
html, body {s
/* From bootstrap */
color: #333;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 1.42857143;
font-size: 14px;
}
.highscore {
margin-top: 10px;
width: 100%;
border: 1px solid #ddd;
}
.highscore > tbody > tr {
height: 2em;
}
.highscore > tbody > tr > th {
border-bottom: 1px solid #ddd;
text-align: left;
padding-left: 0.5em;
}
.highscore > tbody > tr > td {
padding-left: 1em;
}
</style>
</head>
<body>
{{body}}
</body>
</html>
]===]
if type(title) == "string" then
return (template:gsub("{{title}}", "Balloons - " .. title):gsub("{{body}}", "\n" .. body .. "\n"))
else
return (template:gsub("{{title}}", "Balloons"):gsub("{{body}}", "\n" .. body .. "\n"))
end
end
if config.logfile then
function log(...)
local logfile = io.open(config.path .. config.logfile, "a")
if logfile then
local t = {}
for k,v in pairs({...}) do
t[tonumber(k)] = tostring(v)
end
logfile:write(os.date() .. " - " .. table.concat(t, "\t"), "\n")
logfile:close()
end
end
function logf(str, ...)
log(str:format(...))
end
else
function log(...) end
logf = log
end
function htmlescape(str)
if type(str) == "string" then
str = str:gsub("&", "&")
for k,v in pairs({
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["Ä"] = "Ä",
["ä"] = "ä",
["Ö"] = "Ö",
["ö"] = "ö",
["Ü"] = "Ü",
["ü"] = "ü"
}) do
str = str:gsub(k,v)
end
return str
else
return ""
end
end
function unescape (str)
str = string.gsub(str, "+", " ")
str = string.gsub(str, "%%(%x%x)", function (h)
return string.char(tonumber(h, 16))
end)
return str
end
function urldecode(str)
local parms = {}
for name, value in str:gmatch("([^&=]+)=([^&=]+)") do
local name = unescape(name)
local value = unescape(value)
parms[name] = value
end
return parms
end
function urlencode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])", function (c)
return string.format ("%%%02X", string.byte(c))
end)
str = string.gsub (str, " ", "+")
end
return str
end
function httperror(title, str)
local title = tostring(title)
if str then
log("ERROR: " .. title .. " :" .. tostring(str))
-- return ("Content-type: text/html\n\n<h1>%s</h1>\n<p>%s</p>\n"):format(title, str)
return template(("<h1>Error: %s</h1>\n<pre>%s</pre>\n"):format(htmlescape(title), htmlescape(str)),htmlescape(title))
else
log("ERROR: " .. title)
return template(("<h1>Error</h1>\n<pre>%s</pre>\n"):format(htmlescape(title)))
end
end
function addEntry(name, game_config, game_state)
assert(type(name) == "string", "Name not a string")
assert(type(game_config) == "table", "Invalid game config!")
assert(type(game_state) == "table", "Invalid game state!")
assert(tonumber(game_state.total_popped), "Invalid game state! (Missing total_popped)")
local scorefile = assert(io.open(config.path .. config.scorefile, "a"), "Can't open score file!")
scorefile:write(urlencode(name) .. "!" .. os.time() .. "!" .. game_state.total_popped .. "\n")
scorefile:close()
logf("Added highscore entry for %s (score: %d)", name, tonumber(game_state.total_popped))
return true
end
function getEntrys()
local entrys = {}
for line in io.lines(config.path .. config.scorefile) do
if line and #line >= 1 then
local name,time,popped = line:match("(.*)!(%d*)!(%d*)")
if name and tonumber(time) and tonumber(popped) then
entrys[#entrys + 1] = {name=unescape(name), time=tonumber(time), popped=tonumber(popped)}
end
end
end
return entrys
end
function getEntrysTime()
entrys = getEntrys()
table.sort(entrys, function(a, b)
if a.time > b.time then
return true
end
end)
return entrys
end
function getEntrysScore()
entrys = getEntrys()
table.sort(entrys, function(a, b)
if tonumber(a.popped) > tonumber(b.popped) then
return true
end
end)
return entrys
end
function http_GET(parms)
log("GET")
local entrys
local sortby = "score"
if parms.sort == "time" then
sortby = "time"
entrys = getEntrysTime()
else
entrys = getEntrysScore()
end
local str = "<h1>Highscore(1-10) by " .. sortby .. "</h1>\n<table class=\"highscore\">\n\t<tr>\n\t\t<th><b>Name</b></th>\n\t\t<th><b>Date</b></th>\n\t\t<th><b>Score</b></th>\n\t</tr>\n"
for i=1, 10 do
local centry = entrys[i]
if centry then
log("!!!", centry.name, centry.time, centry.popped)
str = str .. ("\t<tr>\n\t\t<td>%s</td>\n\t\t<td>%s</td>\n\t\t<td>%d</td>\n\t</tr>\n"):format(htmlescape(centry.name), os.date("%c", centry.time), centry.popped)
else
break
end
end
str = str .. "</table>\n<p>\n\ttotal entrys: <b>" .. #entrys .. "</b> | <a href=\"/balloons/score.txt\">complete highscore dump</a>\n</p>\n"
return template(str, "highscore")
end
function http_POST(parms, body)
log("POST")
local valid_config, config = pcall(json.decode, body.config)
local valid_state, state = pcall(json.decode, body.state)
if valid_config and valid_state then
local ok, ret = pcall(addEntry, body.name, config, state)
if ok then
return http_GET(parms)
else
return httperror("Bad Entry! Error: " .. tostring(ret))
end
else
return httperror("Invalid JSON!")
end
end
log(("="):rep(40))
log("Started!")
if _G["http_" .. tostring(os.getenv("REQUEST_METHOD"))] then
-- Diabolic...
io.write((_G["http_" .. os.getenv("REQUEST_METHOD"):upper()](urldecode(os.getenv("QUERY_STRING") or ""), urldecode(io.read("*a") or ""))))
else
io.write("Content-type: text/html\n\n<h1>Unknown method!</h1>")
end
io.close()
|
Fixed bug in template system
|
Fixed bug in template system
|
Lua
|
mit
|
max1220/balloons,max1220/balloons,max1220/balloons
|
c81ca8dae3e914b41b754e1cdc7cad3aeead9e66
|
applications/luci-app-ocserv/luasrc/model/cbi/ocserv/main.lua
|
applications/luci-app-ocserv/luasrc/model/cbi/ocserv/main.lua
|
-- Copyright 2014 Nikos Mavrogiannopoulos <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
local o_sha = s:taboption("general", DummyValue, "sha_hash", translate("Server's certificate SHA1 hash"),
translate("That value should be communicated to the client to verify the server's certificate"))
local o_pki = s:taboption("general", DummyValue, "pkid", translate("Server's Public Key ID"),
translate("An alternative value to be communicated to the client to verify the server's certificate; this value only depends on the public key"))
local fd = io.popen("/usr/bin/certtool -i --infile /etc/ocserv/server-cert.pem", "r")
if fd then local ln
local found_sha = false
local found_pki = false
local complete = 0
while complete < 2 do
local ln = fd:read("*l")
if not ln then
break
elseif ln:match("SHA%-?1 fingerprint:") then
found_sha = true
elseif found_sha then
local hash = ln:match("([a-f0-9]+)")
o_sha.default = hash and hash:upper()
complete = complete + 1
found_sha = false
elseif ln:match("Public Key I[Dd]:") then
found_pki = true
elseif found_pki then
local hash = ln:match("([a-f0-9]+)")
o_pki.default = hash and "sha1:" .. hash:upper()
complete = complete + 1
found_pki = false
end
end
fd:close()
end
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local compr = s:taboption("general", Flag, "compression", translate("Enable compression"),
translate("Enable compression"))
compr.default = "0"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[Networking options]]--
local parp = s:taboption("general", Flag, "proxy_arp", translate("Enable proxy arp"),
translate("Provide addresses to clients from a subnet of LAN; if enabled the network below must be a subnet of LAN. Note that the first address of the specified subnet will be reserved by ocserv, so it should not be in use. If you have a network in LAN covering 192.168.1.0/24 use 192.168.1.192/26 to reserve the upper 62 addresses."))
parp.default = "0"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"),
translate("The IPv4 subnet address to provide to clients; this should be some private network different than the LAN addresses unless proxy ARP is enabled. Leave empty to attempt auto-configuration."))
ipaddr.datatype = "ip4addr"
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"),
translate("The mask of the subnet above."))
nm.datatype = "ip4addr"
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"),
translate("The IPv6 subnet address to provide to clients; leave empty to attempt auto-configuration."))
ip6addr.datatype = "ip6addr"
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4. Typically you should include the address of this device"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
s.datatype = "ipaddr"
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
|
-- Copyright 2014 Nikos Mavrogiannopoulos <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
local o_pki = s:taboption("general", DummyValue, "pkid", translate("Server's Public Key ID"),
translate("The value to be communicated to the client to verify the server's certificate; this value only depends on the public key"))
local fd = io.popen("/usr/bin/certtool --hash sha256 --key-id --infile /etc/ocserv/server-cert.pem", "r")
if fd then local ln
local ln = fd:read("*l")
if ln then
o_pki.default = "sha256:" .. ln
end
fd:close()
end
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local compr = s:taboption("general", Flag, "compression", translate("Enable compression"),
translate("Enable compression"))
compr.default = "0"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[Networking options]]--
local parp = s:taboption("general", Flag, "proxy_arp", translate("Enable proxy arp"),
translate("Provide addresses to clients from a subnet of LAN; if enabled the network below must be a subnet of LAN. Note that the first address of the specified subnet will be reserved by ocserv, so it should not be in use. If you have a network in LAN covering 192.168.1.0/24 use 192.168.1.192/26 to reserve the upper 62 addresses."))
parp.default = "0"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"),
translate("The IPv4 subnet address to provide to clients; this should be some private network different than the LAN addresses unless proxy ARP is enabled. Leave empty to attempt auto-configuration."))
ipaddr.datatype = "ip4addr"
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"),
translate("The mask of the subnet above."))
nm.datatype = "ip4addr"
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"),
translate("The IPv6 subnet address to provide to clients; leave empty to attempt auto-configuration."))
ip6addr.datatype = "ip6addr"
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4. Typically you should include the address of this device"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
s.datatype = "ipaddr"
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
|
ocserv: fix the public key ID calculation
|
ocserv: fix the public key ID calculation
New versions of certtool change its output format and thus break
the previous parsing. This update works with certtool 3.5.x or later.
It also restricts the output to valid values for openconnect 7.x or
later for simplification.
Signed-off-by: Nikos Mavrogiannopoulos <[email protected]>
|
Lua
|
apache-2.0
|
lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,openwrt/luci,hnyman/luci,rogerpueyo/luci,rogerpueyo/luci,hnyman/luci,openwrt/luci,rogerpueyo/luci,tobiaswaldvogel/luci,openwrt/luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,rogerpueyo/luci,tobiaswaldvogel/luci,openwrt/luci,tobiaswaldvogel/luci,openwrt/luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci
|
fcde0d9d52caee19bf7a101b896fb41328e48eb2
|
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 (for T7)
-- 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.
local NumFuncs = 2 -- Number of functions being executed in scheduler. Must equal number of fuction defined in the scheduler table.
local MsgThresh = 1 -- Allowable number of scheduler tics beyond function period before posting a warning.
local IntvlCnt = 0
local 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.
local checkInterval=LJ.CheckInterval
local 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 = 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.
local 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
--==============================================================================
|
--[[
Name: task-scheduler_1.0.lua
Desc: This script demonstrates a simple task scheduler used to execute
multiple tasks at regular intervals to 1ms resolution
Note: Requires Firmware 1.0199 or higher (for T7)
Increase scheduler resolution to reduce CPU load on the T7 processor
--]]
print("LabJack Lua Task Scheduler Example. Version 1.0")
-- 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
-- Number of functions being executed in the scheduler
-- Must equal the number of a function defined in the scheduler table
local numfuncs = 2
-- Allowable number of scheduler tics beyond function period before posting
-- a warning
local msgthreshold = 1
local intervalcount = 0
local schedule = {}
-- New row (1 row per function)
schedule[0] = {}
-- New row (1 row per function)
schedule[1] = {}
-- Function1 name
schedule[0][0] = "func1"
-- Function1 counter. The function will execute when this value equals zero.
-- Set to a positive nonzero number to set the delay before first execution
schedule[0][1] = 10
-- Function1 period
schedule[0][2] = 50
-- Function1 parameters (if required)
schedule[0][3] = {}
-- Function2 name
schedule[1][0] = "func2"
-- Function2 counter. The function will execute when this value equals zero.
-- Set to a positive nonzero number to set the delay before first execution
schedule[1][1] = 10
-- Function2 period
schedule[1][2] = 500
-- Function2 parameters (if required)
schedule[1][3] = {}
-- Define the scheduler resolution (1 ms). Increase if necessary
LJ.IntervalConfig(0, 1)
local test = 0
-------------------------------------------------------------------------------
-- Desc: Task function definitions
-- Note: 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
-------------------------------------------------------------------------------
-- Desc: Task Scheduler
-- Note: No need to modify the scheduler main loop. The scheduler will execute
-- any number of tasks defined in the task table.
-------------------------------------------------------------------------------
while true do
-- Save the count to catch missed interval servicing
intervalcount = LJ.CheckInterval(0)
if (intervalcount) 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 interval
-- count will normally equal 1, unless some delay causes
-- script to go multiple intervals between checks. Adjust function
-- counter accordingly to maintain function timing
local delay = intervalcount - schedule[i][1]
schedule[i][1] = schedule[i][1] - intervalcount
-- Call a function when counter reaches zero.
if(schedule[i][1] <= 0) then
-- Post a message if we see the function execution time was delayed too long
if (schedule[i][1] < 0) then
print("Warning: Function", i, "delayed by", delay, "ms")
end
-- Execute Task
--_G["func1"](params{})
-- Call the function from the global namespace
_G[schedule[i][0]](schedule[1][3])
-- Reset the function counter
schedule[i][1] = schedule[i][2]
end
end
end
end
|
Fixed up the formatting of the task scheduler example
|
Fixed up the formatting of the task scheduler example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
61372e1e253daa78084909dcc3fa190bf3a74772
|
kong/plugins/acl/migrations/003_200_to_210.lua
|
kong/plugins/acl/migrations/003_200_to_210.lua
|
local operations = require "kong.db.migrations.operations.200_to_210"
local plugin_entities = {
{
name = "acls",
primary_key = "id",
uniques = {},
fks = {{name = "consumer", reference = "consumers", on_delete = "cascade"}},
}
}
local function ws_migration_up(ops)
return ops:ws_adjust_fields(plugin_entities)
end
local function ws_migration_teardown(ops)
return function(connector)
local _, err = ops:ws_adjust_data(connector, plugin_entities)
if err then
return nil, err
end
_, err = ops:fixup_plugin_config(connector, "acl", function(config)
config.allow = config.whitelist
config.whitelist = nil
config.deny = config.blacklist
config.blacklist = nil
return true
end)
if err then
return nil, err
end
return true
end
end
return {
postgres = {
up = ws_migration_up(operations.postgres.up),
teardown = ws_migration_teardown(operations.postgres.teardown),
},
cassandra = {
up = ws_migration_up(operations.cassandra.up),
teardown = ws_migration_teardown(operations.cassandra.teardown),
},
}
|
local operations = require "kong.db.migrations.operations.200_to_210"
local plugin_entities = {
{
name = "acls",
primary_key = "id",
uniques = {},
cache_key = { "consumer", "group" },
fks = {{name = "consumer", reference = "consumers", on_delete = "cascade"}},
}
}
local function ws_migration_up(ops)
return ops:ws_adjust_fields(plugin_entities)
end
local function ws_migration_teardown(ops)
return function(connector)
local _, err = ops:ws_adjust_data(connector, plugin_entities)
if err then
return nil, err
end
_, err = ops:fixup_plugin_config(connector, "acl", function(config)
config.allow = config.whitelist
config.whitelist = nil
config.deny = config.blacklist
config.blacklist = nil
return true
end)
if err then
return nil, err
end
return true
end
end
return {
postgres = {
up = ws_migration_up(operations.postgres.up),
teardown = ws_migration_teardown(operations.postgres.teardown),
},
cassandra = {
up = ws_migration_up(operations.cassandra.up),
teardown = ws_migration_teardown(operations.cassandra.teardown),
},
}
|
fix(migrations) acl migrations did not specify cache_key
|
fix(migrations) acl migrations did not specify cache_key
### Summary
This fixes ACLs migrations by telling migration function about the composite
cache key that need to be updated with workspace.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
7ea1a4b995d6dd5410cc9b0637b6d7a4324cd638
|
OS/DiskOS/Libraries/parser/languages/lua.lua
|
OS/DiskOS/Libraries/parser/languages/lua.lua
|
local keywords = {
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "if",
"in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
}
local api = getAPI()
local callbacks = {"_draw","_init","_keypressed","_keyreleased","_mousemoved","_mousepressed","_mousereleased","_textinput","_touchcontrol","_touchmoved","_touchpressed","_touchreleased","_update","_wheelmoved"}
local escapable = {"a", "b", "f", "n", "r", "t", "v", "\\", "\"", "'"}
-- Convert values to keys
for _, list in ipairs({keywords, api, callbacks, escapable}) do
for i, word in ipairs(list) do
list[word] = true
list[i] = nil
end
end
function startState()
return {
tokenizer = "base",
starter = ""
}
end
function token(stream, state)
local result = nil
if state.tokenizer == "base" then
char = stream:next()
-- Comment and multiline comment matching
if char == "-" and stream:eat('%-') then
if stream:match("%[%[") then
state.tokenizer = "multilineComment"
else
stream:skipToEnd()
result = "comment"
end
-- String matching
elseif char == "\"" or char == "'" then
state.starter = char
state.tokenizer = "string"
-- Decimal numbers
elseif char == '.' and stream:match('%d+') then
result = 'number'
-- Hex
elseif char == "0" and stream:eat("[xX]") then
stream:eatWhile("%x")
result = "number"
-- Ints and floats numbers
elseif char:find('%d') then
stream:eatWhile("%d")
stream:match("\\.%d+")
local nextChar = stream:peek() or "" -- TODO: Do this to hex and decimals too
if not nextChar:find("[%w_]") then
result = "number"
end
-- elseif operators[char] then
-- return 'operator'
-- Multiline string matching
elseif char == "[" and stream:eat("%[") then
state.tokenizer = "multilineString"
-- Keyword matching
elseif char:find('[%w_]') then
stream:eatWhile('[%w_]')
local word = stream:current()
if keywords[word] then
result = "keyword"
elseif api[word] then
result = "api"
elseif callbacks[word] then
result = "callback"
end
end
end
if state.tokenizer == "string" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == state.starter then
state.starter = ""
state.tokenizer = "base"
--else
-- stream:skipToEnd()
else
if stream:eol() then state.tokenizer = "base" end
end
elseif state.tokenizer == "multilineString" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == "]" and stream:eat("%]") then
state.tokenizer = "base"
end
elseif state.tokenizer == "multilineComment" then
if stream:skipTo("%]%]") then
stream:next()
state.tokenizer = "base"
else
stream:skipToEnd()
end
result = "comment"
end
return result
end
return {
startState = startState,
token = token
}
|
local keywords = {
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function", "if",
"in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
}
local api = getAPI()
local callbacks = {"_draw","_init","_keypressed","_keyreleased","_mousemoved","_mousepressed","_mousereleased","_textinput","_touchcontrol","_touchmoved","_touchpressed","_touchreleased","_update","_wheelmoved"}
local escapable = {"a", "b", "f", "n", "r", "t", "v", "\\", "\"", "'"}
-- Convert values to keys
for _, list in ipairs({keywords, api, callbacks, escapable}) do
for i, word in ipairs(list) do
list[word] = true
list[i] = nil
end
end
function startState()
return {
tokenizer = "base",
starter = ""
}
end
function token(stream, state)
local result = nil
if state.tokenizer == "base" then
char = stream:next()
-- Comment and multiline comment matching
if char == "-" and stream:eat('%-') then
if stream:match("%[%[") then
state.tokenizer = "multilineComment"
else
stream:skipToEnd()
result = "comment"
end
-- String matching
elseif char == "\"" or char == "'" then
state.starter = char
state.tokenizer = "string"
return "string" -- Return immediatelly so quotes doesn't get affected by escape sequences
-- Decimal numbers
elseif char == '.' and stream:match('%d+') then
result = 'number'
-- Hex
elseif char == "0" and stream:eat("[xX]") then
stream:eatWhile("%x")
result = "number"
-- Ints and floats numbers
elseif char:find('%d') then
stream:eatWhile("%d")
stream:match("\\.%d+")
local nextChar = stream:peek() or "" -- TODO: Do this to hex and decimals too
if not nextChar:find("[%w_]") then
result = "number"
end
-- elseif operators[char] then
-- return 'operator'
-- Multiline string matching
elseif char == "[" and stream:eat("%[") then
state.tokenizer = "multilineString"
return "string"
-- Keyword matching
elseif char:find('[%w_]') then
stream:eatWhile('[%w_]')
local word = stream:current()
if keywords[word] then
result = "keyword"
elseif api[word] then
result = "api"
elseif callbacks[word] then
result = "callback"
end
end
end
if state.tokenizer == "string" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == state.starter then
state.starter = ""
state.tokenizer = "base"
--else
-- stream:skipToEnd()
else
if stream:eol() then state.tokenizer = "base" end
end
elseif state.tokenizer == "multilineString" then
char = stream:next()
result = "string"
if char == "\\" then
escaped = stream:peek()
if escaped and escapable[escaped] then
stream:next()
result = "escape"
end
elseif char == "]" and stream:eat("%]") then
state.tokenizer = "base"
end
elseif state.tokenizer == "multilineComment" then
if stream:skipTo("%]%]") then
stream:next()
state.tokenizer = "base"
else
stream:skipToEnd()
end
result = "comment"
end
return result
end
return {
startState = startState,
token = token
}
|
Fix syntax parsing
|
Fix syntax parsing
Fix a bug in the string parser where the opening quotation marks are
included in the first token returned.
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
2a29fd6c0ce846a6456b40a2882eec290bc20bd4
|
agents/monitoring/default/check/disk.lua
|
agents/monitoring/default/check/disk.lua
|
--[[
Copyright 2012 Rackspace
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 BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local DiskCheck = BaseCheck:extend()
function DiskCheck:initialize(params)
BaseCheck.initialize(self, 'agent.disk', params)
end
-- Dimension key is the mount point name, e.g. /, /home
function DiskCheck:run(callback)
-- Perform Check
local s = sigar:new()
local disks = s:disks()
local checkResult = CheckResult:new(self, {})
local name, usage
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
for key, value in pairs(usage) do
checkResult:addMetric(key, name, nil, value)
end
end
end
-- Return Result
self._lastResult = checkResult
callback(checkResult)
end
local exports = {}
exports.DiskCheck = DiskCheck
return exports
|
--[[
Copyright 2012 Rackspace
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 BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local DiskCheck = BaseCheck:extend()
function DiskCheck:initialize(params)
BaseCheck.initialize(self, 'agent.disk', params)
end
-- Dimension key is the mount point name, e.g. /, /home
function DiskCheck:run(callback)
-- Perform Check
local s = sigar:new()
local disks = s:disks()
local checkResult = CheckResult:new(self, {})
local name, usage
local metrics = {
'reads',
'writes',
'read_bytes',
'write_bytes',
'rtime',
'wtime',
'qtime',
'time',
'service_time',
'queue'
}
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
for _, key in pairs(metrics) do
checkResult:addMetric(key, name, nil, usage[key])
end
end
end
-- Return Result
self._lastResult = checkResult
callback(checkResult)
end
local exports = {}
exports.DiskCheck = DiskCheck
return exports
|
fixes: remove snaptime metric
|
fixes: remove snaptime metric
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
0023bd375b2d1a2a240c7667cd95b8cc20698ac7
|
mod_auth_external/mod_auth_external.lua
|
mod_auth_external/mod_auth_external.lua
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
assert(not host:find(":"), "Invalid hostname");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false });
function send_query(text)
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
return pty:read(read_timeout);
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
end
if script_type == "generic" then
query = query..'\n';
end
local response = send_query(query);
if (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
if response then
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
else
log("warn", "Error while waiting for result from auth process: %s", response or "unknown error");
end
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
assert(not host:find(":"), "Invalid hostname");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false });
function send_query(text)
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
return pty:read(read_timeout);
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
end
if script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
mod_auth_external: Fix logging of errors
|
mod_auth_external: Fix logging of errors
|
Lua
|
mit
|
syntafin/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,either1/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,prosody-modules/import,dhotson/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,prosody-modules/import,heysion/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules
|
2852e64fe91134e307908c9245210115b07b2e70
|
src/luarocks/add.lua
|
src/luarocks/add.lua
|
--- Module implementing the luarocks-admin "add" command.
-- Adds a rock or rockspec to a rocks server.
module("luarocks.add", package.seeall)
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local fetch = require("luarocks.fetch")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local fs = require("luarocks.fs")
help_summary = "Add a rock or rockpec to a rocks server."
help_arguments = "[--to=<server>] {<rockspec>|<rock>]}"
help = [[
Argument may be a local rockspec or rock file.
The flag --to indicates which server to use.
If not given, the default server set in the upload_server variable
from the configuration file is used instead.
]]
local function split_server_url(server, user, password)
local protocol, server_path = dir.split_url(server)
if server_path:match("@") then
local credentials
credentials, server_path = server_path:match("([^@]*)@(.*)")
if credentials:match(":") then
user, password = credentials:match("([^:]*):(.*)")
else
user = credentials
end
end
local local_cache
if cfg.local_cache then
local_cache = cfg.local_cache .. "/" .. server_path
end
return local_cache, protocol, server_path, user, password
end
local function refresh_local_cache(server, user, password)
local local_cache, protocol, server_path, user, password = split_server_url(server, user, password)
fs.make_dir(cfg.local_cache)
local tmp_cache = false
if not local_cache then
local_cache = fs.make_temp_dir("local_cache")
tmp_cache = true
end
local ok = fs.make_dir(local_cache)
if not ok then
return nil, "Failed creating local cache dir."
end
fs.change_dir(local_cache)
print("Refreshing cache "..local_cache.."...")
local login_info = ""
if user then login_info = " --user="..user end
if password then login_info = login_info .. " --password="..password end
fs.execute("wget -q -m -nd "..protocol.."://"..server_path..login_info)
return local_cache, protocol, server_path, user, password
end
local function add_file_to_server(refresh, rockfile, server)
if not fs.exists(rockfile) then
return nil, "Could not find "..rockfile
end
local local_cache, protocol, server_path, user, password
if refresh then
local_cache, protocol, server_path, user, password = refresh_local_cache(server, cfg.upload_user, cfg.upload_password)
else
local_cache, protocol, server_path, user, password = split_server_url(server, cfg.upload_user, cfg.upload_password)
end
fs.change_dir(local_cache)
local rockfile = fs.absolute_name(rockfile)
print("Copying file "..rockfile.." to "..local_cache.."...")
fs.copy(rockfile, local_cache)
print("Updating manifest...")
manif.make_manifest(local_cache)
print("Updating index.html...")
manif.make_index(local_cache)
local login_info = ""
if user then login_info = " -u "..user end
if password then login_info = login_info..":"..password end
if not server_path:match("/$") then
server_path = server_path .. "/"
end
fs.execute("curl "..login_info.." -T '{manifest,index.html,"..dir.base_name(rockfile).."}' "..protocol.."://"..server_path)
return true
end
function run(...)
local flags, file = util.parse_flags(...)
if type(file) ~= "string" then
return nil, "Argument missing, see help."
end
local server = flags["to"]
if not server then server = cfg.upload_server end
if not server then
return nil, "No server specified with --to and no default configured with upload_server."
end
if cfg.upload_aliases then
server = cfg.upload_aliases[server] or server
end
return add_file_to_server(not flags["no-refresh"], file, server)
end
|
--- Module implementing the luarocks-admin "add" command.
-- Adds a rock or rockspec to a rocks server.
module("luarocks.add", package.seeall)
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local fetch = require("luarocks.fetch")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local fs = require("luarocks.fs")
help_summary = "Add a rock or rockpec to a rocks server."
help_arguments = "[--to=<server>] {<rockspec>|<rock>]}"
help = [[
Argument may be a local rockspec or rock file.
The flag --to indicates which server to use.
If not given, the default server set in the upload_server variable
from the configuration file is used instead.
]]
local function split_server_url(server, user, password)
local protocol, server_path = dir.split_url(server)
if server_path:match("@") then
local credentials
credentials, server_path = server_path:match("([^@]*)@(.*)")
if credentials:match(":") then
user, password = credentials:match("([^:]*):(.*)")
else
user = credentials
end
end
local local_cache
if cfg.local_cache then
local_cache = cfg.local_cache .. "/" .. server_path
end
return local_cache, protocol, server_path, user, password
end
local function refresh_local_cache(server, user, password)
local local_cache, protocol, server_path, user, password = split_server_url(server, user, password)
fs.make_dir(cfg.local_cache)
local tmp_cache = false
if not local_cache then
local_cache = fs.make_temp_dir("local_cache")
tmp_cache = true
end
local ok = fs.make_dir(local_cache)
if not ok then
return nil, "Failed creating local cache dir."
end
fs.change_dir(local_cache)
print("Refreshing cache "..local_cache.."...")
local login_info = ""
if user then login_info = " --user="..user end
if password then login_info = login_info .. " --password="..password end
fs.execute("wget -q -m -nd "..protocol.."://"..server_path..login_info)
return local_cache, protocol, server_path, user, password
end
local function add_file_to_server(refresh, rockfile, server)
if not fs.exists(rockfile) then
return nil, "Could not find "..rockfile
end
local rockfile = fs.absolute_name(rockfile)
local local_cache, protocol, server_path, user, password
if refresh then
local_cache, protocol, server_path, user, password = refresh_local_cache(server, cfg.upload_user, cfg.upload_password)
else
local_cache, protocol, server_path, user, password = split_server_url(server, cfg.upload_user, cfg.upload_password)
end
fs.change_dir(local_cache)
print("Copying file "..rockfile.." to "..local_cache.."...")
fs.copy(rockfile, local_cache)
print("Updating manifest...")
manif.make_manifest(local_cache)
print("Updating index.html...")
manif.make_index(local_cache)
local login_info = ""
if user then login_info = " -u "..user end
if password then login_info = login_info..":"..password end
if not server_path:match("/$") then
server_path = server_path .. "/"
end
fs.execute("curl "..login_info.." -T '{manifest,index.html,"..dir.base_name(rockfile).."}' "..protocol.."://"..server_path)
return true
end
function run(...)
local flags, file = util.parse_flags(...)
if type(file) ~= "string" then
return nil, "Argument missing, see help."
end
local server = flags["to"]
if not server then server = cfg.upload_server end
if not server then
return nil, "No server specified with --to and no default configured with upload_server."
end
if cfg.upload_aliases then
server = cfg.upload_aliases[server] or server
end
return add_file_to_server(not flags["no-refresh"], file, server)
end
|
fix use of relative paths
|
fix use of relative paths
git-svn-id: b90ab2797f6146e3ba3e3d8b20782c4c2887e809@50 9ca3f7c1-7366-0410-b1a3-b5c78f85698c
|
Lua
|
mit
|
tst2005/luarocks,starius/luarocks,starius/luarocks,xpol/luainstaller,xiaq/luarocks,xpol/luarocks,aryajur/luarocks,lxbgit/luarocks,starius/luarocks,lxbgit/luarocks,keplerproject/luarocks,tarantool/luarocks,xpol/luainstaller,aryajur/luarocks,tst2005/luarocks,ignacio/luarocks,xpol/luavm,coderstudy/luarocks,xpol/luavm,ignacio/luarocks,coderstudy/luarocks,xiaq/luarocks,coderstudy/luarocks,rrthomas/luarocks,usstwxy/luarocks,leafo/luarocks,xpol/luarocks,aryajur/luarocks,xpol/luainstaller,xpol/luainstaller,robooo/luarocks,ignacio/luarocks,luarocks/luarocks,leafo/luarocks,rrthomas/luarocks,luarocks/luarocks,usstwxy/luarocks,keplerproject/luarocks,coderstudy/luarocks,tarantool/luarocks,rrthomas/luarocks,robooo/luarocks,xpol/luavm,ignacio/luarocks,tarantool/luarocks,leafo/luarocks,starius/luarocks,usstwxy/luarocks,xiaq/luarocks,luarocks/luarocks,keplerproject/luarocks,tst2005/luarocks,xpol/luarocks,xpol/luavm,lxbgit/luarocks,xiaq/luarocks,lxbgit/luarocks,keplerproject/luarocks,tst2005/luarocks,usstwxy/luarocks,robooo/luarocks,rrthomas/luarocks,aryajur/luarocks,robooo/luarocks,xpol/luavm,xpol/luarocks
|
a5cbe9808b73158fcc182db040dd98383f2c38a9
|
libs/uvl/luasrc/uvl/errors.lua
|
libs/uvl/luasrc/uvl/errors.lua
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <[email protected]>
(c) 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 uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
{ 'UCILOAD', 'Unable to load config "%p": %1' },
{ 'SCHEME', 'Error in scheme "%p":\n%c' },
{ 'CONFIG', 'Error in config "%p":\n%c' },
{ 'SECTION', 'Error in section "%i" (%I):\n%c' },
{ 'OPTION', 'Error in option "%i" (%I):\n%c' },
{ 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' },
{ 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' },
{ 'SME_FIND', 'Can not find scheme "%p" in "%1"' },
{ 'SME_READ', 'Can not access file "%1"' },
{ 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' },
{ 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' },
{ 'SME_BADREF', 'Malformed reference in "%1"' },
{ 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' },
{ 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' },
{ 'SME_ERRVAL', 'External validator "%1" failed: %2' },
{ 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' },
{ 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' },
{ 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' },
{ 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' },
{ 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' },
{ 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' },
{ 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' },
{ 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' },
{ 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' },
{ 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' },
{ 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' },
{ 'OPT_REQUIRED', 'Required option "%i" has no value' },
{ 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' },
{ 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' },
{ 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' },
{ 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' },
{ 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' },
{ 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' },
{ 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' },
{ 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' },
{ 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' },
{ 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' },
{ 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' }
}
-- build error constants and instance constructors
for i, v in ipairs(ERRCODES) do
_M[v[1]] = function(...)
return error(i, ...)
end
_M['ERR_'..v[1]] = i
end
function i18n(key, def)
if luci.i18n then
return luci.i18n.translate(key,def)
else
return def
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(
'uvl_err_%s' % string.lower(ERRCODES[self.code][1]),
ERRCODES[self.code][2]
)
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <[email protected]>
(c) 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 uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
{ 'UCILOAD', 'Unable to load config "%p": %1' },
{ 'SCHEME', 'Error in scheme "%p":\n%c' },
{ 'CONFIG', 'Error in config "%p":\n%c' },
{ 'SECTION', 'Error in section "%i" (%I):\n%c' },
{ 'OPTION', 'Error in option "%i" (%I):\n%c' },
{ 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' },
{ 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' },
{ 'SME_FIND', 'Can not find scheme "%p" in "%1"' },
{ 'SME_READ', 'Can not access file "%1"' },
{ 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' },
{ 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' },
{ 'SME_BADREF', 'Malformed reference in "%1"' },
{ 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' },
{ 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' },
{ 'SME_ERRVAL', 'External validator "%1" failed: %2' },
{ 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' },
{ 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' },
{ 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' },
{ 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' },
{ 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' },
{ 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' },
{ 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' },
{ 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' },
{ 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' },
{ 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' },
{ 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' },
{ 'OPT_REQUIRED', 'Required option "%i" has no value' },
{ 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' },
{ 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' },
{ 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' },
{ 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' },
{ 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' },
{ 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' },
{ 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' },
{ 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' },
{ 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' },
{ 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' },
{ 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' }
}
-- build error constants and instance constructors
for i, v in ipairs(ERRCODES) do
_M[v[1]] = function(...)
return error(i, ...)
end
_M['ERR_'..v[1]] = i
end
function i18n(key)
if luci.i18n then
return luci.i18n.translate(key)
else
return key
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(ERRCODES[self.code][2])
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
libs/uvl: fix i18n handling for errors
|
libs/uvl: fix i18n handling for errors
|
Lua
|
apache-2.0
|
8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
|
ef25d483c8776d115089f9bb84ed5f7a2b8c0630
|
test_scripts/Polices/build_options/037_ATF_P_TC_PTU_Changes_Applied_OnPermissionChange_Notification_App_HTTP.lua
|
test_scripts/Polices/build_options/037_ATF_P_TC_PTU_Changes_Applied_OnPermissionChange_Notification_App_HTTP.lua
|
-- Requirement summary:
-- [PolicyTableUpdate] Apply PTU changes and OnPermissionChange notifying the apps
--
-- Description:
-- Right after the PoliciesManager merges the UpdatedPT with Local PT, it must apply the changes
-- and send onPermissionChange() notification to any registered mobile app in case the Updated PT
-- affected to this app`s policies.
-- app via OnSystemRequest() RPC.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- policyfile' corresponds to PTU validation rules
-- 2. Performed steps
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
--
-- Expected:
-- SDL->HMI:OnStatusUpdate("UP_TO_DATE")
-- SDL->app: onPermissionChange(permisssions)
-- SDL->HMI: SDL.OnAppPermissionChanged(app, permissions)
---------------------------------------------------------------------------------------------
--[[ 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 json = require('json')
--[[ Local Variables ]]
local HMIAppID
local basic_ptu_file = "files/ptu.json"
local ptu_app_registered = "files/ptu_app.json"
-- Prepare parameters for app to save it in json file
local function PrepareJsonPTU1(name, new_ptufile)
local json_app = [[ {
"keep_context": false,
"steal_focus": false,
"priority": "NONE",
"default_hmi": "NONE",
"groups": [
"Base-4", "Emergency-1"
],
"RequestType":[
"TRAFFIC_MESSAGE_CHANNEL",
"PROPRIETARY",
"HTTP",
"QUERY_APPS"
]
}]]
local app = json.decode(json_app)
testCasesForPolicyTable:AddApplicationToPTJsonFile(basic_ptu_file, new_ptufile, name, app)
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--ToDo: should 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')
local mobile_session = require('mobile_session')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_StartSDL()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_initHMI()
self:initHMI()
end
function Test:Precondition_initHMI_onReady()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
end
function Test.Precondition_PreparePTData()
PrepareJsonPTU1(config.application1.registerAppInterfaceParams.appID, ptu_app_registered)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_RegisterApp()
self.mobileSession:StartService(7)
:Do(function (_,_)
local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
HMIAppID = data.params.application.appID
end)
EXPECT_RESPONSE(correlationId, { success = true })
EXPECT_NOTIFICATION("OnPermissionsChange")
end)
end
function Test:TestStep_ActivateAppInFull()
commonSteps:ActivateAppInSpecificLevel(self,HMIAppID,"FULL")
end
function Test:TestStep_UpdatePolicy_ExpectOnAppPermissionChangedWithAppID()
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_app_registered,
config.application1.registerAppInterfaceParams.appName,
self.mobileSession)
EXPECT_NOTIFICATION("OnPermissionsChange")
:ValidIf(function (_, data)
if data.payload~=nil then
return true
else
print("OnPermissionsChange came without permissions")
return false
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_RemovePTUfiles()
os.remove(ptu_app_registered)
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
-- Requirement summary:
-- [PolicyTableUpdate] Apply PTU changes and OnPermissionChange notifying the apps
--
-- Description:
-- Right after the PoliciesManager merges the UpdatedPT with Local PT, it must apply the changes
-- and send onPermissionChange() notification to any registered mobile app in case the Updated PT
-- affected to this app`s policies.
-- app via OnSystemRequest() RPC.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
-- policyfile' corresponds to PTU validation rules
-- 2. Performed steps
-- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile)
--
-- Expected:
-- SDL->HMI:OnStatusUpdate("UP_TO_DATE")
-- SDL->app: onPermissionChange(permisssions)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local json = require("modules/json")
--[[ Local Variables ]]
local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local policy_file_name = "PolicyTableUpdate"
local f_name = os.tmpname()
local ptu
local sequence = { }
--[[ Local Functions ]]
local function timestamp()
local f = io.popen("date +%H:%M:%S.%3N")
local o = f:read("*all")
f:close()
return (o:gsub("\n", ""))
end
local function log(event, ...)
table.insert(sequence, { ts = timestamp(), e = event, p = {...} })
end
local function show_log()
print("--- Sequence -------------------------------------")
for k, v in pairs(sequence) do
local s = k .. ": " .. v.ts .. ": " .. v.e
for _, val in pairs(v.p) do
if val then s = s .. ": " .. val end
end
print(s)
end
print("--------------------------------------------------")
end
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 ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--ToDo: Should 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")
--[[ Specific Notifications ]]
function Test:RegisterNotification()
self.mobileSession:ExpectNotification("OnSystemRequest")
:Do(function(_, d)
log("SDL->MOB: OnSystemRequest")
ptu = json.decode(d.binaryData)
end)
:Times(AtLeast(1))
:Pin()
end
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate")
:Do(function(_, d)
log("SDL->HMI: SDL.OnStatusUpdate", d.params.status)
end)
:Times(AnyNumber())
:Pin()
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.DeletePTUFile()
if check_file_exists(policy_file_path .. "/" .. policy_file_name) then
os.remove(policy_file_path .. "/" .. policy_file_name)
print("Policy file is removed")
end
end
function Test:ValidatePTS()
if ptu.policy_table.consumer_friendly_messages.messages then
self:FailTestCase("Expected absence of 'consumer_friendly_messages.messages' section in PTS")
end
end
function Test.UpdatePTS()
ptu.policy_table.device_data = nil
ptu.policy_table.usage_and_error_counts = nil
ptu.policy_table.app_policies["0000001"] = { keep_context = false, steal_focus = false, priority = "NONE", default_hmi = "NONE" }
ptu.policy_table.app_policies["0000001"]["groups"] = { "Base-4", "Base-6" }
ptu.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null
end
function Test.StorePTSInFile()
local f = io.open(f_name, "w")
f:write(json.encode(ptu))
f:close()
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:PTU()
local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = policy_file_name }, f_name)
log("MOB->SDL: SystemRequest")
self.mobileSession:ExpectNotification("OnPermissionsChange")
:Do(function()
log("SDL->MOB: OnPermissionsChange")
end)
EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" })
:Do(function()
log("SUCCESS: SystemRequest")
end)
end
function Test.Test_ShowSequence()
show_log()
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Clean()
os.remove(f_name)
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
1fac478b4f8617fcce3de9501c1397df01affddd
|
tundra.lua
|
tundra.lua
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-Wno-switch-enum",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-unknown-warning-option",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-reserved-id-macro",
"-Wno-missing-prototypes",
"-Wno-deprecated-declarations",
"-Wno-cast-qual",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = {
{ "Cocoa" },
{ "Metal" },
{ "QuartzCore" },
{ "OpenGL" }
},
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = {
{ "Cocoa" },
{ "Metal" },
{ "QuartzCore" },
{ "OpenGL" }
},
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
-- "units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx", "rust" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx", "rust" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc", "rust", "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc", "rust" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
Variants = { "debug", "release" },
SubVariants = { "default", "test" },
}
-- vim: ts=4:sw=4:sts=4
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-Wno-switch-enum",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-unknown-warning-option",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-reserved-id-macro",
"-Wno-missing-prototypes",
"-Wno-deprecated-declarations",
"-Wno-cast-qual",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wno-microsoft-enum-value", -- enumerator value is not representable in the underlying type 'int'
"-Wno-microsoft-const-init", -- default initialization of an object of const type '' without a user-provided default constructor is a Microsoft extension
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = {
{ "Cocoa" },
{ "Metal" },
{ "QuartzCore" },
{ "OpenGL" }
},
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = {
{ "Cocoa" },
{ "Metal" },
{ "QuartzCore" },
{ "OpenGL" }
},
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
RUST_CARGO_OPTS = {
{ "test"; Config = "*-*-*-test" },
},
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
-- "units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx", "rust" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx", "rust" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc", "rust", "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc", "rust" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
Variants = { "debug", "release" },
SubVariants = { "default", "test" },
}
-- vim: ts=4:sw=4:sts=4
|
Fix compile issues due to clang support for msvc compilation
|
Fix compile issues due to clang support for msvc compilation
|
Lua
|
mit
|
v3n/ProDBG,v3n/ProDBG,v3n/ProDBG,v3n/ProDBG,v3n/ProDBG,v3n/ProDBG
|
67da133916d51cecbebd7b46b2947fc8ea1a71f2
|
loader/DataLoader.lua
|
loader/DataLoader.lua
|
require 'paths'
require 'image'
require 'hdf5'
local DataLoader = torch.class('DataLoader')
require 'loader.utils'
function DataLoader:__init(dataTrain, dataVal, opts)
self.batchSize = opts.batchSize
self.mismatchFreq = opts.mismatchFreq -- percent of time a misaligned image should be presented
self.dataTrain = dataTrain
self.dataVal = dataVal
--self.eor = soreor[2]:view(1, -1)
groupByLen(dataTrain)
groupByLen(dataVal)
self.imfeatDim = opts.imfeatDim
self.stDim = opts.stDim
self.maxIngrs = opts.maxIngrs
self.semantic = opts.semantic
self.dataset = opts.dataset
self.net = opts.net
self.imstore = opts.imstore
self.meanstd = {
mean = { 0.485, 0.456, 0.406 },
std = { 0.229, 0.224, 0.225 },
}
self.vgg_mean = torch.FloatTensor{123.68, 116.779, 103.939}
self.imsize = opts.imsize
torch.manualSeed(opts.seed)
collectgarbage()
end
function DataLoader:makebatch(partition)
collectgarbage()
partData = partition == 'val' and self.dataVal or self.dataTrain
local seqlen = partData.lengths[torch.multinomial(partData.lenFreqs, 1)[1]]
local seqlenInds = partData.indsByLen[seqlen]
local batchSize = math.min(#seqlenInds, self.batchSize)
imagefile = hdf5.open(self.dataset, 'r'):read('/ims_'..partData.partition)
local selIndInds = torch.randperm(#seqlenInds) -- indices of indices in the batch
local batchIds = torch.CharTensor(batchSize, 11)
local batchImgs
batchImgs = torch.Tensor(batchSize,3,self.imsize,self.imsize)
local batchInstrs = torch.Tensor(seqlen, batchSize, self.stDim)
local batchIngrs = torch.LongTensor(batchSize, self.maxIngrs)
local batchMatches = torch.CharTensor(batchSize) -- whether image belongs to instrs
local batchClsRecipe = torch.LongTensor(batchSize)
local batchClsImg = torch.LongTensor(batchSize)
--batchInstrs[-1]:copy(self.eor:expand(batchSize, self.stDim))
local batchMaxIngrs = 0
for i=1,batchSize do
local selInd = seqlenInds[selIndInds[i]]
batchIds[i]:sub(1, 10):copy(partData.ids[selInd])
if self.semantic then
batchClsRecipe[i] = partData.classes[selInd]
batchClsImg[i] = partData.classes[selInd]
end
local match = math.random() > self.mismatchFreq
batchMatches[i] = match and 1 or -1
local position
if match then
position = selInd
else
local mismatch = selInd
while mismatch == selInd do
mismatch = torch.random(partData.ids:size(1))
end
position = mismatch
end
local mean_pixel = self.vgg_mean:view(1,3,1,1)
-- READING FROM JPG FILE
--name = torch.serialize(partData.images[mismatch]:clone(),'ascii')
--local img = loadImage(name:sub(74,148),self.imstore)
-- Select random image from list of images for that sample
local numims = partData.numims[position]
local imid = torch.randperm(numims)[1]
local impos = partData.impos[position][imid]
local img = imagefile:partial({impos,impos},{1,3},{1,self.imstore},{1,self.imstore}):float()
img = improc(self.imsize,img)
img = img:view(1, img:size(1), img:size(2), img:size(3)) -- batch the image
if self.net == 'resnet' then
img:div(256)
img = ImageNormalize(img,self.meanstd)
else
img:add(-1, mean_pixel:expandAs(img))
end
batchImgs[i] = img
if self.semantic then
batchClsImg[i] = partData.classes[position] -- replace class with mismatched class
end
local rbp = partData.rbps[selInd]
local rlen = partData.rlens[selInd]
local svecs = partData.stvecs:narrow(1, rbp, rlen)
batchInstrs[{{1, seqlen}, i}] = svecs
batchIngrs[i] = partData.ingrs[selInd]
end
imagefile:close()
if self.semantic then
return {batchImgs, batchInstrs, batchIngrs}, {batchMatches,batchClsImg,batchClsRecipe}, batchIds
else
return {batchImgs, batchInstrs, batchIngrs}, batchMatches, batchIds
end
end
function DataLoader:partitionSize(partition)
local ds = partition == 'train' and self.dataTrain or self.dataVal
return ds.rlens:size(1)
end
function DataLoader:terminate() end
|
require 'paths'
require 'image'
require 'hdf5'
local DataLoader = torch.class('DataLoader')
require 'loader.utils'
function DataLoader:__init(dataTrain, dataVal, opts)
self.batchSize = opts.batchSize
self.mismatchFreq = opts.mismatchFreq -- percent of time a misaligned image should be presented
self.dataTrain = dataTrain
self.dataVal = dataVal
--self.eor = soreor[2]:view(1, -1)
groupByLen(dataTrain)
groupByLen(dataVal)
self.imfeatDim = opts.imfeatDim
self.stDim = opts.stDim
self.maxIngrs = opts.maxIngrs
self.semantic = opts.semantic
self.dataset = opts.dataset
self.net = opts.net
self.imstore = opts.imstore
self.meanstd = {
mean = { 0.485, 0.456, 0.406 },
std = { 0.229, 0.224, 0.225 },
}
self.vgg_mean = torch.FloatTensor{123.68, 116.779, 103.939}
self.imsize = opts.imsize
torch.manualSeed(opts.seed)
self.dsH5 = hdf5.open(self.dataset, 'r')
collectgarbage()
end
function DataLoader:makebatch(partition)
collectgarbage()
partData = partition == 'val' and self.dataVal or self.dataTrain
local seqlen = partData.lengths[torch.multinomial(partData.lenFreqs, 1)[1]]
local seqlenInds = partData.indsByLen[seqlen]
local batchSize = math.min(#seqlenInds, self.batchSize)
local imagefile = self.dsH5:read('/ims_'..partData.partition)
local selIndInds = torch.randperm(#seqlenInds) -- indices of indices in the batch
local batchIds = torch.CharTensor(batchSize, 11)
local batchImgs
batchImgs = torch.Tensor(batchSize,3,self.imsize,self.imsize)
local batchInstrs = torch.Tensor(seqlen, batchSize, self.stDim)
local batchIngrs = torch.LongTensor(batchSize, self.maxIngrs)
local batchMatches = torch.CharTensor(batchSize) -- whether image belongs to instrs
local batchClsRecipe = torch.LongTensor(batchSize)
local batchClsImg = torch.LongTensor(batchSize)
--batchInstrs[-1]:copy(self.eor:expand(batchSize, self.stDim))
local batchMaxIngrs = 0
for i=1,batchSize do
local selInd = seqlenInds[selIndInds[i]]
batchIds[i]:sub(1, 10):copy(partData.ids[selInd])
if self.semantic then
batchClsRecipe[i] = partData.classes[selInd]
batchClsImg[i] = partData.classes[selInd]
end
local match = math.random() > self.mismatchFreq
batchMatches[i] = match and 1 or -1
local position
if match then
position = selInd
else
local mismatch = selInd
while mismatch == selInd do
mismatch = torch.random(partData.ids:size(1))
end
position = mismatch
end
local mean_pixel = self.vgg_mean:view(1,3,1,1)
-- READING FROM JPG FILE
--name = torch.serialize(partData.images[mismatch]:clone(),'ascii')
--local img = loadImage(name:sub(74,148),self.imstore)
-- Select random image from list of images for that sample
local numims = partData.numims[position]
local imid = torch.randperm(numims)[1]
local impos = partData.impos[position][imid]
local img = imagefile:partial({impos,impos},{1,3},{1,self.imstore},{1,self.imstore}):float()
img = improc(self.imsize,img)
img = img:view(1, img:size(1), img:size(2), img:size(3)) -- batch the image
if self.net == 'resnet' then
img:div(256)
img = ImageNormalize(img,self.meanstd)
else
img:add(-1, mean_pixel:expandAs(img))
end
batchImgs[i] = img
if self.semantic then
batchClsImg[i] = partData.classes[position] -- replace class with mismatched class
end
local rbp = partData.rbps[selInd]
local rlen = partData.rlens[selInd]
local svecs = partData.stvecs:narrow(1, rbp, rlen)
batchInstrs[{{1, seqlen}, i}] = svecs
batchIngrs[i] = partData.ingrs[selInd]
end
if self.semantic then
return {batchImgs, batchInstrs, batchIngrs}, {batchMatches,batchClsImg,batchClsRecipe}, batchIds
else
return {batchImgs, batchInstrs, batchIngrs}, batchMatches, batchIds
end
end
function DataLoader:partitionSize(partition)
local ds = partition == 'train' and self.dataTrain or self.dataVal
return ds.rlens:size(1)
end
function DataLoader:terminate()
self.dsH5:close()
end
|
Fix HDF5 error
|
Fix HDF5 error
An issue was reported describing a possible malfunction of HDF5: https://github.com/torralba-lab/im2recipe/issues/5
This malfunction could be caused by the fact that each data loading threads open the hdf5 data file `data/data.h5` and close it each time `DataLoader:makebatch` is called.
Notice that for a small amount of threads (~=4), this error may not happen.
Moving the `hdf5.open` call to the `DataLoader:__init` (called only once) seems to fix the problem.
@MicaelCarvalho @Cadene
|
Lua
|
mit
|
torralba-lab/im2recipe
|
05c6f1d6e1dda227bd999a04d171ccdfe1e6a7df
|
modules/rroulette.lua
|
modules/rroulette.lua
|
local rr = ivar2.persist
if(not ivar2.timers) then ivar2.timers = {} end
local getBullet = function(n)
return n % 10
end
local getChamber = function(n)
return (n - getBullet(n)) / 10 % 10
end
return {
PRIVMSG = {
['^%prr$'] = function(self, source, destination)
local nick = source.nick
if(not rr['rr:'..destination]) then
rr['rr:'..destination] = 60 + math.random(1,6)
end
local bullet = getBullet(rr['rr:'..destination])
local chamber = getChamber(rr['rr:'..destination])
local deathKey = destination .. ':' .. nick .. ':deaths'
local attemptKey = destination .. ':' .. nick .. ':attempts'
local deaths = rr['rr:'..deathKey] or 0
local attempts = (rr['rr:'..attemptKey] or 0) + 1
local seed = math.random(1, chamber)
if(seed == bullet) then
bullet = math.random(1, 6)
chamber = 6
deaths = deaths + 1
self:Kick(destination, nick, 'BANG!')
say('BANG! %s died a gruesome death.', source.nick)
else
chamber = chamber - 1
if(bullet > chamber) then
bullet = chamber
end
local src = 'Russian Roulette:' .. destination
local timer = self:Timer(src, 15*60, function(loop, timer, revents)
local n = rr['rr:'..destination]
rr['rr:'..destination] = 60 + math.random(1,6)
end)
say('Click. %d/6', chamber)
end
rr['rr:'..destination] = (chamber * 10) + bullet
rr['rr:'..deathKey] = deaths
rr['rr:'..attemptKey] = attempts
end,
['^%prrstat$'] = function(self, source, destination)
local nicks = {}
for n,t in pairs(self.channels[destination].nicks) do
nicks[n] = destination..':'..n
end
local tmp = {}
for nick, key in next, nicks do
if(not tmp[nick]) then tmp[nick] = {} end
type = 'attempts'
res = tonumber(rr['rr:'..key..':'..type])
if not res then res = 0 end
tmp[nick][type] = res
type = 'deaths'
res = tonumber(rr['rr:'..key..':'..type])
if not res then res = 0 end
tmp[nick][type] = res
end
local stats = {}
for nick, data in next, tmp do
if data.deaths > 0 or data.attempts > 0 then
local deathRatio = data.deaths / data.attempts
table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio})
end
end
table.sort(stats, function(a,b) return a.ratio < b.ratio end)
local out = {}
for i=1, #stats do
table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100))
end
say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', ')))
end,
}
}
|
local rr = ivar2.persist
local getBullet = function(n)
return n % 10
end
local getChamber = function(n)
return (n - getBullet(n)) / 10 % 10
end
return {
PRIVMSG = {
['^%prr$'] = function(self, source, destination)
local nick = source.nick
if(not rr['rr:'..destination]) then
rr['rr:'..destination] = 60 + math.random(1,6)
end
local bullet = getBullet(rr['rr:'..destination])
local chamber = getChamber(rr['rr:'..destination])
local deathKey = destination .. ':' .. nick .. ':deaths'
local attemptKey = destination .. ':' .. nick .. ':attempts'
local deaths = rr['rr:'..deathKey] or 0
local attempts = (rr['rr:'..attemptKey] or 0) + 1
local seed = math.random(1, chamber)
if(seed == bullet) then
bullet = math.random(1, 6)
chamber = 6
deaths = deaths + 1
self:Kick(destination, nick, 'BANG!')
say('BANG! %s died a gruesome death.', source.nick)
else
chamber = chamber - 1
if(bullet > chamber) then
bullet = chamber
end
local src = 'Russian Roulette:' .. destination
local timer = self:Timer(src, 15*60, function(loop, timer, revents)
local n = rr['rr:'..destination]
rr['rr:'..destination] = 60 + math.random(1,6)
end)
say('Click. %d/6', chamber)
end
rr['rr:'..destination] = (chamber * 10) + bullet
rr['rr:'..deathKey] = deaths
rr['rr:'..attemptKey] = attempts
end,
['^%prrstat$'] = function(self, source, destination)
local nicks = {}
for n,t in pairs(self.channels[destination].nicks) do
nicks[n] = destination..':'..n
end
local tmp = {}
for nick, key in next, nicks do
if(not tmp[nick]) then tmp[nick] = {} end
local rtype = 'attempts'
local res = tonumber(rr['rr:'..key..':'..rtype])
if not res then res = 0 end
tmp[nick][rtype] = res
rtype = 'deaths'
res = tonumber(rr['rr:'..key..':'..rtype])
if not res then res = 0 end
tmp[nick][rtype] = res
end
local stats = {}
for nick, data in next, tmp do
if data.deaths > 0 or data.attempts > 0 then
local deathRatio = data.deaths / data.attempts
table.insert(stats, {nick = nick, deaths = data.deaths, attempts = data.attempts, ratio = deathRatio})
end
end
table.sort(stats, function(a,b) return a.ratio < b.ratio end)
local out = {}
for i=1, #stats do
table.insert(out, string.format('%s (%.1f%%)', stats[i].nick, (1 - stats[i].ratio) * 100))
end
say('Survival rate: %s', ivar2.util.nonickalert(self.channels[destination].nicks, table.concat(out, ', ')))
end,
}
}
|
rroulette: fix variables usage
|
rroulette: fix variables usage
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
db6569b284990840925ebe0e2e42f460f4776bf1
|
src/achievements.lua
|
src/achievements.lua
|
local AchievementTracker = {}
AchievementTracker.__index = AchievementTracker
trophies = {
'adorable' = {
'headline' = "Aww, we're adorable",
'description' = "Start a new game",
'icon' = nil
},
"oh cool I'm alive" = {
'headline' = "Oh cool, I'm alive!",
'description' = "Die once",
'icon' = nil
},
}
---
-- Create a new tracker for achievements.
-- @return tracker
function AchievementTracker.new()
local tracker = {}
setmetatable(tracker, AchievementTracker)
tracker.counters = {}
return tracker
end
---
-- Return current count for a tracked label.
-- @param label
-- @return count
function AchievementTracker:getCount(label)
if self.counters[label] == nil then
self:setCount(label, 0)
return 0
end
return self.counters[label]
end
---
-- Set current count for a tracked label.
-- @param label
-- @param count
-- @return nil
function AchievementTracker:setCount(label, count)
self.counters[label] = count
end
---
-- Return a list of tracked labels.
-- @return labels
function AchievementTracker:getTrackedLabels()
local labels = {}
for l, _ in ipairs(tracker.counters) do table.insert(labels, l) end
return labels
end
---
-- Accomplish some tracked task, with optional delta
-- @param label
-- @param delta (optional)
-- @return nil
function AchievementTracker:achieve(label, delta)
delta = delta or 1
self:setCount(label, self:getCount(label) + delta)
self:onAchieve(label)
end
---
-- Code to display achievements as they happen.
-- @param label
-- @return nil
function AchievementTracker:display(label)
local info = trophies[label]
print(info.headline .. '\n\n\t' .. info.description)
end
---
-- Messy logic for individual achievements
-- @param label
-- @return nil
function AchievementTracker:onAchieve(label)
count = self:getCount(label)
if label == 'start game' then
if count == 1 then
return self:achieve('adorable')
end
elseif label == 'die' then
if count == 1 then
return self:achieve("oh cool I'm alive")
end
end
end
return AchievementTracker
|
local AchievementTracker = {}
AchievementTracker.__index = AchievementTracker
trophies = {
["adorable"]={
["headline"]="Aww, we're adorable",
["description"]="Start a new game",
["icon"]=nil
},
["oh cool I'm alive"]={
["headline"]="Oh cool, I'm alive!",
["description"]="Die once",
["icon"]=nil
}
}
counters = {}
---
-- Create a new tracker for achievements.
-- @return tracker
function AchievementTracker.new()
local tracker = {}
setmetatable(tracker, AchievementTracker)
return tracker
end
---
-- Return current count for a tracked label.
-- @param label
-- @return count
function AchievementTracker:getCount(label)
if counters[label] == nil then
self:setCount(label, 0)
return 0
end
return counters[label]
end
---
-- Set current count for a tracked label.
-- @param label
-- @param count
-- @return nil
function AchievementTracker:setCount(label, count)
counters[label] = count
end
---
-- Return a list of tracked labels.
-- @return labels
function AchievementTracker:getTrackedLabels()
local labels = {}
for l, _ in ipairs(tracker.counters) do table.insert(labels, l) end
return labels
end
---
-- Accomplish some tracked task, with optional delta
-- @param label
-- @param delta (optional)
-- @return nil
function AchievementTracker:achieve(label, delta)
delta = delta or 1
self:setCount(label, self:getCount(label) + delta)
self:display(label)
self:onAchieve(label)
end
---
-- Code to display achievements as they happen.
-- @param label
-- @return nil
function AchievementTracker:display(label)
local info = trophies[label]
if info == nil then return end
print(info.headline .. '\n\n\t' .. info.description)
end
---
-- Messy logic for individual achievements
-- @param label
-- @return nil
function AchievementTracker:onAchieve(label)
count = self:getCount(label)
if label == 'start game' then
if count == 1 then
return self:achieve('adorable')
end
elseif label == 'die' then
if count == 1 then
return self:achieve("oh cool I'm alive")
end
end
end
return AchievementTracker
|
#221 Some fixes for achievements.lua
|
#221 Some fixes for achievements.lua
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
|
375ab8436c368951d10c7d6e193efb14606a1421
|
lua/framework/mouse.lua
|
lua/framework/mouse.lua
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
local framework = framework
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
SDL.SDL_SetCursor( cursor )
if ( cursor ) then
else
SDL.SDL_SetCursor( SDL.SDL_GetDefaultCursor() )
end
end
function setPosition( x, y )
SDL.SDL_WarpMouseInWindow( framework.window._window, x, y )
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and 1 or 0 )
end
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
local framework = framework
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
if ( cursor ) then
SDL.SDL_SetCursor( cursor )
else
SDL.SDL_SetCursor( SDL.SDL_GetDefaultCursor() )
end
end
function setPosition( x, y )
SDL.SDL_WarpMouseInWindow( framework.window._window, x, y )
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and 1 or 0 )
end
|
Fix typo
|
Fix typo
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
a01ffdb144743222e643926021db19b5c16bdb27
|
premake5.lua
|
premake5.lua
|
local sep = "/"
local ext = ""
local copyFix = ""
if os.ishost("windows") then
sep = "\\"
ext = ".exe"
copyFix = "*"
end
cwd = os.getcwd()
-- Workspace definition.
workspace("Rendu")
-- Configurations
configurations({ "Debug", "Release"})
location("build")
targetdir ("build/%{prj.name}/%{cfg.longname}")
debugdir ("build/%{prj.name}/%{cfg.longname}")
architecture("x64")
-- Configuration specific settings.
filter("configurations:Debug")
defines({ "DEBUG" })
symbols("On")
filter("configurations:Release")
defines({ "NDEBUG" })
optimize("On")
filter({})
-- Helper functions for the projects.
function InstallProject(projectName, destination)
filter("configurations:Debug")
postbuildcommands({
path.translate( "{CHDIR} "..os.getcwd(), sep),
path.translate( "{COPY} build/"..projectName.."/Debug/"..projectName..ext.." "..destination..copyFix, sep)
})
filter("configurations:Release")
postbuildcommands({
path.translate( "{CHDIR} "..os.getcwd(), sep),
path.translate( "{COPY} build/"..projectName.."/Release/"..projectName..ext.." "..destination..copyFix, sep)
})
filter({})
end
function CPPSetup()
language("C++")
cppdialect("C++11")
buildoptions({ "-Wall" })
end
function GraphicsSetup(srcDir)
CPPSetup()
libDir = srcDir.."/libs/"
-- To support angled brackets in Xcode.
sysincludedirs({ libDir, libDir.."glfw/include/" })
-- Libraries for each platform.
if os.istarget("macosx") then
libdirs({libDir.."glfw/lib-mac/", libDir.."nfd/lib-mac/"})
links({"glfw3", "nfd", "OpenGL.framework", "Cocoa.framework", "IOKit.framework", "CoreVideo.framework", "AppKit.framework"})
elseif os.istarget("windows") then
libdirs({libDir.."glfw/lib-win-x64/", libDir.."nfd/lib-win-x64/"})
links({"glfw3", "nfd", "opengl32", "comctl32"})
else -- Assume linux
-- Libraries needed: OpenGL and glfw3. glfw3 require X11, Xi, and so on...
libdirs({ os.findlib("glfw3"), os.findlib("nfd") })
links({"glfw3", "nfd", "GL", "X11", "Xi", "Xrandr", "Xxf86vm", "Xinerama", "Xcursor", "rt", "m", "pthread", "dl", "gtk+-3.0"})
end
end
function ShaderValidation()
-- Run the shader validator on all existing shaders.
-- Output IDE compatible error messages.
dependson({"ShaderValidator"})
prebuildcommands({
-- Move to the build directory.
path.translate("{CHDIR} "..os.getcwd().."/build", sep),
-- Run the shader validator on the resources directory.
path.translate( "./shader_validator"..ext.." "..cwd.."/resources/", sep)
})
end
function RegisterSourcesAndResources(srcPath, rscPath)
files({ srcPath, rscPath })
removefiles({"**.DS_STORE", "**.thumbs"})
-- Reorganize file hierarchy in the IDE project.
vpaths({
["*"] = {srcPath},
["Resources/*"] = {rscPath}
})
end
function AppSetup(appName)
GraphicsSetup("src")
includedirs({ "src/engine" })
links({"Engine"})
kind("ConsoleApp")
ShaderValidation()
-- Declare src and resources files.
srcPath = "src/apps/"..appName.."/**"
rscPath = "resources/"..appName.."/**"
RegisterSourcesAndResources(srcPath, rscPath)
end
function ToolSetup(toolName)
GraphicsSetup("src")
includedirs({ "src/engine" })
links({"Engine"})
kind("ConsoleApp")
--location("build/tools")
end
-- Projects
project("Engine")
GraphicsSetup("src")
includedirs({ "src/engine" })
kind("StaticLib")
files({ "src/engine/**.hpp", "src/engine/**.cpp",
"resources/common/**", "resources/common/**", "resources/common/**",
"src/libs/*/*.hpp", "src/libs/*/*.cpp", "src/libs/*/*.h",
"premake5.lua"
})
removefiles({"**.DS_STORE", "**.thumbs"})
-- Virtual path allow us to get rid of the on-disk hierarchy.
vpaths({
["engine/*"] = {"src/engine/**"},
["Resources/*"] = {"resources/common/**"},
["Libraries/*"] = {"src/libs/**"},
})
group("Apps")
project("PBRDemo")
AppSetup("pbrdemo")
project("Playground")
AppSetup("playground")
project("Atmosphere")
AppSetup("atmosphere")
project("ImageViewer")
AppSetup("imageviewer")
project("SnakeGame")
AppSetup("snakegame")
project("RaytracerDemo")
AppSetup("raytracerdemo")
project("ImageFiltering")
AppSetup("imagefiltering")
group("Tools")
project("AtmosphericScatteringEstimator")
ToolSetup()
files({ "src/tools/AtmosphericScatteringEstimator.cpp" })
project("BRDFEstimator")
ToolSetup()
includedirs({ "src/apps/pbrdemo" })
files({ "src/tools/BRDFEstimator.cpp" })
project("ControllerTest")
ToolSetup()
files({ "src/tools/controllertest/**.hpp", "src/tools/controllertest/**.cpp", })
project("ShaderValidator")
ToolSetup()
files({ "src/tools/ShaderValidator.cpp" })
-- Install the shader validation utility in the root build directory.
InstallProject("%{prj.name}", "build/shader_validator"..ext)
filter({})
group("Meta")
project("ALL")
CPPSetup()
kind("ConsoleApp")
dependson( {"Engine", "PBRDemo", "Playground", "Atmosphere", "ImageViewer", "AtmosphericScatteringEstimator", "BRDFEstimator", "ControllerTest", "SnakeGame", "RaytracerDemo"})
-- Actions
newaction {
trigger = "clean",
description = "Clean the build directory",
execute = function ()
print("Cleaning...")
os.rmdir("./build")
print("Done.")
end
}
newaction {
trigger = "docs",
description = "Build the documentation using Doxygen",
execute = function ()
print("Generating documentation...")
os.execute("doxygen"..ext.." docs/Doxyfile")
print("Done.")
end
}
-- Internal private projects can be added here.
if os.isfile("src/internal/premake5.lua") then
include("src/internal/premake5.lua")
end
|
local sep = "/"
local ext = ""
local copyFix = ""
if os.ishost("windows") then
sep = "\\"
ext = ".exe"
copyFix = "*"
end
cwd = os.getcwd()
-- Workspace definition.
workspace("Rendu")
-- Configurations
configurations({ "Release", "Dev"})
location("build")
targetdir ("build/%{prj.name}/%{cfg.longname}")
debugdir ("build/%{prj.name}/%{cfg.longname}")
architecture("x64")
-- Configuration specific settings.
filter("configurations:Release")
defines({ "NDEBUG" })
optimize("On")
filter("configurations:Dev")
defines({ "DEBUG" })
symbols("On")
filter({})
startproject("ALL")
-- Helper functions for the projects.
function InstallProject(projectName, destination)
filter("configurations:Release")
postbuildcommands({
path.translate( "{CHDIR} "..os.getcwd(), sep),
path.translate( "{COPY} build/"..projectName.."/Release/"..projectName..ext.." "..destination..copyFix, sep)
})
filter("configurations:Dev")
postbuildcommands({
path.translate( "{CHDIR} "..os.getcwd(), sep),
path.translate( "{COPY} build/"..projectName.."/Dev/"..projectName..ext.." "..destination..copyFix, sep)
})
filter({})
end
function CPPSetup()
language("C++")
cppdialect("C++11")
buildoptions({ "-Wall" })
systemversion("latest")
end
function GraphicsSetup(srcDir)
CPPSetup()
libDir = srcDir.."/libs/"
-- To support angled brackets in Xcode.
sysincludedirs({ libDir, libDir.."glfw/include/" })
-- Libraries for each platform.
if os.istarget("macosx") then
libdirs({libDir.."glfw/lib-mac/", libDir.."nfd/lib-mac/"})
links({"glfw3", "nfd", "OpenGL.framework", "Cocoa.framework", "IOKit.framework", "CoreVideo.framework", "AppKit.framework"})
elseif os.istarget("windows") then
libdirs({libDir.."glfw/lib-win-x64/", libDir.."nfd/lib-win-x64/"})
links({"glfw3", "nfd", "opengl32", "comctl32"})
else -- Assume linux
-- Libraries needed: OpenGL and glfw3. glfw3 require X11, Xi, and so on...
libdirs({ os.findlib("glfw3"), os.findlib("nfd") })
links({"glfw3", "nfd", "GL", "X11", "Xi", "Xrandr", "Xxf86vm", "Xinerama", "Xcursor", "rt", "m", "pthread", "dl", "gtk+-3.0"})
end
end
function ShaderValidation()
-- Run the shader validator on all existing shaders.
-- Output IDE compatible error messages.
dependson({"ShaderValidator"})
prebuildcommands({
-- Move to the build directory.
path.translate("{CHDIR} "..os.getcwd().."/build", sep),
-- Run the shader validator on the resources directory.
path.translate( "./shader_validator"..ext.." "..cwd.."/resources/", sep)
})
end
function RegisterSourcesAndResources(srcPath, rscPath)
files({ srcPath, rscPath })
removefiles({"**.DS_STORE", "**.thumbs"})
-- Reorganize file hierarchy in the IDE project.
vpaths({
["*"] = {srcPath},
["Resources/*"] = {rscPath}
})
end
function AppSetup(appName)
GraphicsSetup("src")
includedirs({ "src/engine" })
links({"Engine"})
kind("ConsoleApp")
ShaderValidation()
-- Declare src and resources files.
srcPath = "src/apps/"..appName.."/**"
rscPath = "resources/"..appName.."/**"
RegisterSourcesAndResources(srcPath, rscPath)
end
function ToolSetup(toolName)
GraphicsSetup("src")
includedirs({ "src/engine" })
links({"Engine"})
kind("ConsoleApp")
--location("build/tools")
end
-- Projects
project("Engine")
GraphicsSetup("src")
includedirs({ "src/engine" })
kind("StaticLib")
files({ "src/engine/**.hpp", "src/engine/**.cpp",
"resources/common/**", "resources/common/**", "resources/common/**",
"src/libs/*/*.hpp", "src/libs/*/*.cpp", "src/libs/*/*.h",
"premake5.lua"
})
removefiles({"**.DS_STORE", "**.thumbs"})
-- Virtual path allow us to get rid of the on-disk hierarchy.
vpaths({
["engine/*"] = {"src/engine/**"},
["Resources/*"] = {"resources/common/**"},
["Libraries/*"] = {"src/libs/**"},
})
group("Apps")
project("PBRDemo")
AppSetup("pbrdemo")
project("Playground")
AppSetup("playground")
project("Atmosphere")
AppSetup("atmosphere")
project("ImageViewer")
AppSetup("imageviewer")
project("SnakeGame")
AppSetup("snakegame")
project("RaytracerDemo")
AppSetup("raytracerdemo")
project("ImageFiltering")
AppSetup("imagefiltering")
group("Tools")
project("AtmosphericScatteringEstimator")
ToolSetup()
files({ "src/tools/AtmosphericScatteringEstimator.cpp" })
project("BRDFEstimator")
ToolSetup()
includedirs({ "src/apps/pbrdemo" })
files({ "src/tools/BRDFEstimator.cpp" })
project("ControllerTest")
ToolSetup()
files({ "src/tools/controllertest/**.hpp", "src/tools/controllertest/**.cpp", })
project("ShaderValidator")
ToolSetup()
files({ "src/tools/ShaderValidator.cpp" })
-- Install the shader validation utility in the root build directory.
InstallProject("%{prj.name}", "build/shader_validator"..ext)
filter({})
group("Meta")
project("ALL")
CPPSetup()
kind("ConsoleApp")
dependson( {"Engine", "PBRDemo", "Playground", "Atmosphere", "ImageViewer", "ImageFiltering", "AtmosphericScatteringEstimator", "BRDFEstimator", "ControllerTest", "SnakeGame", "RaytracerDemo"})
-- Actions
newaction {
trigger = "clean",
description = "Clean the build directory",
execute = function ()
print("Cleaning...")
os.rmdir("./build")
print("Done.")
end
}
newaction {
trigger = "docs",
description = "Build the documentation using Doxygen",
execute = function ()
print("Generating documentation...")
os.execute("doxygen"..ext.." docs/Doxyfile")
print("Done.")
end
}
-- Internal private projects can be added here.
if os.isfile("src/internal/premake5.lua") then
include("src/internal/premake5.lua")
end
|
Premake: fix for default project, configuration and SDK.
|
Premake: fix for default project, configuration and SDK.
Former-commit-id: 4d5f5e030e08e2bea96c645d6025bdce456e3d51
|
Lua
|
mit
|
kosua20/GL_Template,kosua20/GL_Template
|
0f0901159b2e279bb30c4f565f675f2fcc557390
|
cabook.lua
|
cabook.lua
|
local book = SILE.require("classes/book")
local plain = SILE.require("classes/plain")
local cabook = book { id = "cabook" }
cabook:declareOption("crop", "true")
cabook:declareOption("background", "true")
cabook:declareOption("verseindex", "false")
cabook:loadPackage("verseindex", CASILE.casiledir)
cabook.endPage = function (self)
cabook:moveTocNodes()
if cabook.options.verseindex() == "true" then cabook:moveTovNodes() end
if not SILE.scratch.headers.skipthispage then
SILE.settings.pushState()
SILE.settings.reset()
if cabook:oddPage() then
SILE.call("output-right-running-head")
else
SILE.call("output-left-running-head")
end
SILE.settings.popState()
end
SILE.scratch.headers.skipthispage = false
return plain.endPage(cabook)
end
cabook.finish = function (self)
if cabook.options.verseindex() == "true" then cabook:writeTov() end
local ret = book:finish()
return ret
end
-- CaSILE books sometimes have sections, sometimes don't.
-- Initialize some sectioning levels to work either way
SILE.scratch.counters["sectioning"] = {
value = { 0, 0 },
display = { "ORDINAL", "STRING" }
}
-- I can't figure out how or where, but book.endPage() gets run on the last page
book.endPage = cabook.endPage
return cabook
|
local book = SILE.require("classes/book")
local plain = SILE.require("classes/plain")
local cabook = book { id = "cabook" }
cabook:declareOption("crop", "true")
cabook:declareOption("background", "true")
cabook:declareOption("verseindex", "false")
cabook:loadPackage("verseindex", CASILE.casiledir)
cabook.endPage = function (self)
cabook:moveTocNodes()
if cabook.options.verseindex() then cabook:moveTovNodes() end
if not SILE.scratch.headers.skipthispage then
SILE.settings.pushState()
SILE.settings.reset()
if cabook:oddPage() then
SILE.call("output-right-running-head")
else
SILE.call("output-left-running-head")
end
SILE.settings.popState()
end
SILE.scratch.headers.skipthispage = false
return plain.endPage(cabook)
end
cabook.finish = function (self)
if cabook.options.verseindex() then
cabook:writeTov()
SILE.call("tableofverses")
end
local ret = book:finish()
return ret
end
-- CaSILE books sometimes have sections, sometimes don't.
-- Initialize some sectioning levels to work either way
SILE.scratch.counters["sectioning"] = {
value = { 0, 0 },
display = { "ORDINAL", "STRING" }
}
-- I can't figure out how or where, but book.endPage() gets run on the last page
book.endPage = cabook.endPage
return cabook
|
Fix option handaling so TOV actually builds
|
Fix option handaling so TOV actually builds
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
dcb5f4d9ff26916f499d04c6d77da3a541150d2f
|
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
|
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
|
--- === cp.apple.finalcutpro.browser.Columns ===
---
--- Final Cut Pro Browser List View Columns
local require = require
--local log = require("hs.logger").new("Columns")
local ax = require("hs._asm.axuielement")
local geometry = require("hs.geometry")
local axutils = require("cp.ui.axutils")
local tools = require("cp.tools")
local Element = require("cp.ui.Element")
local Menu = require("cp.ui.Menu")
local systemElementAtPosition = ax.systemElementAtPosition
local childWithRole = axutils.childWithRole
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns")
--- cp.apple.finalcutpro.browser.Columns(parent) -> Columns
--- Constructor
--- Constructs a new Columns object.
---
--- Parameters:
--- * parent - The parent object
---
--- Returns:
--- * The new `Columns` instance.
function Columns:initialize(parent)
local UI = parent.UI:mutate(function(original)
return childWithRole(original(), "AXScrollArea")
end)
Element.initialize(self, parent, UI)
end
--- getVisibleHeightOfAXOutline(ui) -> number | nil
--- Constructor
--- Gets the visible height of an `AXOutline` object.
---
--- Parameters:
--- * ui - The `AXOutline` object to check.
---
--- Returns:
--- * The height of the visible area of the `AXOutline` or `nil` if something goes wrong.
local function getVisibleHeightOfAXOutline(ui)
if ui then
local visibleRows = ui:attributeValue("AXVisibleRows")
if visibleRows and #visibleRows >= 1 then
local firstRowUI = ui:attributeValue("AXChildren")[1]
local lastRowUI = ui:attributeValue("AXChildren")[#visibleRows]
if firstRowUI and lastRowUI then
local firstFrame = firstRowUI:attributeValue("AXFrame")
local lastFrame = lastRowUI:attributeValue("AXFrame")
local top = firstFrame and firstFrame.y
local bottom = lastFrame and lastFrame.y + lastFrame.h
if top and bottom then
return bottom - top
end
end
end
end
end
--- cp.apple.finalcutpro.browser.Columns:show() -> self
--- Method
--- Shows the Browser List View columns menu popup.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function Columns:show()
local ui = self:UI()
if ui then
local scrollAreaFrame = ui:attributeValue("AXFrame")
local outlineUI = childWithRole(ui, "AXOutline")
local visibleHeight = getVisibleHeightOfAXOutline(outlineUI)
local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame")
if scrollAreaFrame and outlineFrame and visibleHeight then
local headerHeight = (scrollAreaFrame.h - visibleHeight) / 2
local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight)
local element = point and systemElementAtPosition(point)
if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then
--cp.dev.highlightPoint(point)
tools.ninjaRightMouseClick(point)
end
end
end
return self
end
--- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean
--- Method
--- Is the Columns menu popup showing?
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if the columns menu popup is showing, otherwise `false`
function Columns:isMenuShowing()
return self:menu():isShowing()
end
--- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu
--- Method
--- Gets the Columns menu object.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `Menu` object.
function Columns.lazy.method:menu()
return Menu(self, self.UI:mutate(function(original)
return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu")
end))
end
return Columns
|
--- === cp.apple.finalcutpro.browser.Columns ===
---
--- Final Cut Pro Browser List View Columns
local require = require
--local log = require("hs.logger").new("Columns")
local ax = require("hs._asm.axuielement")
local geometry = require("hs.geometry")
local axutils = require("cp.ui.axutils")
local tools = require("cp.tools")
local Element = require("cp.ui.Element")
local Menu = require("cp.ui.Menu")
local systemElementAtPosition = ax.systemElementAtPosition
local childWithRole = axutils.childWithRole
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns")
--- cp.apple.finalcutpro.browser.Columns(parent) -> Columns
--- Constructor
--- Constructs a new Columns object.
---
--- Parameters:
--- * parent - The parent object
---
--- Returns:
--- * The new `Columns` instance.
function Columns:initialize(parent)
local UI = parent.UI:mutate(function(original)
return childWithRole(original(), "AXScrollArea")
end)
Element.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.browser.Columns:show() -> self
--- Method
--- Shows the Browser List View columns menu popup.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function Columns:show()
local ui = self:UI()
if ui then
local scrollAreaFrame = ui:attributeValue("AXFrame")
local outlineUI = childWithRole(ui, "AXOutline")
local scrollbarUI = childWithRole(ui, "AXScrollBar")
local scrollbarFrame = scrollbarUI and scrollbarUI:attributeValue("AXFrame")
local scrollbarHeight = scrollbarFrame and scrollbarFrame.h
local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame")
if scrollAreaFrame and outlineFrame and scrollbarHeight then
local headerHeight = (scrollAreaFrame.h - scrollbarHeight) / 2
local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight)
local element = point and systemElementAtPosition(point)
--cp.dev.highlightPoint(point)
if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then
tools.ninjaRightMouseClick(point)
end
end
end
return self
end
--- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean
--- Method
--- Is the Columns menu popup showing?
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if the columns menu popup is showing, otherwise `false`
function Columns:isMenuShowing()
return self:menu():isShowing()
end
--- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu
--- Method
--- Gets the Columns menu object.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `Menu` object.
function Columns.lazy.method:menu()
return Menu(self, self.UI:mutate(function(original)
return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu")
end))
end
return Columns
|
#1701
|
#1701
- Fixes a bug that still exists in
`cp.apple.finalcutpro.browser.Columns:show()`
- Closes #1701
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
5fe4ded673a2bc38f5019ce2a647863353355282
|
mods/food/food/init.lua
|
mods/food/food/init.lua
|
-- FOOD MOD
-- A mod written by rubenwardy that adds
-- food to the minetest game
-- =====================================
-- >> food/api.lua
-- The supporting api for the mod
-- =====================================
food = {
modules = {},
disabled_modules = {},
debug = false,
version = 2.3
}
-- Checks for external content, and adds support
function food.support(group, item)
if type(group) == "table" then
for i = 1, #group do
food.support(group[i], item)
end
return
end
if type(item) == "table" then
for i = 1, #item do
food.support(group, item[i])
end
return
end
local idx = string.find(item, ":")
if idx <= 1 then
error("[Food Error] food.support - error in item name ('" .. item .. "')")
end
local mod = string.sub(item, 1, idx - 1)
if not minetest.get_modpath(mod) then
if food.debug then
print("[Food Debug] Mod '"..mod.."' is not installed")
end
return
end
local data = minetest.registered_items[item]
if not data then
print("[Food Warning] Item '"..item.."' not found")
return
end
food.disable(group)
-- Add group
local g = {}
if data.groups then
for k, v in pairs(data.groups) do
g[k] = v
end
end
g["food_"..group] = 1
minetest.override_item(item, {groups = g})
end
function food.disable(name)
if type(name) == "table" then
for i = 1, #name do
food.disable(name[i])
end
return
end
food.disabled_modules[name] = true
end
function food.disable_if(mod, name)
if minetest.get_modpath(mod) then
food.disable(name)
end
end
-- Adds a module
function food.module(name, func, ingred)
if food.disabled_modules[name] then
return
end
if ingred then
for name, def in pairs(minetest.registered_items) do
local g = def.groups and def.groups["food_"..name] or 0
if g > 0 then
print("cancelled")
return
end
end
if food.debug then
print("[Food Debug] Registering " .. name .. " fallback definition")
end
elseif food.debug then
print("[Food Debug] Module " .. name)
end
func()
end
-- Checks for hunger mods to register food on
function food.item_eat(amt)
if minetest.get_modpath("diet") and diet and diet.item_eat then
return diet.item_eat(amt)
elseif minetest.get_modpath("hud") and hud and hud.item_eat then
return hud.item_eat(amt)
elseif minetest.get_modpath("hbhunger") then
if hbhunger then
return hbhunger.item_eat(amt)
else
return hbhunger.item_eat(amt)
end
else
return minetest.item_eat(amt)
end
end
-- Registers craft item or node depending on settings
function food.register(name, data, mod)
if (minetest.setting_getbool("food_use_2d") or (mod ~= nil and minetest.setting_getbool("food_"..mod.."_use_2d"))) then
minetest.register_craftitem(name,{
description = data.description,
inventory_image = data.inventory_image,
groups = data.groups,
on_use = data.on_use
})
else
local newdata = {
description = data.description,
tiles = data.tiles,
groups = data.groups,
on_use = data.on_use,
walkable = false,
sunlight_propagates = true,
drawtype = "nodebox",
paramtype = "light",
node_box = data.node_box
}
if (minetest.setting_getbool("food_2d_inv_image")) then
newdata.inventory_image = data.inventory_image
end
minetest.register_node(name,newdata)
end
end
-- Allows for overriding in the future
function food.craft(craft)
minetest.register_craft(craft)
end
|
-- FOOD MOD
-- A mod written by rubenwardy that adds
-- food to the minetest game
-- =====================================
-- >> food/api.lua
-- The supporting api for the mod
-- =====================================
food = {
modules = {},
disabled_modules = {},
debug = false,
version = 2.3
}
-- Checks for external content, and adds support
function food.support(group, item)
if type(group) == "table" then
for i = 1, #group do
food.support(group[i], item)
end
return
end
if type(item) == "table" then
for i = 1, #item do
food.support(group, item[i])
end
return
end
local idx = string.find(item, ":")
if idx <= 1 then
error("[Food Error] food.support - error in item name ('" .. item .. "')")
end
local mod = string.sub(item, 1, idx - 1)
if not minetest.get_modpath(mod) then
if food.debug then
print("[Food Debug] Mod '"..mod.."' is not installed")
end
return
end
local data = minetest.registered_items[item]
if not data then
print("[Food Warning] Item '"..item.."' not found")
return
end
food.disable(group)
-- Add group
local g = {}
if data.groups then
for k, v in pairs(data.groups) do
g[k] = v
end
end
g["food_"..group] = 1
minetest.override_item(item, {groups = g})
end
function food.disable(name)
if type(name) == "table" then
for i = 1, #name do
food.disable(name[i])
end
return
end
food.disabled_modules[name] = true
end
function food.disable_if(mod, name)
if minetest.get_modpath(mod) then
food.disable(name)
end
end
-- Adds a module
function food.module(name, func, ingred)
if food.disabled_modules[name] then
return
end
if ingred then
for name, def in pairs(minetest.registered_items) do
local g = def.groups and def.groups["food_"..name] or 0
if g > 0 then
print("cancelled")
return
end
end
if food.debug then
print("[Food Debug] Registering " .. name .. " fallback definition")
end
elseif food.debug then
print("[Food Debug] Module " .. name)
end
func()
end
-- Checks for hunger mods to register food on
function food.item_eat(amt)
if minetest.get_modpath("diet") and diet and diet.item_eat then
return diet.item_eat(amt)
elseif minetest.get_modpath("hud") and hud and hud.item_eat then
return hud.item_eat(amt)
elseif minetest.get_modpath("hbhunger") then
if hbhunger and hbhunger.item_eat then -- hbhunger is nil when world is loaded with damage disabled
return hbhunger.item_eat(amt)
end
return function(...) end
elseif minetest.get_modpath("hunger") and hunger and hunger.item_eat then
return hunger.item_eat(amt)
else
return minetest.item_eat(amt)
end
end
-- Registers craft item or node depending on settings
function food.register(name, data, mod)
if (minetest.setting_getbool("food_use_2d") or (mod ~= nil and minetest.setting_getbool("food_"..mod.."_use_2d"))) then
minetest.register_craftitem(name,{
description = data.description,
inventory_image = data.inventory_image,
groups = data.groups,
on_use = data.on_use
})
else
local newdata = {
description = data.description,
tiles = data.tiles,
groups = data.groups,
on_use = data.on_use,
walkable = false,
sunlight_propagates = true,
drawtype = "nodebox",
paramtype = "light",
node_box = data.node_box
}
if (minetest.setting_getbool("food_2d_inv_image")) then
newdata.inventory_image = data.inventory_image
end
minetest.register_node(name,newdata)
end
end
-- Allows for overriding in the future
function food.craft(craft)
minetest.register_craft(craft)
end
|
Fix [food] crashing when damage is disabled (hbhunger not loading)
|
Fix [food] crashing when damage is disabled (hbhunger not loading)
|
Lua
|
unlicense
|
LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
fbfc43fc63fb1b05ab453bec468a753c4b4481b2
|
mods/sprint/esprint.lua
|
mods/sprint/esprint.lua
|
--[[
Sprint mod for Minetest by GunshipPenguin
To the extent possible under law, the author(s)
have dedicated all copyright and related and neighboring rights
to this software to the public domain worldwide. This software is
distributed without any warranty.
]]
sprint.players = {}
local staminaHud = {}
-- Lil' helping functions
sprint.set_maxstamina = function(pname, mstamina)
if sprint.players[pname] and mstamina > 0 then
sprint.players[pname].maxStamina = mstamina
if sprint.players[pname].stamina > sprint.players[pname].maxStamina then
sprint.players[pname].stamina = sprint.players[pname].maxStamina
end
end
end
sprint.get_maxstamina = function(pname)
if sprint.players[pname] then
return sprint.players[pname].maxStamina
end
end
sprint.increase_maxstamina = function(pname, sincrease)
local stamina = sprint.get_maxstamina(pname)
if stamina then
sprint.set_maxstamina(pname, stamina + sincrease)
end
end
sprint.dicrease_maxstamina = function(pname, sdicrease)
local stamina = sprint.get_maxstamina(pname)
if stamina then
sprint.set_maxstamina(pname, stamina - sdicrease)
end
end
sprint.set_default_maxstamina = function(pname)
if sprint.players[pname] then
sprint.players[pname].maxStamina = SPRINT_STAMINA
if sprint.players[pname].stamina > sprint.players[pname].maxStamina then
sprint.players[pname].stamina = sprint.players[pname].maxStamina
end
end
end
minetest.register_on_joinplayer(function(player)
local playerName = player:get_player_name()
sprint.players[playerName] = {
sprinting = false,
timeOut = 0,
stamina = SPRINT_STAMINA,
shouldSprint = false,
maxStamina = SPRINT_STAMINA
}
if SPRINT_HUDBARS_USED then
hb.init_hudbar(player, "sprint")
else
sprint.players[playerName].hud = player:hud_add({
hud_elem_type = "statbar",
position = {x=0.5,y=1},
size = {x=24, y=24},
text = "stamina.png",
number = 20,
alignment = {x=0,y=1},
offset = {x=-320, y=-186},
}
)
end
end)
minetest.register_on_leaveplayer(function(player)
local playerName = player:get_player_name()
sprint.players[playerName] = nil
end)
local gameTime = 0
minetest.register_globalstep(function(dtime)
--Get the gametime
gameTime = gameTime + dtime
--Loop through all connected sprint.players
for playerName,playerInfo in pairs(sprint.players) do
local player = minetest.get_player_by_name(playerName)
if player ~= nil then
--Check if the player should be sprinting
if player:get_player_control()["aux1"] and player:get_player_control()["up"] then
sprint.players[playerName]["shouldSprint"] = true
else
sprint.players[playerName]["shouldSprint"] = false
end
--Stop sprinting if the player is pressing the LMB or RMB
if player:get_player_control()["LMB"] or player:get_player_control()["RMB"] then
setSprinting(playerName, false)
playerInfo["timeOut"] = 3
end
if gameTime > 0.4 then
local pos = player:getpos()
-- From playerplus :
-- am I near a cactus?
pos.y = pos.y + 0.1
if minetest.find_node_near(pos, 1, "default:cactus") and player:get_hp() > 0 then
player:set_hp(player:get_hp()-1)
end
--If the player is sprinting, create particles behind him/her
if playerInfo["sprinting"] == true then
local numParticles = math.random(1, 2)
local playerPos = player:getpos()
local playerNode = minetest.get_node({x=playerPos["x"], y=playerPos["y"]-1, z=playerPos["z"]})
if playerNode["name"] ~= "air" then
for i=1, numParticles, 1 do
minetest.add_particle({
pos = {x=playerPos["x"]+math.random(-1,1)*math.random()/2,y=playerPos["y"]+0.1,z=playerPos["z"]+math.random(-1,1)*math.random()/2},
vel = {x=0, y=5, z=0},
acc = {x=0, y=-13, z=0},
expirationtime = math.random(),
size = math.random()+0.5,
collisiondetection = true,
vertical = false,
texture = "sprint_particle.png",
})
end
end
end
end
--Adjust player states
if sprint.players[playerName]["shouldSprint"] == true and playerInfo["timeOut"] == 0 then --Stopped
setSprinting(playerName, true)
elseif sprint.players[playerName]["shouldSprint"] == false then
setSprinting(playerName, false)
end
if playerInfo["timeOut"] > 0 then
playerInfo["timeOut"] = playerInfo["timeOut"] - dtime
if playerInfo["timeOut"] < 0 then
playerInfo["timeOut"] = 0
end
else
--Lower the player's stamina by dtime if he/she is sprinting and set his/her state to 0 if stamina is zero
if playerInfo["sprinting"] == true then
playerInfo["stamina"] = playerInfo["stamina"] - dtime
if playerInfo["stamina"] <= 0 then
playerInfo["stamina"] = 0
setSprinting(playerName, false)
playerInfo["timeOut"] = 1
minetest.sound_play("default_breathless",{object=player})
end
end
end
--Increase player's stamina if he/she is not sprinting and his/her stamina is less than SPRINT_STAMINA
if playerInfo["sprinting"] == false and playerInfo["stamina"] < playerInfo["maxStamina"] then
playerInfo["stamina"] = playerInfo["stamina"] + dtime
end
-- Cap stamina at SPRINT_STAMINA
if playerInfo["stamina"] > playerInfo["maxStamina"] then
playerInfo["stamina"] = playerInfo["maxStamina"]
end
--Update the sprint.players's hud sprint stamina bar
if SPRINT_HUDBARS_USED then
hb.change_hudbar(player, "sprint", playerInfo["stamina"])
else
local numBars = (playerInfo["stamina"]/playerInfo["maxStamina"])*20
player:hud_change(playerInfo["hud"], "number", numBars)
end
end
end
if gameTime > 0.4 then
gameTime = 0
end
end)
function setSprinting(playerName, sprinting) --Sets the state of a player (0=stopped/moving, 1=sprinting)
local player = minetest.get_player_by_name(playerName)
if sprint.players[playerName] then
sprint.players[playerName]["sprinting"] = sprinting
if sprinting == true then
player:set_physics_override({speed=SPRINT_SPEED,jump=SPRINT_JUMP})
elseif sprinting == false then
player:set_physics_override({speed=1.0,jump=1.0})
end
return true
end
return false
end
|
--[[
Sprint mod for Minetest by GunshipPenguin
To the extent possible under law, the author(s)
have dedicated all copyright and related and neighboring rights
to this software to the public domain worldwide. This software is
distributed without any warranty.
]]
sprint.players = {}
local staminaHud = {}
-- Lil' helping functions
sprint.set_maxstamina = function(pname, mstamina)
if sprint.players[pname] and mstamina > 0 then
sprint.players[pname].maxStamina = mstamina
if sprint.players[pname].stamina > sprint.players[pname].maxStamina then
sprint.players[pname].stamina = sprint.players[pname].maxStamina
end
hb.change_hudbar(minetest.get_player_by_name(pname), "sprint", sprint.players[pname].stamina, sprint.players[pname].maxStamina)
end
end
sprint.get_maxstamina = function(pname)
if sprint.players[pname] then
return sprint.players[pname].maxStamina
end
end
sprint.increase_maxstamina = function(pname, sincrease)
local stamina = sprint.get_maxstamina(pname)
if stamina then
sprint.set_maxstamina(pname, stamina + sincrease)
end
end
sprint.decrease_maxstamina = function(pname, sdicrease)
local stamina = sprint.get_maxstamina(pname)
if stamina then
sprint.set_maxstamina(pname, stamina - sdicrease)
end
end
-- When you write shit english, don't write shit code.
-- Writing it in your native language would be less of a pain.
-- - gravgun
sprint.dicrease_maxstamina = sprint.decrease_maxstamina
sprint.set_default_maxstamina = function(pname)
sprint.set_maxstamina(pname, SPRINT_STAMINA)
end
minetest.register_on_joinplayer(function(player)
local playerName = player:get_player_name()
sprint.players[playerName] = {
sprinting = false,
timeOut = 0,
stamina = SPRINT_STAMINA,
shouldSprint = false,
maxStamina = SPRINT_STAMINA
}
if SPRINT_HUDBARS_USED then
hb.init_hudbar(player, "sprint")
else
sprint.players[playerName].hud = player:hud_add({
hud_elem_type = "statbar",
position = {x=0.5,y=1},
size = {x=24, y=24},
text = "stamina.png",
number = 20,
alignment = {x=0,y=1},
offset = {x=-320, y=-186},
}
)
end
end)
minetest.register_on_leaveplayer(function(player)
local playerName = player:get_player_name()
sprint.players[playerName] = nil
end)
local gameTime = 0
minetest.register_globalstep(function(dtime)
--Get the gametime
gameTime = gameTime + dtime
--Loop through all connected sprint.players
for playerName,playerInfo in pairs(sprint.players) do
local player = minetest.get_player_by_name(playerName)
if player ~= nil then
--Check if the player should be sprinting
if player:get_player_control()["aux1"] and player:get_player_control()["up"] then
sprint.players[playerName]["shouldSprint"] = true
else
sprint.players[playerName]["shouldSprint"] = false
end
--Stop sprinting if the player is pressing the LMB or RMB
if player:get_player_control()["LMB"] or player:get_player_control()["RMB"] then
setSprinting(playerName, false)
playerInfo["timeOut"] = 3
end
if gameTime > 0.4 then
local pos = player:getpos()
-- From playerplus :
-- am I near a cactus?
pos.y = pos.y + 0.1
if minetest.find_node_near(pos, 1, "default:cactus") and player:get_hp() > 0 then
player:set_hp(player:get_hp()-1)
end
--If the player is sprinting, create particles behind him/her
if playerInfo["sprinting"] == true then
local numParticles = math.random(1, 2)
local playerPos = player:getpos()
local playerNode = minetest.get_node({x=playerPos["x"], y=playerPos["y"]-1, z=playerPos["z"]})
if playerNode["name"] ~= "air" then
for i=1, numParticles, 1 do
minetest.add_particle({
pos = {x=playerPos["x"]+math.random(-1,1)*math.random()/2,y=playerPos["y"]+0.1,z=playerPos["z"]+math.random(-1,1)*math.random()/2},
vel = {x=0, y=5, z=0},
acc = {x=0, y=-13, z=0},
expirationtime = math.random(),
size = math.random()+0.5,
collisiondetection = true,
vertical = false,
texture = "sprint_particle.png",
})
end
end
end
end
--Adjust player states
if sprint.players[playerName]["shouldSprint"] == true and playerInfo["timeOut"] == 0 then --Stopped
setSprinting(playerName, true)
elseif sprint.players[playerName]["shouldSprint"] == false then
setSprinting(playerName, false)
end
if playerInfo["timeOut"] > 0 then
playerInfo["timeOut"] = playerInfo["timeOut"] - dtime
if playerInfo["timeOut"] < 0 then
playerInfo["timeOut"] = 0
end
else
--Lower the player's stamina by dtime if he/she is sprinting and set his/her state to 0 if stamina is zero
if playerInfo["sprinting"] == true then
playerInfo["stamina"] = playerInfo["stamina"] - dtime
if playerInfo["stamina"] <= 0 then
playerInfo["stamina"] = 0
setSprinting(playerName, false)
playerInfo["timeOut"] = 1
minetest.sound_play("default_breathless",{object=player})
end
end
end
--Increase player's stamina if he/she is not sprinting and his/her stamina is less than SPRINT_STAMINA
if playerInfo["sprinting"] == false and playerInfo["stamina"] < playerInfo["maxStamina"] then
playerInfo["stamina"] = playerInfo["stamina"] + dtime
end
-- Cap stamina at SPRINT_STAMINA
if playerInfo["stamina"] > playerInfo["maxStamina"] then
playerInfo["stamina"] = playerInfo["maxStamina"]
end
--Update the sprint.players's hud sprint stamina bar
if SPRINT_HUDBARS_USED then
hb.change_hudbar(player, "sprint", playerInfo["stamina"])
else
local numBars = (playerInfo["stamina"]/playerInfo["maxStamina"])*20
player:hud_change(playerInfo["hud"], "number", numBars)
end
end
end
if gameTime > 0.4 then
gameTime = 0
end
end)
function setSprinting(playerName, sprinting) --Sets the state of a player (0=stopped/moving, 1=sprinting)
local player = minetest.get_player_by_name(playerName)
if sprint.players[playerName] then
sprint.players[playerName]["sprinting"] = sprinting
if sprinting == true then
player:set_physics_override({speed=SPRINT_SPEED,jump=SPRINT_JUMP})
elseif sprinting == false then
player:set_physics_override({speed=1.0,jump=1.0})
end
return true
end
return false
end
|
[sprint] Fix method name and stamina HUD bar max_value change
|
[sprint] Fix method name and stamina HUD bar max_value change
|
Lua
|
unlicense
|
paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server
|
b994f779869287930c5ccb1065b8154283a0dc74
|
make-runtime.lua
|
make-runtime.lua
|
local lm = require "luamake"
local platform = require "bee.platform"
lm.gcc = 'clang'
lm.gxx = 'clang++'
lm.arch = ARGUMENTS.arch or 'x64'
lm.bindir = ("build/%s/bin/%s"):format(lm.plat, lm.arch)
lm.objdir = ("build/%s/obj/%s"):format(lm.plat, lm.arch)
local BUILD_BIN = platform.OS ~= "Windows" or lm.arch == "x86"
local install_deps = {
BUILD_BIN and "bee",
BUILD_BIN and "lua",
BUILD_BIN and "bootstrap",
BUILD_BIN and "inject",
BUILD_BIN and platform.OS == "Windows" and "lua54",
platform.OS == "Windows" and "launcher",
}
if BUILD_BIN then
lm:import '3rd/bee.lua/make.lua'
if platform.OS == "Windows" then
lm:shared_library 'inject' {
deps = {
"bee",
"lua54"
},
includes = {
"3rd/bee.lua",
lm.arch == "x86" and "3rd/wow64ext/src",
},
sources = {
"src/process_inject/injectdll.cpp",
"src/process_inject/query_process.cpp",
"src/process_inject/inject.cpp",
lm.arch == "x86" and "3rd/wow64ext/src/wow64ext.cpp",
},
links = {
"advapi32",
}
}
else
lm:shared_library 'inject' {
deps = {
"bee",
},
includes = {
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"src/process_inject/inject_osx.cpp",
}
}
end
end
if platform.OS == "Windows" then
lm:source_set 'detours' {
rootdir = "3rd/detours/src",
permissive = true,
sources = {
"*.cpp",
"!uimports.cpp"
}
}
lm:lua_library 'launcher' {
export_luaopen = false,
deps = {
"detours",
},
includes = {
"3rd/bee.lua",
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"3rd/bee.lua/bee/error.cpp",
"3rd/bee.lua/bee/utility/unicode_win.cpp",
"3rd/bee.lua/bee/utility/path_helper.cpp",
"3rd/bee.lua/bee/utility/file_helper.cpp",
"src/remotedebug/rdebug_delayload.cpp",
"src/launcher/*.cpp",
},
defines = {
"BEE_INLINE",
"_CRT_SECURE_NO_WARNINGS",
},
links = {
"ws2_32",
"user32",
"delayimp",
},
ldflags = '/DELAYLOAD:lua54.dll',
}
end
lm:source_set 'runtime/onelua' {
includes = {
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"src/remotedebug/onelua.c",
},
flags = {
platform.OS == "Linux" and "-fPIC",
platform.OS ~= "Windows" and "-fvisibility=hidden",
}
}
for _, luaver in ipairs {"lua51","lua52","lua53","lua54"} do
install_deps[#install_deps+1] = "runtime/"..luaver.."/lua"
install_deps[#install_deps+1] = "runtime/"..luaver.."/remotedebug"
if platform.OS == "Windows" then
install_deps[#install_deps+1] = "runtime/"..luaver.."/"..luaver
end
lm.rootdir = '3rd/'..luaver
if platform.OS == "Windows" then
lm:shared_library ('runtime/'..luaver..'/'..luaver) {
sources = {
"*.c",
"!lua.c",
"!luac.c",
},
defines = {
"LUA_BUILD_AS_DLL",
luaver == "lua51" and "_CRT_SECURE_NO_WARNINGS",
luaver == "lua52" and "_CRT_SECURE_NO_WARNINGS",
}
}
lm:executable ('runtime/'..luaver..'/lua') {
output = "lua",
deps = ('runtime/'..luaver..'/'..luaver),
sources = {
"lua.c",
},
defines = {
luaver == "lua51" and "_CRT_SECURE_NO_WARNINGS",
luaver == "lua52" and "_CRT_SECURE_NO_WARNINGS",
}
}
else
lm:executable ('runtime/'..luaver..'/lua') {
sources = {
"*.c",
"!luac.c",
},
defines = {
luaver == "lua51" and "_XOPEN_SOURCE=600",
luaver == "lua52" and "_XOPEN_SOURCE=600",
platform.OS == "macOS" and "LUA_USE_MACOSX",
platform.OS == "Linux" and "LUA_USE_LINUX",
},
ldflags = {
platform.OS == "Linux" and "-Wl,-E"
},
visibility = "default",
links = {
"m",
"dl",
"readline",
}
}
end
lm.rootdir = ''
local lua_version_num = 100 * math.tointeger(luaver:sub(4,4)) + math.tointeger(luaver:sub(5,5))
lm:shared_library ('runtime/'..luaver..'/remotedebug') {
deps = {
platform.OS == "Windows" and ('runtime/'..luaver..'/'..luaver),
"runtime/onelua",
},
defines = {
"BEE_STATIC",
"BEE_INLINE",
("DBG_LUA_VERSION=%d"):format(lua_version_num),
platform.OS == "Windows" and "_CRT_SECURE_NO_WARNINGS",
},
includes = {
"3rd/bee.lua/",
"3rd/bee.lua/3rd/lua-seri",
platform.OS ~= "Windows" and "3rd/"..luaver,
},
sources = {
"src/remotedebug/*.cpp",
"3rd/bee.lua/bee/error.cpp",
"3rd/bee.lua/bee/net/*.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/platform/version_win.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/utility/module_version_win.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/utility/unicode_win.cpp",
},
links = {
platform.OS == "Windows" and "version",
platform.OS == "Windows" and "ws2_32",
platform.OS == "Windows" and "user32",
platform.OS == "Windows" and "delayimp",
platform.OS == "Linux" and "stdc++",
platform.OS == "Linux" and "pthread",
},
ldflags = {
platform.OS == "Windows" and ("/DELAYLOAD:%s.dll"):format(luaver),
},
flags = {
platform.OS ~= "Windows" and "-fvisibility=hidden"
}
}
end
lm:build 'install' {
'$luamake', 'lua', 'make/install-runtime.lua', lm.plat, lm.arch,
deps = install_deps
}
lm:default {
"install",
}
|
local lm = require "luamake"
local platform = require "bee.platform"
lm.gcc = 'clang'
lm.gxx = 'clang++'
lm.arch = ARGUMENTS.arch or 'x64'
lm.bindir = ("build/%s/bin/%s"):format(lm.plat, lm.arch)
lm.objdir = ("build/%s/obj/%s"):format(lm.plat, lm.arch)
local BUILD_BIN = platform.OS ~= "Windows" or lm.arch == "x86"
local install_deps = {
BUILD_BIN and "bee",
BUILD_BIN and "lua",
BUILD_BIN and "bootstrap",
BUILD_BIN and "inject",
BUILD_BIN and platform.OS == "Windows" and "lua54",
platform.OS == "Windows" and "launcher",
}
if BUILD_BIN then
lm:import '3rd/bee.lua/make.lua'
if platform.OS == "Windows" then
lm:shared_library 'inject' {
deps = {
"bee",
"lua54"
},
includes = {
"3rd/bee.lua",
lm.arch == "x86" and "3rd/wow64ext/src",
},
sources = {
"src/process_inject/injectdll.cpp",
"src/process_inject/query_process.cpp",
"src/process_inject/inject.cpp",
lm.arch == "x86" and "3rd/wow64ext/src/wow64ext.cpp",
},
links = {
"advapi32",
}
}
else
lm:shared_library 'inject' {
deps = {
"bee",
},
includes = {
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"src/process_inject/inject_osx.cpp",
}
}
end
end
if platform.OS == "Windows" then
lm:source_set 'detours' {
rootdir = "3rd/detours/src",
permissive = true,
sources = {
"*.cpp",
"!uimports.cpp"
}
}
lm:lua_library 'launcher' {
export_luaopen = false,
deps = {
"detours",
},
includes = {
"3rd/bee.lua",
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"3rd/bee.lua/bee/error.cpp",
"3rd/bee.lua/bee/utility/unicode_win.cpp",
"3rd/bee.lua/bee/utility/path_helper.cpp",
"3rd/bee.lua/bee/utility/file_helper.cpp",
"src/remotedebug/rdebug_delayload.cpp",
"src/launcher/*.cpp",
},
defines = {
"BEE_INLINE",
"_CRT_SECURE_NO_WARNINGS",
},
links = {
"ws2_32",
"user32",
"delayimp",
},
ldflags = '/DELAYLOAD:lua54.dll',
}
end
lm:source_set 'runtime/onelua' {
includes = {
"3rd/bee.lua/3rd/lua/src",
},
sources = {
"src/remotedebug/onelua.c",
},
flags = {
platform.OS == "Linux" and "-fPIC",
platform.OS ~= "Windows" and "-fvisibility=hidden",
}
}
for _, luaver in ipairs {"lua51","lua52","lua53","lua54"} do
install_deps[#install_deps+1] = "runtime/"..luaver.."/lua"
install_deps[#install_deps+1] = "runtime/"..luaver.."/remotedebug"
if platform.OS == "Windows" then
install_deps[#install_deps+1] = "runtime/"..luaver.."/"..luaver
end
lm.rootdir = '3rd/'..luaver
if platform.OS == "Windows" then
lm:shared_library ('runtime/'..luaver..'/'..luaver) {
sources = {
"*.c",
"!lua.c",
"!luac.c",
},
defines = {
"LUA_BUILD_AS_DLL",
luaver == "lua51" and "_CRT_SECURE_NO_WARNINGS",
luaver == "lua52" and "_CRT_SECURE_NO_WARNINGS",
}
}
lm:executable ('runtime/'..luaver..'/lua') {
output = "lua",
deps = ('runtime/'..luaver..'/'..luaver),
sources = {
"lua.c",
},
defines = {
luaver == "lua51" and "_CRT_SECURE_NO_WARNINGS",
luaver == "lua52" and "_CRT_SECURE_NO_WARNINGS",
}
}
else
lm:executable ('runtime/'..luaver..'/lua') {
sources = {
"*.c",
"!luac.c",
},
defines = {
luaver == "lua51" and "_XOPEN_SOURCE=600",
luaver == "lua52" and "_XOPEN_SOURCE=600",
(luaver == "lua51" and platform.OS == "macOS") and "LUA_USE_DLOPEN",
platform.OS == "macOS" and "LUA_USE_MACOSX",
platform.OS == "Linux" and "LUA_USE_LINUX",
},
ldflags = {
platform.OS == "Linux" and "-Wl,-E"
},
visibility = "default",
links = {
"m",
"dl",
"readline",
}
}
end
lm.rootdir = ''
local lua_version_num = 100 * math.tointeger(luaver:sub(4,4)) + math.tointeger(luaver:sub(5,5))
lm:shared_library ('runtime/'..luaver..'/remotedebug') {
deps = {
platform.OS == "Windows" and ('runtime/'..luaver..'/'..luaver),
"runtime/onelua",
},
defines = {
"BEE_STATIC",
"BEE_INLINE",
("DBG_LUA_VERSION=%d"):format(lua_version_num),
platform.OS == "Windows" and "_CRT_SECURE_NO_WARNINGS",
},
includes = {
"3rd/bee.lua/",
"3rd/bee.lua/3rd/lua-seri",
platform.OS ~= "Windows" and "3rd/"..luaver,
},
sources = {
"src/remotedebug/*.cpp",
"3rd/bee.lua/bee/error.cpp",
"3rd/bee.lua/bee/net/*.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/platform/version_win.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/utility/module_version_win.cpp",
platform.OS == "Windows" and "3rd/bee.lua/bee/utility/unicode_win.cpp",
},
links = {
platform.OS == "Windows" and "version",
platform.OS == "Windows" and "ws2_32",
platform.OS == "Windows" and "user32",
platform.OS == "Windows" and "delayimp",
platform.OS == "Linux" and "stdc++",
platform.OS == "Linux" and "pthread",
},
ldflags = {
platform.OS == "Windows" and ("/DELAYLOAD:%s.dll"):format(luaver),
},
flags = {
platform.OS ~= "Windows" and "-fvisibility=hidden"
}
}
end
lm:build 'install' {
'$luamake', 'lua', 'make/install-runtime.lua', lm.plat, lm.arch,
deps = install_deps
}
lm:default {
"install",
}
|
Fixed #74
|
Fixed #74
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
5481c41e01c52fd55336c713bd530dbcd1c92a40
|
lua/plugins/lsp.lua
|
lua/plugins/lsp.lua
|
local nvim = require('nvim')
local plugs = require('nvim').plugs
local executable = require('nvim').fn.executable
local nvim_set_autocmd = require('nvim').nvim_set_autocmd
local nvim_set_command = require('nvim').nvim_set_command
local ok, lsp = pcall(require, 'nvim_lsp')
if not ok then
return nil
end
local servers = {
sh = { bashls = 'bash-language-server', },
docker = { dockerls = 'docker-language-server', },
rust = { rust_analyzer = 'rust_analyzer', },
go = { gopls = 'gopls', },
latex = { texlab = 'texlab', },
python = { pyls = 'pyls', },
c = {
ccls = 'ccls',
clangd = 'clangd',
},
cpp = {
ccls = 'ccls',
clangd = 'clangd',
},
}
local available_languages = {}
for language,options in pairs(servers) do
for option,server in pairs(options) do
if executable(server) == 1 then
lsp[option].setup({})
if language ~= 'latex' or plugs['vimtex'] == nil then -- Use vimtex function instead
available_languages[#available_languages + 1] = language
end
break
end
end
end
nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'CursorHold',
available_languages,
"lua vim.lsp.buf.hover()",
{group = 'NvimLSP', nested = true}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
|
local nvim = require('nvim')
local plugs = require('nvim').plugs
local executable = require('nvim').fn.executable
local nvim_set_autocmd = require('nvim').nvim_set_autocmd
local nvim_set_command = require('nvim').nvim_set_command
local ok, lsp = pcall(require, 'nvim_lsp')
if not ok then
return nil
end
local servers = {
sh = { bashls = 'bash-language-server', },
docker = { dockerls = 'docker-language-server', },
rust = { rust_analyzer = 'rust_analyzer', },
go = { gopls = 'gopls', },
latex = { texlab = 'texlab', },
python = { pyls = 'pyls', },
c = { -- Since both clangd and ccls works with C,Cpp,ObjC and ObjCpp; just 1 setup is ok
ccls = 'ccls',
clangd = 'clangd',
},
}
local available_languages = {}
for language,options in pairs(servers) do
for option,server in pairs(options) do
if executable(server) == 1 then
lsp[option].setup({})
if language ~= 'latex' or plugs['vimtex'] == nil then -- Use vimtex function instead
available_languages[#available_languages + 1] = language
if language == 'c' then
available_languages[#available_languages + 1] = 'cpp'
available_languages[#available_languages + 1] = 'objc'
available_languages[#available_languages + 1] = 'objcpp'
end
end
break
end
end
end
nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'})
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"autocmd CursorHold <buffer> lua vim.lsp.buf.hover()",
{group = 'NvimLSP', nested = true}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
nvim_set_autocmd(
'FileType',
available_languages,
"lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})",
{group = 'NvimLSP'}
)
|
fix: Made some lsp config fixes
|
fix: Made some lsp config fixes
Fix CursorHold autocmd
Add missing C-family filetypes
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
0dfdb55734267f03d9ee561f05c95d1a5d31c010
|
src/kong/plugins/authentication/schema.lua
|
src/kong/plugins/authentication/schema.lua
|
local constants = require "kong.constants"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
print "HERE"
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then
return false, "This field is not available for \""..BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
fixing import and removing debug info
|
fixing import and removing debug info
|
Lua
|
apache-2.0
|
ajayk/kong,rafael/kong,kyroskoh/kong,beauli/kong,smanolache/kong,icyxp/kong,isdom/kong,li-wl/kong,Kong/kong,ejoncas/kong,rafael/kong,streamdataio/kong,xvaara/kong,streamdataio/kong,ccyphers/kong,akh00/kong,jerizm/kong,jebenexer/kong,isdom/kong,Kong/kong,vzaramel/kong,Mashape/kong,ejoncas/kong,shiprabehera/kong,Vermeille/kong,kyroskoh/kong,vzaramel/kong,salazar/kong,ind9/kong,ind9/kong,Kong/kong
|
d52b64983ae9bfbfe859766095cb314be00fe40e
|
src/lfs/application.lua
|
src/lfs/application.lua
|
require("wipe")
local sensors = require("sensors")
local dht_sensors = require("dht_sensors")
local ds18b20_sensors = require("ds18b20_sensors")
local actuators = require("actuators")
local settings = require("settings")
local sensorTimer = tmr.create()
-- globals
sensorPut = {}
actuatorGet = {}
-- initialize binary sensors
for i, sensor in pairs(sensors) do
print("Heap:", node.heap(), "Initializing sensor pin:", sensor.pin)
gpio.mode(sensor.pin, gpio.INPUT, gpio.PULLUP)
end
-- initialize actuators
for i, actuator in pairs(actuators) do
print("Heap:", node.heap(), "Initializing actuator pin:", actuator.pin)
gpio.mode(actuator.pin, gpio.OUTPUT)
table.insert(actuatorGet, actuator)
end
-- initialize DHT sensors
if #dht_sensors > 0 then
require("dht")
local function readDht(pin)
local status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
local temperature_string = temp .. "." .. math.abs(temp_dec)
local humidity_string = humi .. "." .. humi_dec
print("Heap:", node.heap(), "Temperature:", temperature_string, "Humidity:", humidity_string)
table.insert(sensorPut, { pin = pin, temp = temperature_string, humi = humidity_string })
else
print("Heap:", node.heap(), "DHT Status:", status)
end
end
for i, sensor in pairs(dht_sensors) do
local pollInterval = tonumber(sensor.poll_interval) or 0
pollInterval = (pollInterval > 0 and pollInterval or 3) * 60 * 1000
print("Heap:", node.heap(), "Polling DHT on pin " .. sensor.pin .. " every " .. pollInterval .. "ms")
tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() readDht(sensor.pin) end)
readDht(sensor.pin)
end
end
-- initialize ds18b20 temp sensors
if #ds18b20_sensors > 0 then
local function ds18b20Callback(pin)
local callbackFn = function(i, rom, res, temp, temp_dec, par)
local temperature_string = temp .. "." .. math.abs(temp_dec)
print("Heap:", node.heap(), "Temperature:", temperature_string, "Resolution:", res)
if (res >= 12) then
table.insert(sensorPut, { pin = pin, temp = temperature_string,
addr = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
string.match(rom, "(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")) })
end
end
return callbackFn
end
for i, sensor in pairs(ds18b20_sensors) do
local pollInterval = tonumber(sensor.poll_interval) or 0
pollInterval = (pollInterval > 0 and pollInterval or 3) * 60 * 1000
print("Heap:", node.heap(), "Polling DS18b20 on pin " .. sensor.pin .. " every " .. pollInterval .. "ms")
local callbackFn = ds18b20Callback(sensor.pin)
ds18b20.setup(sensor.pin)
ds18b20.setting({}, 12)
tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() ds18b20.read(callbackFn, {}) end)
ds18b20.read(callbackFn, {})
end
end
-- Poll every configured binary sensor and insert into the request queue when changed
sensorTimer:alarm(200, tmr.ALARM_AUTO, function(t)
for i, sensor in pairs(sensors) do
if sensor.state ~= gpio.read(sensor.pin) then
sensor.state = gpio.read(sensor.pin)
table.insert(sensorPut, { pin = sensor.pin, state = sensor.state })
end
end
end)
-- Support different communication methods for reporting to upstream platforms
local endpoint_type = settings.endpoint_type or 'rest'
-- REST is the default communication method and is used by the original SmartThings, Hubitat, Home Assistant,
-- and OpenHab integrations.
if endpoint_type == 'rest' then
require("rest_endpoint")(settings)
-- AWS IoT is used for the Konnected Cloud Connector or custom integrations build on AWS
elseif endpoint_type == 'aws_iot' then
require("aws_iot")()
end
|
require("wipe")
local sensors = require("sensors")
local dht_sensors = require("dht_sensors")
local ds18b20_sensors = require("ds18b20_sensors")
local actuators = require("actuators")
local settings = require("settings")
local sensorTimer = tmr.create()
-- globals
sensorPut = {}
actuatorGet = {}
-- initialize binary sensors
for i, sensor in pairs(sensors) do
print("Heap:", node.heap(), "Initializing sensor pin:", sensor.pin)
gpio.mode(sensor.pin, gpio.INPUT, gpio.PULLUP)
end
-- initialize actuators
for i, actuator in pairs(actuators) do
local initialState = actuator.trigger == gpio.LOW and gpio.HIGH or gpio.LOW
print("Heap:", node.heap(), "Initializing actuator pin:", actuator.pin, "on:", actuator.trigger or gpio.HIGH, "off:", initialState)
gpio.write(actuator.pin, initialState)
gpio.mode(actuator.pin, gpio.OUTPUT)
table.insert(actuatorGet, actuator)
end
-- initialize DHT sensors
if #dht_sensors > 0 then
require("dht")
local function readDht(pin)
local status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
local temperature_string = temp .. "." .. math.abs(temp_dec)
local humidity_string = humi .. "." .. humi_dec
print("Heap:", node.heap(), "Temperature:", temperature_string, "Humidity:", humidity_string)
table.insert(sensorPut, { pin = pin, temp = temperature_string, humi = humidity_string })
else
print("Heap:", node.heap(), "DHT Status:", status)
end
end
for i, sensor in pairs(dht_sensors) do
local pollInterval = tonumber(sensor.poll_interval) or 0
pollInterval = (pollInterval > 0 and pollInterval or 3) * 60 * 1000
print("Heap:", node.heap(), "Polling DHT on pin " .. sensor.pin .. " every " .. pollInterval .. "ms")
tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() readDht(sensor.pin) end)
readDht(sensor.pin)
end
end
-- initialize ds18b20 temp sensors
if #ds18b20_sensors > 0 then
local function ds18b20Callback(pin)
local callbackFn = function(i, rom, res, temp, temp_dec, par)
local temperature_string = temp .. "." .. math.abs(temp_dec)
print("Heap:", node.heap(), "Temperature:", temperature_string, "Resolution:", res)
if (res >= 12) then
table.insert(sensorPut, { pin = pin, temp = temperature_string,
addr = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
string.match(rom, "(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")) })
end
end
return callbackFn
end
for i, sensor in pairs(ds18b20_sensors) do
local pollInterval = tonumber(sensor.poll_interval) or 0
pollInterval = (pollInterval > 0 and pollInterval or 3) * 60 * 1000
print("Heap:", node.heap(), "Polling DS18b20 on pin " .. sensor.pin .. " every " .. pollInterval .. "ms")
local callbackFn = ds18b20Callback(sensor.pin)
ds18b20.setup(sensor.pin)
ds18b20.setting({}, 12)
tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() ds18b20.read(callbackFn, {}) end)
ds18b20.read(callbackFn, {})
end
end
-- Poll every configured binary sensor and insert into the request queue when changed
sensorTimer:alarm(200, tmr.ALARM_AUTO, function(t)
for i, sensor in pairs(sensors) do
if sensor.state ~= gpio.read(sensor.pin) then
sensor.state = gpio.read(sensor.pin)
table.insert(sensorPut, { pin = sensor.pin, state = sensor.state })
end
end
end)
-- Support different communication methods for reporting to upstream platforms
local endpoint_type = settings.endpoint_type or 'rest'
-- REST is the default communication method and is used by the original SmartThings, Hubitat, Home Assistant,
-- and OpenHab integrations.
if endpoint_type == 'rest' then
require("rest_endpoint")(settings)
-- AWS IoT is used for the Konnected Cloud Connector or custom integrations build on AWS
elseif endpoint_type == 'aws_iot' then
require("aws_iot")()
end
|
fix issue with low-level relays activating on reboot; always explicitly set to off
|
fix issue with low-level relays activating on reboot; always explicitly set to off
|
Lua
|
apache-2.0
|
konnected-io/konnected-security,konnected-io/konnected-security
|
c9f644b6085dcd839ce80da6ff24bd464bf9460c
|
histArray.lua
|
histArray.lua
|
-- XXX: not fully implemented yet. See the tests in spec/
local M = {}
local function lookupKeyIn(proxy, private, key)
-- XXX
if type(key) == 'number' then
-- blah blah blah
elseif key == 'histSize' then
return private.histSize
else
return 'whatever'
end
end
local function setKeyIn(proxy, private, key, newVal)
if type(key) ~= 'number' then
error("attempt to set non-number in HistArray")
end
if math.floor(key) ~= key then
error("attempt to set non-integer index in HistArray")
end
if key <= private.latestIndex then
error("attempt to set old index in HistArray")
end
-- actually set it XXX
end
function M.new(histSize)
if type(histSize) ~= 'number' or math.floor(histSize) ~= histSize then
error("history size must be an integer")
end
if histSize < 1 then error("history size must be at least 1") end
local private = {}
local proxy = {}
local meta = {
__index = function(proxy, key)
return lookupKeyIn(proxy, private, key)
end,
__newindex = function(proxy, key, newVal)
setKeyIn(proxy, private, key, newVal)
end
}
setmetatable(proxy, meta)
private.histSize = histSize
-- XXX: more initialization
return proxy
end
return M
|
-- XXX: not fully implemented yet. See the tests in spec/
local M = {}
local function computeActualIndexFor(key, histSize)
return ((key-1) % (histSize+1) + 1)
end
local function getAllElementsFrom(proxy, private)
local results = {}
local earliestIndex = private.latestIndex - private.histSize
for i=earliestIndex,private.latestIndex do
results[i] = private[computeActualIndexFor(i, private.histSize)]
end
return results
end
local function lookupKeyIn(proxy, private, key)
if type(key) == 'number' then
if math.floor(key) ~= key then
error("attempt to access non-integer index in HistArray")
end
-- Check if index is valid
if key > private.latestIndex then
error("attempt to access too-new index in HistArray")
elseif key < private.latestIndex - private.histSize then
error("attempt to access too-old index in HistArray")
end
return private[computeActualIndexFor(key, private.histSize)]
elseif key == 'histSize' then
return private.histSize
elseif key == 'all' then
return private.all
elseif key == '_debug' then
return private -- XXX
else
error("attempt to access undefined HistArray key " .. tostring(key))
end
end
local function setKeyIn(proxy, private, key, newVal)
if type(key) ~= 'number' then
error("attempt to set non-number in HistArray")
end
if math.floor(key) ~= key then
error("attempt to set non-integer index in HistArray")
end
if key <= private.latestIndex then
error("attempt to set old index in HistArray")
end
local previousHighIndex = private.latestIndex
private[computeActualIndexFor(key, private.histSize)] = newVal
private.latestIndex = key
-- Zero-fill if we advanced by more than one.
local backFillTo = math.max(key - private.histSize, previousHighIndex + 1)
for i=key-1,backFillTo,-1 do
private[computeActualIndexFor(i, private.histSize)] = 0
end
end
function M.new(histSize)
if type(histSize) ~= 'number' or math.floor(histSize) ~= histSize then
error("history size must be an integer")
end
if histSize < 1 then error("history size must be at least 1") end
local private = {}
local proxy = {}
local meta = {
__index = function(proxy, key)
return lookupKeyIn(proxy, private, key)
end,
__newindex = function(proxy, key, newVal)
setKeyIn(proxy, private, key, newVal)
end
}
setmetatable(proxy, meta)
private.histSize = histSize
private.all = function(proxy)
return getAllElementsFrom(proxy, private)
end
-- Initialize array with zeroes.
for v = 1, histSize+1 do private[v] = 0 end
private.latestIndex = 0
return proxy
end
return M
|
Finish HistArray implementation
|
Finish HistArray implementation
Beware of bugs in this code. I have only shown it passes the 9 tests I
wrote, not tried to use it :)
|
Lua
|
mit
|
graue/luasynth
|
54ec82b70bf56816d16c142c0b9239769cd8b529
|
nvim/.config/nvim/lua/sets.lua
|
nvim/.config/nvim/lua/sets.lua
|
vim.g.mapleader = ' '
local opt = vim.o
opt.termguicolors = true
opt.mouse = 'a'
-- Tab control
opt.tabstop = 2 -- the visible width of tabs
opt.softtabstop = opt.tabstop -- edit as if the tabs are 4 characters wide
opt.shiftwidth = opt.tabstop -- number of spaces to use for indent and unindent
opt.expandtab = true -- insert tabs rather than spaces for <Tab>
opt.shiftround = true -- round indent to a multiple of 'shiftwidth'
opt.undolevels = 5000
opt.undodir = '~/.VIM_UNDO_FILES'
opt.undofile = true
opt.clipboard = 'unnamedplus'
opt.scrolloff = 10 -- lines of text around cursor
opt.wildoptions = 'pum'
opt.pumblend = 17 -- floating window popup menu for command line completion
opt.ignorecase = true -- case insensitive searching
opt.smartcase = true -- case-sensitive if expression contains a capital letter
opt.number = true
opt.relativenumber = true
opt.cursorline = true -- highlight current line
opt.wrap = false -- do not wrap long lines
opt.updatetime = 1000 -- update the swap file quicker (also helps with updating git status)
|
vim.g.mapleader = ' '
local opt = vim.api.nvim_set_option
opt('termguicolors', true)
opt('mouse', 'a')
-- Tab control
opt('tabstop', 2) -- the visible width of tabs
opt('softtabstop', 2) -- edit as if the tabs are 4 characters wide
opt('shiftwidth', 2) -- number of spaces to use for indent and unindent
opt('expandtab', true) -- insert tabs rather than spaces for <Tab>
opt('shiftround', true) -- round indent to a multiple of 'shiftwidth'
opt('undolevels', 5000)
opt('undodir', '~/.VIM_UNDO_FILES')
opt('undofile', true)
opt('clipboard', 'unnamedplus')
opt('scrolloff', 10) -- lines of text around cursor
opt('wildoptions', 'pum')
opt('pumblend', 17) -- floating window popup menu for command line completion
opt('ignorecase', true) -- case insensitive searching
opt('smartcase', true) -- case-sensitive if expression contains a capital letter
vim.wo.number = true
vim.wo.relativenumber = true
opt('cursorline', true) -- highlight current line
opt('wrap', false) -- do not wrap long lines
opt('updatetime', 100) -- update the swap file quicker (also helps with updating git status)
|
Fix setting options
|
Fix setting options
|
Lua
|
mit
|
gblock0/dotfiles
|
15d7ac9da602c29c7d8b0d3ad28152487d4a6e1a
|
new/xml.lua
|
new/xml.lua
|
#!/usr/bin/lua
local parseargs, collect, strip_escapes
strip_escapes = function (s)
s = string.gsub(s, '>', '>')
s = string.gsub(s, '<', '<')
return s
end
function parseargs(s)
local arg = {}
string.gsub(s, "([%w_]+)=([\"'])(.-)%2", function (w, _, a)
arg[strip_escapes(w)] = strip_escapes(a)
end)
return arg
end
function collect(s)
local stack = {}
local top = {}
table.insert(stack, top)
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string.find(s, "<(%/?)(%w+)(.-)(%/?)>", j)
if not ni then break end
local text = string.sub(s, i, ni-1)
if not string.find(text, "^%s*$") then
table.insert(top, text)
end
if empty == "/" then -- empty element tag
table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
elseif c == "" then -- start tag
top = {label=label, xarg=parseargs(xarg)}
table.insert(stack, top) -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("nothing to close with "..label)
end
if toclose.label ~= label then
error("trying to close "..toclose.label.." with "..label)
end
table.insert(top, toclose)
toclose.parent = top
if toclose.xarg.name then
top.byname = top.byname or {}
local overload = top.byname[toclose.xarg.name]
if overload then
-- FIXME: most probably a case of overload: check
if overload.tag~='Overloaded' then
--print('created overload '..toclose.xarg.name)
overload = { tag='Overloaded', xargs={ name=toclose.xarg.name }, overload }
top.byname[toclose.xarg.name] = overload
end
table.insert(overload, toclose)
--print('used overload '..toclose.xarg.name)
else
top.byname[toclose.xarg.name] = toclose
end
end
if toclose.xarg.id then
stack[1].byid = stack[1].byid or {}
stack[1].byid[toclose.xarg.id] = toclose
end
end
i = j+1
end
local text = string.sub(s, i)
if not string.find(text, "^%s*$") then
table.insert(stack[#stack], text)
end
if #stack > 1 then
error("unclosed "..stack[stack.n].label)
end
return stack[1]
end
return collect
|
#!/usr/bin/lua
local parseargs, collect, strip_escapes
strip_escapes = function (s)
s = string.gsub(s, '>', '>')
s = string.gsub(s, '<', '<')
return s
end
function parseargs(s)
local arg = {}
string.gsub(s, "([%w_]+)=([\"'])(.-)%2", function (w, _, a)
arg[strip_escapes(w)] = strip_escapes(a)
end)
return arg
end
function collect(s)
local stack = {}
local top = {}
table.insert(stack, top)
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string.find(s, "<(%/?)(%w+)(.-)(%/?)>", j)
if not ni then break end
local text = string.sub(s, i, ni-1)
if not string.find(text, "^%s*$") then
table.insert(top, text)
end
if empty == "/" then -- empty element tag
table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
elseif c == "" then -- start tag
top = {label=label, xarg=parseargs(xarg)}
table.insert(stack, top) -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("nothing to close with "..label)
end
if toclose.label ~= label then
error("trying to close "..toclose.label.." with "..label)
end
table.insert(top, toclose)
toclose.parent = top
if toclose.xarg.name then
--[[
local print = toclose.xarg.id=='_4334' and function(...)
io.stderr:write(...)
io.stderr:write'\n'
end or function()end
--]]
top.byname = top.byname or {}
local overload = top.byname[toclose.xarg.name]
if overload then
-- FIXME: most probably a case of overload: check
if overload.label~='Overloaded' then
--print('created overload '..toclose.xarg.name)
top.byname[toclose.xarg.name] = {
label='Overloaded',
xarg={ name=toclose.xarg.name },
overload
}
end
table.insert(top.byname[toclose.xarg.name], toclose)
--print('used overload '..toclose.xarg.name)
else
top.byname[toclose.xarg.name] = toclose
--print('not overloaded')
end
end
if toclose.xarg.id then
stack[1].byid = stack[1].byid or {}
stack[1].byid[toclose.xarg.id] = toclose
end
end
i = j+1
end
local text = string.sub(s, i)
if not string.find(text, "^%s*$") then
table.insert(stack[#stack], text)
end
if #stack > 1 then
error("unclosed "..stack[stack.n].label)
end
return stack[1]
end
return collect
|
fixed how overloads were stored
|
fixed how overloads were stored
|
Lua
|
mit
|
mkottman/lqt,mkottman/lqt
|
d02b759ce383f8910e2eb6b2e431c08daa4d1b05
|
tests/check/windows.lua
|
tests/check/windows.lua
|
local math = require('math')
local os = require('os')
local string = require('string')
local helper = require('../helper')
local fixtures = require('/tests/fixtures').checks
local WindowsChecks = require('/check/windows').checks
local exports = {}
exports['test_windowsperfos_check'] = function(test, asserts)
local check = WindowsChecks.WindowsPerfOSCheck:new({id='foo', period=30})
asserts.ok(check._lastResult == nil)
check:run(function(result)
asserts.ok(result ~= nil)
asserts.ok(check._lastResult ~= nil)
if os.type() == 'win32' then
asserts.equals(result:getStatus(), 'success')
asserts.ok(#check._lastResult:serialize() > 0)
local metrics = result:getMetrics()['none']
asserts.ok(metrics['Processes']['t'] == 'uint32')
-- Values always become strings internally
asserts.ok(tonumber(metrics['Processes']['v']) > 0)
else
asserts.ok(result:getStatus() ~= 'success')
end
test.done()
end)
end
local function add_iterative_test(original_test_set, base_name, test_function)
local test_name = 'test_' .. base_name
if helper.test_configs == nil or helper.test_configs[test_name] == nil then
original_test_set[test_name] = function(test, asserts)
test.skip(test_name .. ' requires at least one config file entry')
end
else
for i, config in ipairs(helper.test_configs[test_name]) do
original_test_set[string.format('%s_%u', test_name, i)] = function(test, asserts)
return test_function(test, asserts, config)
end
end
end
return original_test_set
end
local function add_iterative_and_fixture_test(original_test_set, base_name, test_function)
local test_name = 'test_' .. base_name
if not fixtures[base_name .. ".txt"] then
original_test_set[test_name .. '_fixture'] = function(test, asserts)
test.skip(test_name .. '_fixture, fixture is missing')
end
else
original_test_set[test_name .. '_fixture'] = function(test, asserts)
return test_function(test, asserts, {db='foo', powershell_csv_fixture=fixtures[base_name .. ".txt"]})
end
end
return add_iterative_test(original_test_set, base_name, test_function)
end
local function mssql_test_common(check, test, asserts, specific_tests)
asserts.ok(check._lastResult == nil)
--p(check)
check:run(function(result)
asserts.ok(result ~= nil)
asserts.ok(check._lastResult ~= nil)
if os.type() == 'win32' then
asserts.equals(result:getStatus(), 'success')
asserts.ok(#check._lastResult:serialize() > 0, "no metrics")
--local metrics = result:getMetrics()['none']
--p(metrics)
specific_tests(result, test, asserts)
else
asserts.ok(result:getStatus() ~= 'success')
end
test.done()
end)
end
exports = add_iterative_and_fixture_test(exports, 'mssql_database', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerDatabaseCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['size']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_buffer_manager', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerBufferManagerCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_pages']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_sql_statistics', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerSQLStatisticsCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['sql_attention_rate']['v']) >= 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_memory_manager', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerMemoryManagerCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_server_memory']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_plan_cache', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerPlanCacheCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_cache_pages']['v']) > 0)
end
)
end)
return exports
|
local math = require('math')
local os = require('os')
local string = require('string')
local helper = require('../helper')
local fixtures = require('/tests/fixtures').checks
local WindowsChecks = require('/check/windows').checks
local exports = {}
exports['test_windowsperfos_check'] = function(test, asserts)
local check = WindowsChecks.WindowsPerfOSCheck:new({id='foo', period=30})
asserts.ok(check._lastResult == nil)
check:run(function(result)
asserts.ok(result ~= nil)
asserts.ok(check._lastResult ~= nil)
if os.type() == 'win32' then
asserts.equals(result:getStatus(), 'success')
asserts.ok(#check._lastResult:serialize() > 0)
local metrics = result:getMetrics()['none']
asserts.ok(metrics['Processes']['t'] == 'uint32')
-- Values always become strings internally
asserts.ok(tonumber(metrics['Processes']['v']) > 0)
else
asserts.ok(result:getStatus() ~= 'success')
end
test.done()
end)
end
local function add_iterative_test(original_test_set, base_name, test_function)
local test_name = 'test_' .. base_name
if helper.test_configs == nil or helper.test_configs[test_name] == nil then
original_test_set[test_name] = function(test, asserts)
test.skip(test_name .. ' requires at least one config file entry')
end
else
for i, config in ipairs(helper.test_configs[test_name]) do
original_test_set[string.format('%s_%u', test_name, i)] = function(test, asserts)
return test_function(test, asserts, config)
end
end
end
return original_test_set
end
local function add_iterative_and_fixture_test(original_test_set, base_name, test_function)
local test_name = 'test_' .. base_name
if not fixtures[base_name .. ".txt"] then
original_test_set[test_name .. '_fixture'] = function(test, asserts)
test.skip(test_name .. '_fixture, fixture is missing')
end
else
original_test_set[test_name .. '_fixture'] = function(test, asserts)
return test_function(test, asserts, {db='foo', powershell_csv_fixture=fixtures[base_name .. ".txt"]})
end
end
return add_iterative_test(original_test_set, base_name, test_function)
end
local function mssql_test_common(check, test, asserts, specific_tests)
asserts.ok(check._lastResult == nil)
--p(check)
check:run(function(result)
asserts.ok(result ~= nil)
asserts.ok(check._lastResult ~= nil)
if os.type() == 'win32' or check:getPowershellCSVFixture() then
asserts.equals(result:getStatus(), 'success')
asserts.ok(#check._lastResult:serialize() > 0, "no metrics")
--local metrics = result:getMetrics()['none']
--p(metrics)
specific_tests(result, test, asserts)
else
asserts.ok(result:getStatus() ~= 'success')
end
test.done()
end)
end
exports = add_iterative_and_fixture_test(exports, 'mssql_database', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerDatabaseCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['size']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_buffer_manager', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerBufferManagerCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_pages']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_sql_statistics', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerSQLStatisticsCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['sql_attention_rate']['v']) >= 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_memory_manager', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerMemoryManagerCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_server_memory']['v']) > 0)
end
)
end)
exports = add_iterative_and_fixture_test(exports, 'mssql_plan_cache', function(test, asserts, config)
mssql_test_common(WindowsChecks.MSSQLServerPlanCacheCheck:new({id='foo', period=30, details=config}),
test, asserts, function(result, test, asserts)
local metrics = result:getMetrics()['none']
-- Values always become strings internally
asserts.ok(tonumber(metrics['total_cache_pages']['v']) > 0)
end
)
end)
return exports
|
mssql fixture tests should also be successful outside of win32
|
mssql fixture tests should also be successful outside of win32
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
|
c67afc836e2013518d735cd9a21c8205ab3c33ad
|
share/luaplaylist/dailymotion.lua
|
share/luaplaylist/dailymotion.lua
|
-- $Id$
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion.com" )
and vlc.peek( 9 ) == "<!DOCTYPE"
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\"url=" )
then
path = vlc.decode_uri( string.gsub( line, "^.*param name=\"flashvars\" value=\"url=([^&]*).*$", "%1" ) )
end
--[[ if string.match( line, "<title>" )
then
title = vlc.decode_uri( string.gsub( line, "^.*<title>([^<]*).*$", "%1" ) )
end ]]
if string.match( line, "<meta name=\"description\"" )
then
name = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"Regarder (.*) sur Dailymotion Partagez Vos Videos\..*$", "%1" ) )
description = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"Regarder .* sur Dailymotion Partagez Vos Videos\. ([^\"]*)\".*$", "%1" ) )
end
if string.match( line, "<link rel=\"thumbnail\"" )
then
arturl = string.gsub( line, "^.*\"thumbnail\" type=\"([^\"]*)\".*$", "http://%1" ) -- looks like the dailymotion people mixed up type and href here ...
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
-- $Id$
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion.com" )
and vlc.peek( 9 ) == "<!DOCTYPE"
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\"url=" )
then
path = vlc.decode_uri( string.gsub( line, "^.*param name=\"flashvars\" value=\"url=([^&]*).*$", "%1" ) )
end
--[[ if string.match( line, "<title>" )
then
title = vlc.decode_uri( string.gsub( line, "^.*<title>([^<]*).*$", "%1" ) )
end ]]
if string.match( line, "<meta name=\"description\"" )
then
name = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ (.*) %w+ %w+ %w+ %w+ Videos\..*$", "%1" ) )
description = vlc.resolve_xml_special_chars( string.gsub( line, "^.*name=\"description\" content=\"%w+ .* %w+ %w+ %w+ %w+ Videos\. ([^\"]*)\".*$", "%1" ) )
end
if string.match( line, "<link rel=\"thumbnail\"" )
then
arturl = string.gsub( line, "^.*\"thumbnail\" type=\"([^\"]*)\".*$", "http://%1" ) -- looks like the dailymotion people mixed up type and href here ...
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
* dailymotion.lua: fix.
|
* dailymotion.lua: fix.
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc
|
00a7d113594f26a360a04da72301c164323fa978
|
lua/weapons/remotecontroller.lua
|
lua/weapons/remotecontroller.lua
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local ply = self:GetOwner()
local trace = ply:GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", ply, trace.Entity) then
self.Linked = trace.Entity
ply:ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if self.Linked then
self:Off()
end
return true
end
function SWEP:Deploy()
return true
end
function SWEP:OnDrop()
if not self.Linked then return end
self:Off()
self.Linked = nil
end
function SWEP:On()
local ply = self:GetOwner()
if IsValid(self.Linked) and self.Linked.HasPly and self.Linked:HasPly() then
if hook.Run("CanTool", ply, WireLib.dummytrace(self.Linked), "remotecontroller") then
if self.Linked.RC then
self.Linked:RCEject(self.Linked:GetPly())
else
self.Linked:GetPly():ExitVehicle()
end
else
ply:ChatPrint("Pod is in use.")
return
end
end
self.Active = true
self.OldMoveType = not ply:InVehicle() and ply:GetMoveType() or MOVETYPE_WALK
ply:SetMoveType(MOVETYPE_NONE)
ply:DrawViewModel(false)
if IsValid(self.Linked) and self.Linked.PlayerEntered then
self.Linked:PlayerEntered(ply, self)
end
end
function SWEP:Off()
local ply = self:GetOwner()
if self.Active then
ply:SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
ply:DrawViewModel(true)
if IsValid(self.Linked) then
self.Linked:PlayerExited(ply)
end
end
function SWEP:Think()
if not self.Linked then return end
if self:GetOwner():KeyPressed(IN_USE) then
if not self.Active then
self:On()
else
self:Off()
end
end
end
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local ply = self:GetOwner()
local trace = ply:GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", ply, trace.Entity) then
self.Linked = trace.Entity
ply:ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if self.Linked then
self:Off()
end
return true
end
function SWEP:Deploy()
return true
end
function SWEP:OnDrop()
if not self.Linked then return end
self:Off()
self.Linked = nil
end
function SWEP:On()
local ply = self:GetOwner()
if IsValid(self.Linked) and self.Linked.HasPly and self.Linked:HasPly() then
if hook.Run("CanTool", ply, WireLib.dummytrace(self.Linked), "remotecontroller") then
if self.Linked.RC then
self.Linked:RCEject(self.Linked:GetPly())
else
self.Linked:GetPly():ExitVehicle()
end
else
ply:ChatPrint("Pod is in use.")
return
end
end
self.Active = true
self.OldMoveType = not ply:InVehicle() and ply:GetMoveType() or MOVETYPE_WALK
ply:SetMoveType(MOVETYPE_NONE)
ply:DrawViewModel(false)
if IsValid(self.Linked) and self.Linked.PlayerEntered then
self.Linked:PlayerEntered(ply, self)
end
end
function SWEP:Off()
local ply = self:GetOwner()
if self.Active then
ply:SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
ply:DrawViewModel(true)
if IsValid(self.Linked) and self.Linked:GetPly() == ply then
self.Linked:PlayerExited(ply)
end
end
function SWEP:Think()
if not self.Linked then return end
if self:GetOwner():KeyPressed(IN_USE) then
if not self.Active then
self:On()
else
self:Off()
end
end
end
|
Fix swapping from/to RC circumventing driver check
|
Fix swapping from/to RC circumventing driver check
Currently the RC only requires that one is linked to the pod (not driving) in order to call PlayerExited when you put the tool away. This allows the RC to pass the pod occupancy check when you pull the tool back out (PlayerExited sets HasPly to nil) and then it's possible to hijack a player's vehicle.
Simple change requires that you also be the driver of the pod in order to run PlayerExited.
|
Lua
|
apache-2.0
|
sammyt291/wire,Grocel/wire,NezzKryptic/Wire,garrysmodlua/wire,wiremod/wire,dvdvideo1234/wire
|
8c228d1bda9b716576348964c8a07311bd3900b6
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 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
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 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
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8135 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
|
79c3b883ae3918fc0f675b70b67057331d1c0699
|
modules/twitch.lua
|
modules/twitch.lua
|
-- Module to display, search and alert twitch.tv streams
-- vim: set noexpandtab:
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local moduleName = 'twitch'
local key = moduleName
local store = ivar2.persist
local parseData = function(self, source, destination, data)
data = json.decode(data)
if data._total == 0 then
return {}
end
local streams = {}
for i=1, #data.streams do
local this = data.streams[i]
--TODO configure filter languages ?
if this.channel.broadcaster_language
and (this.channel.broadcaster_language == 'en' or
this.channel.broadcaster_language == 'no') then
table.insert(streams, this)
end
end
-- sort streams wrt viewer count
table.sort(streams, function(a,b) return a.viewers>b.viewers end)
return streams
end
local formatData = function(self, source, destination, streams, limit)
limit = limit or 5
local i = 0
local out = {}
for _, stream in pairs(streams) do
local viewers = tostring(math.floor(stream.viewers/1000)) .. 'k'
if viewers == '0k' then
viewers = stream.viewers
end
local title = ''
if stream.channel and stream.channel.status then
title = ': '..stream.channel.status
end
out[#out+1] = string.format(
"[%s] http://twitch.tv/%s %s %s",
util.bold(viewers), stream.channel.display_name, stream.game, title
)
i=i+1
if i > limit then break end
end
return out
end
local gameHandler= function(self, source, destination, input, limit)
limit = limit or 5
-- 'http://api.twitch.tv/kraken/streams?limit=20&offset=0&game='..util.urlEncode(input)..'&on_site=1',
simplehttp(
'https://api.twitch.tv/kraken/search/streams?limit='..tostring(limit)..'&offset=0&query='..util.urlEncode(input),
function(data)
local streams = parseData(self, source, destination, data)
if #streams == 0 then
local out = 'No streams found'
self:Msg('privmsg', destination, source, out)
else
local out = formatData(self, source, destination, streams, limit)
for _,line in pairs(out) do
self:Msg('privmsg', destination, source, line)
end
end
end
)
end
local allHandler = function(self, source, destination)
local url = 'https://api.twitch.tv/kraken/streams'
simplehttp(
url,
function(data)
local streams = parseData(self, source, destination, data)
local out = formatData(self, source, destination, streams)
for _,line in pairs(out) do
self:Msg('privmsg', destination, source, line)
end
end
)
end
local checkStreams = function()
for c,_ in pairs(ivar2.channels) do
local gamesKey = key..':'..c
local games = store[gamesKey] or {}
local alertsKey = gamesKey .. ':alerts'
local alerts = store[alertsKey] or {}
for name, game in pairs(games) do
local limit = 5
simplehttp(
'https://api.twitch.tv/kraken/search/streams?limit='
..tostring(limit)..
'&offset=0&query='
..util.urlEncode(game.name),
function(data)
local streams = parseData(ivar2, nil, c, data, limit)
for _, stream in pairs(streams) do
-- Use Created At to check for uniqueness
if alerts[stream.channel.name] ~= stream.created_at and
-- Check if we meet viewer limit
stream.viewers > game.limit then
alerts[stream.channel.name] = stream.created_at
store[alertsKey] = alerts
ivar2:Msg('privmsg',
game.channel,
ivar2.nick,
"[%s] [%s] %s %s",
util.bold(game.name),
util.bold(tostring(math.floor(stream.viewers/1000))..'k'),
'http://twitch.tv/'..stream.channel.display_name,
stream.channel.status
)
end
end
end
)
end
end
end
-- Start the stream alert poller
ivar2:Timer('twitch', 300, 300, checkStreams)
local regAlert = function(self, source, destination, limit, name)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
games[name] = {channel=destination, name=name, limit=tonumber(limit)}
store[gamesKey] = games
reply('Ok. Added twitch alert.')
checkStreams()
end
local listAlert = function(self, source, destination)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
local out = {}
for name, game in pairs(games) do
out[#out+1] = name
end
if #out > 0 then
say('Alerting following terms: %s', table.concat(out, ', '))
else
say('No alerting here.')
end
end
local delAlert = function(self, source, destination, name)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
games[name] = nil
store[gamesKey] = games
reply('Ok. Removed twitch alert.')
end
return {
PRIVMSG = {
['^%ptwitch$'] = allHandler,
['^%ptwitch (.*)$'] = gameHandler,
['^%ptwitchalert (%d+) (.*)$'] = regAlert,
['^%ptwitchalert list$'] = listAlert,
['^%ptwitchalert del (.*)$'] = delAlert,
},
}
|
-- Module to display, search and alert twitch.tv streams
-- vim: set noexpandtab:
local util = require'util'
local simplehttp = util.simplehttp
local json = util.json
local moduleName = 'twitch'
local key = moduleName
local store = ivar2.persist
local parseData = function(self, source, destination, data)
data = json.decode(data)
if data._total == 0 then
return {}
end
local streams = {}
for i=1, #data.streams do
local this = data.streams[i]
local lang = this.channel.broadcaster_language
--TODO configure filter languages ?
if lang and (lang == 'en' or lang == 'no') then
table.insert(streams, this)
end
end
-- sort streams wrt viewer count
table.sort(streams, function(a,b) return a.viewers>b.viewers end)
return streams
end
local formatData = function(self, source, destination, streams, limit)
limit = limit or 5
local i = 0
local out = {}
for _, stream in pairs(streams) do
local viewers = tostring(math.floor(stream.viewers/1000)) .. 'k'
if viewers == '0k' then
viewers = stream.viewers
end
local title = ''
if stream.channel and stream.channel.status then
title = ': '..stream.channel.status
end
out[#out+1] = string.format(
"[%s] http://twitch.tv/%s %s %s",
util.bold(viewers), stream.channel.display_name, stream.game, title
)
i=i+1
if i > limit then break end
end
return out
end
local gameHandler= function(self, source, destination, input, limit)
limit = limit or 5
-- 'http://api.twitch.tv/kraken/streams?limit=20&offset=0&game='..util.urlEncode(input)..'&on_site=1',
simplehttp(
'https://api.twitch.tv/kraken/search/streams?limit='..tostring(limit)..'&offset=0&query='..util.urlEncode(input),
function(data)
local streams = parseData(self, source, destination, data)
if #streams == 0 then
local out = 'No streams found'
self:Msg('privmsg', destination, source, out)
else
local out = formatData(self, source, destination, streams, limit)
for _,line in pairs(out) do
self:Msg('privmsg', destination, source, line)
end
end
end
)
end
local allHandler = function(self, source, destination)
local url = 'https://api.twitch.tv/kraken/streams'
simplehttp(
url,
function(data)
local streams = parseData(self, source, destination, data)
local out = formatData(self, source, destination, streams)
for _,line in pairs(out) do
self:Msg('privmsg', destination, source, line)
end
end
)
end
local checkStreams = function()
for c,_ in pairs(ivar2.channels) do
local gamesKey = key..':'..c
local games = store[gamesKey] or {}
local alertsKey = gamesKey .. ':alerts'
local alerts = store[alertsKey] or {}
for name, game in pairs(games) do
local limit = 5
simplehttp(
string.format(
'https://api.twitch.tv/kraken/search/streams?limit=%s&offset=0&query=%s',
tostring(limit),
util.urlEncode(game.name)
),
function(data)
local streams = parseData(ivar2, nil, c, data, limit)
for _, stream in pairs(streams) do
-- Use Created At to check for uniqueness
if alerts[stream.channel.name] ~= stream.created_at and
-- Check if we meet viewer limit
stream.viewers > game.limit then
alerts[stream.channel.name] = stream.created_at
store[alertsKey] = alerts
ivar2:Msg('privmsg',
game.channel,
ivar2.nick,
"[%s] [%s] %s %s",
util.bold(game.name),
util.bold(tostring(math.floor(stream.viewers/1000))..'k'),
'http://twitch.tv/'..stream.channel.display_name,
stream.channel.status
)
end
end
end
)
end
end
end
-- Start the stream alert poller
ivar2:Timer('twitch', 300, 300, checkStreams)
local regAlert = function(self, source, destination, limit, name)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
games[name] = {channel=destination, name=name, limit=tonumber(limit)}
store[gamesKey] = games
reply('Ok. Added twitch alert.')
checkStreams()
end
local listAlert = function(self, source, destination)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
local out = {}
for name, game in pairs(games) do
out[#out+1] = name
end
if #out > 0 then
say('Alerting following terms: %s', table.concat(out, ', '))
else
say('No alerting here.')
end
end
local delAlert = function(self, source, destination, name)
local gamesKey = key..':'..destination
local games = store[gamesKey] or {}
games[name] = nil
store[gamesKey] = games
reply('Ok. Removed twitch alert.')
end
return {
PRIVMSG = {
['^%ptwitch$'] = allHandler,
['^%ptwitch (.*)$'] = gameHandler,
['^%ptwitchalert (%d+) (.*)$'] = regAlert,
['^%ptwitchalert list$'] = listAlert,
['^%ptwitchalert del (.*)$'] = delAlert,
},
}
|
twitch: Fix mixed indent.
|
twitch: Fix mixed indent.
Former-commit-id: 55f475de1ef2b6d906fc41ae621025eab2b44ec3 [formerly 66d3e8e48566dab17863c23ffa69ec20ff9ec8dd]
Former-commit-id: cfaebbbc0bd1bd90d960bfd8cbe0d541dc5659f3
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
efd20db318cbc034e58eb55c0dfef4538f6be5ef
|
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')
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
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.get_urls = function(file, url, is_css, iri)
local urls = {}
if item_type == "image" then
if string.match(url, "twitpic%.com/"..item_value.."[^/]+/") then
html = read_file(file)
for videourl in string.gmatch(html, '<meta name="twitter:player:stream" value="(http[^"]+)"') do
table.insert(urls, { url=videourl })
end
for videosource in string.gmatch(html, '<source src="(http[^"]+)"') do
table.insert(urls, { url=videosource })
end
end
end
return urls
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"]
local wgetreason = reason
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
if item_type == "image" then
if string.match(url, "/%%5C%%22[^/]+") or
string.match(url, '/[^"]+"[^/]+') then
return false
elseif string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
if wgetreason == "ALREADY_ON_BLACKLIST" then
return false
else
return verdict
end
elseif string.match(url, "advertise%.twitpic%.com") 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 verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "user" 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 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 verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "tag" 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
-- 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 verdict
end
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 verdict
end
elseif string.match(url, item_value) then
return verdict
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"] .. ". \n")
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')
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
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.get_urls = function(file, url, is_css, iri)
local urls = {}
if item_type == "image" then
twitpicurl = "twitpic%.com/"..item_value
if string.match(url, twitpicurl) then
html = read_file(file)
for videourl in string.gmatch(html, '<meta name="twitter:player:stream" value="(http[^"]+)"') do
table.insert(urls, { url=videourl })
end
for videosource in string.gmatch(html, '<source src="(http[^"]+)"') do
table.insert(urls, { url=videosource })
end
end
end
return urls
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"]
local wgetreason = reason
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
if item_type == "image" then
if string.match(url, "/%%5C%%22") or
string.match(url, '/[^"]+"') then
return false
elseif string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
if wgetreason == "ALREADY_ON_BLACKLIST" then
return false
else
return verdict
end
elseif string.match(url, "advertise%.twitpic%.com") 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 verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "user" 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 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 verdict
end
elseif string.match(url, item_value) then
return verdict
else
return false
end
elseif item_type == "tag" 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
-- 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 verdict
end
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 verdict
end
elseif string.match(url, item_value) then
return verdict
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"] .. ". \n")
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
|
cc3d090e8e8447549d02c0720f7eedc3f23aa3b9
|
src/websocket/server_copas.lua
|
src/websocket/server_copas.lua
|
local socket = require'socket'
local copas = require'copas'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local sync = require'websocket.sync'
local tconcat = table.concat
local tinsert = table.insert
local clients = {}
local client = function(sock,protocol)
local copas = require'copas'
local self = {}
self.state = 'OPEN'
self.is_server = true
self.sock_send = function(self,...)
return copas.send(sock,...)
end
self.sock_receive = function(self,...)
return copas.receive(sock,...)
end
self.sock_close = function(self)
sock:shutdown()
sock:close()
end
self = sync.extend(self)
self.on_close = function(self)
clients[protocol][self] = nil
end
self.broadcast = function(_,...)
for client in pairs(clients[protocol]) do
client:send(...)
end
end
return self
end
local listen = function(opts)
local copas = require'copas'
assert(opts and (opts.protocols or opts.default))
local on_error = opts.on_error or function(s) print(s) end
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
if err then
error(err)
end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
-- true is the 'magic' index for the default handler
clients[true] = {}
copas.addserver(
listener,
function(sock)
local request = {}
repeat
-- no timeout used, so should either return with line or err
local line,err = copas.receive(sock,'*l')
if line then
request[#request+1] = line
else
sock:close()
if on_error then
on_error('invalid request')
end
return
end
until line == ''
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
copas.send(sock,protocol)
sock:close()
if on_error then
on_error('invalid request')
end
return
end
copas.send(sock,response)
local handler
local new_client
local protocol_index
if protocol and opts.protocols[protocol] then
protocol_index = protocol
handler = opts.protocols[protocol]
elseif opts.default then
-- true is the 'magic' index for the default handler
protocol_index = true
handler = opts.default
else
sock:close()
if on_error then
on_error('bad protocol')
end
return
end
new_client = client(sock,protocol_index)
clients[protocol_index][new_client] = true
handler(new_client)
-- this is a dirty trick for preventing
-- copas from automatically and prematurely closing
-- the socket
local q = {
insert = function()
end,
push = function()
end
}
while new_client.state ~= 'CLOSED' do
coroutine.yield(true,q)
end
end)
local self = {}
self.close = function(_,keep_clients)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
return self
end
return {
listen = listen
}
|
local socket = require'socket'
local copas = require'copas'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local sync = require'websocket.sync'
local tconcat = table.concat
local tinsert = table.insert
local clients = {}
local client = function(sock,protocol)
local copas = require'copas'
local self = {}
self.state = 'OPEN'
self.is_server = true
self.sock_send = function(self,...)
return copas.send(sock,...)
end
self.sock_receive = function(self,...)
return copas.receive(sock,...)
end
self.sock_close = function(self)
sock:shutdown()
sock:close()
end
self = sync.extend(self)
self.on_close = function(self)
clients[protocol][self] = nil
end
self.broadcast = function(self,...)
for client in pairs(clients[protocol]) do
if client ~= self then
client:send(...)
end
end
self:send(...)
end
return self
end
local listen = function(opts)
local copas = require'copas'
assert(opts and (opts.protocols or opts.default))
local on_error = opts.on_error or function(s) print(s) end
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
if err then
error(err)
end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
-- true is the 'magic' index for the default handler
clients[true] = {}
copas.addserver(
listener,
function(sock)
local request = {}
repeat
-- no timeout used, so should either return with line or err
local line,err = copas.receive(sock,'*l')
if line then
request[#request+1] = line
else
sock:close()
if on_error then
on_error('invalid request')
end
return
end
until line == ''
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
copas.send(sock,protocol)
sock:close()
if on_error then
on_error('invalid request')
end
return
end
copas.send(sock,response)
local handler
local new_client
local protocol_index
if protocol and opts.protocols[protocol] then
protocol_index = protocol
handler = opts.protocols[protocol]
elseif opts.default then
-- true is the 'magic' index for the default handler
protocol_index = true
handler = opts.default
else
sock:close()
if on_error then
on_error('bad protocol')
end
return
end
new_client = client(sock,protocol_index)
clients[protocol_index][new_client] = true
handler(new_client)
-- this is a dirty trick for preventing
-- copas from automatically and prematurely closing
-- the socket
while new_client.state ~= 'CLOSED' do
local dummy = {
send = function() end,
close = function() end
}
copas.send(dummy)
end
end)
local self = {}
self.close = function(_,keep_clients)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
return self
end
return {
listen = listen
}
|
fix some copas yield stuff
|
fix some copas yield stuff
|
Lua
|
mit
|
enginix/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets
|
a670a566abcaaf20d1a7277fe3348d237117420e
|
tests/config/test_links.lua
|
tests/config/test_links.lua
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
--
-- If fetching directories, the libdirs should be included in the result.
--
function suite.includesLibDirs_onDirectories()
libdirs { "../libs" }
local r = prepare("all", "directory")
test.isequal({ "../libs" }, r)
end
|
Added test for libdirs fix
|
Added test for libdirs fix
|
Lua
|
bsd-3-clause
|
warrenseine/premake,Lusito/premake,Lusito/premake,warrenseine/premake,Lusito/premake,annulen/premake,annulen/premake,warrenseine/premake,annulen/premake,Lusito/premake,annulen/premake
|
461d8c75ba17ea119d03cd63519aa429feb6d621
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd(umname, ent, udata)
local names, data = msgQueueNames[ent], msgQueueData[ent]
if not names then
names, data = {}, {}
msgQueueNames[ent] = names
msgQueueData[ent] = data
end
local i = #names+1
names[i] = umname
data[i] = udata
end
local function msgQueueProcess(ent)
local names, data = msgQueueNames[ent], msgQueueData[ent]
if names then
for i=1,#names do
local name = names[i]
if name == "scale" then
ent:SetScale(data[i])
elseif name == "clip" then
ent:UpdateClip(unpack(data[i]))
end
end
msgQueueNames[ent] = nil
msgQueueData[ent] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
msgQueueProcess(self)
end
function ENT:Draw()
-- Setup clipping
local l = #self.clips
if l > 0 then
render.EnableClipping(true)
for i=1,l do
local clip = self.clips[i]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld(norm) - self:GetPos()
origin = self:LocalToWorld(origin)
end
render.PushCustomClipPlane(norm, norm:Dot(origin))
end
end
end
render.SuppressEngineLighting(self.unlit)
self:DrawModel()
render.SuppressEngineLighting(false)
for i=1,#self.clips do render.PopCustomClipPlane() end
render.EnableClipping(false)
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function()
local holoent = ent or net.ReadEntity()
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd("clip", holoent, {
net.ReadUInt(16),
net.ReadBit() ~= 0,
Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()),
Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()),
net.ReadBit() ~= 0
})
else
holoent:UpdateClip(
net.ReadUInt(16),
net.ReadBit() ~= 0,
Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()),
Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()),
net.ReadBit() ~= 0
)
end
end)
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale(scale)
self.scale = scale
local m = Matrix()
m:Scale(scale)
self:EnableMatrix("RenderMultiply", m)
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds(propmax, propmin)
end
net.Receive("starfall_hologram_scale", function()
local holoent = ent or net.ReadEntity()
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd("scale", holoent, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()))
else
holoent:SetScale(Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()))
end
end)
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd ( umname, ent, udata )
local names, data = msgQueueNames[ ent ], msgQueueData[ ent ]
if not names then
names, data = {}, {}
msgQueueNames[ ent ] = names
msgQueueData[ ent ] = data
end
local i = #names + 1
names[ i ] = umname
data[ i ] = udata
end
local function msgQueueProcess ( ent )
local entid = ent:EntIndex()
local names, data = msgQueueNames[ entid ], msgQueueData[ entid ]
if names then
for i = 1 , #names do
local name = names[ i ]
if name == "scale" then
ent:SetScale( data[ i ] )
elseif name == "clip" then
ent:UpdateClip( unpack( data[ i ] ) )
end
end
msgQueueNames[ entid ] = nil
msgQueueData[ entid ] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
msgQueueProcess(self)
end
function ENT:Draw()
-- Setup clipping
local l = #self.clips
if l > 0 then
render.EnableClipping(true)
for i=1,l do
local clip = self.clips[i]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld(norm) - self:GetPos()
origin = self:LocalToWorld(origin)
end
render.PushCustomClipPlane(norm, norm:Dot(origin))
end
end
end
render.SuppressEngineLighting(self.unlit)
self:DrawModel()
render.SuppressEngineLighting(false)
for i=1,#self.clips do render.PopCustomClipPlane() end
render.EnableClipping(false)
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd( "clip", entid, {
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
} )
else
holoent:UpdateClip (
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
)
end
end )
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale ( scale )
self.scale = scale
local m = Matrix()
m:Scale( scale )
self:EnableMatrix( "RenderMultiply", m )
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds( propmax, propmin )
end
net.Receive("starfall_hologram_scale", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if not holoent:GetTable() then
-- Uninitialized
msgQueueAdd( "scale", entid, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()) )
else
holoent:SetScale( Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ) )
end
end )
|
Fix hologram net messages (setScale/setClip)
|
Fix hologram net messages (setScale/setClip)
Net messages can arrive before the entity is initialised.
While there was a queue to accomodate for that, the queue was indexed by
the entity. However, since all non-existant entities become
NULL-Entities, the queue was not working.
This changes the queue to be indexed by the entity index.
Fixes #20
|
Lua
|
bsd-3-clause
|
Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall
|
1b642a4e138f205c320fa0c9f20dbcd716d8f308
|
mods/BeardLib-Editor/Hooks/GameStateMachine.lua
|
mods/BeardLib-Editor/Hooks/GameStateMachine.lua
|
Hooks:PostHook(GameStateMachine, "init", "BeardLibEditorGameStateInit", function(self)
local editor
local editor_func
local ingame_waiting_for_players
local ingame_waiting_for_players_func
local ingame_waiting_for_respawn
local ingame_lobby
local ingame_lobby_func
for state in pairs(self._transitions) do
if state._name == "ingame_lobby_menu" then
ingame_lobby = state
ingame_lobby_func = callback(nil, state, "default_transition")
end
if state._name == "ingame_waiting_for_respawn" then
ingame_waiting_for_respawn = state
end
if state._name == "ingame_waiting_for_players" then
ingame_waiting_for_players = state
ingame_waiting_for_players_func = callback(nil, state, "default_transition")
end
if state._name == "editor" then
editor = state
editor_func = callback(nil, state, "default_transition")
end
end
if editor and ingame_waiting_for_players and ingame_waiting_for_respawn and ingame_lobby then
self:add_transition(editor, ingame_waiting_for_players, editor_func)
self:add_transition(editor, ingame_waiting_for_respawn, editor_func)
self:add_transition(editor, ingame_lobby, editor_func)
self:add_transition(ingame_waiting_for_players, editor, ingame_waiting_for_players_func)
self:add_transition(ingame_lobby, editor, ingame_lobby_func)
end
end)
|
Hooks:PostHook(GameStateMachine, "init", "BeardLibEditorGameStateInit", function(self)
local editor
local editor_func
local ingame_waiting_for_players
local ingame_waiting_for_players_func
local ingame_waiting_for_respawn
local ingame_lobby
local ingame_lobby_func
for name in pairs(self._transitions) do
state = self._states[name]
if name == "ingame_lobby_menu" then
ingame_lobby = state
ingame_lobby_func = callback(nil, state, "default_transition")
end
if name == "ingame_waiting_for_respawn" then
ingame_waiting_for_respawn = state
end
if name == "ingame_waiting_for_players" then
ingame_waiting_for_players = state
ingame_waiting_for_players_func = callback(nil, state, "default_transition")
end
if name == "editor" then
editor = state
editor_func = callback(nil, state, "default_transition")
end
end
if editor and ingame_waiting_for_players and ingame_waiting_for_respawn and ingame_lobby then
self:add_transition(editor, ingame_waiting_for_players, editor_func)
self:add_transition(editor, ingame_waiting_for_respawn, editor_func)
self:add_transition(editor, ingame_lobby, editor_func)
self:add_transition(ingame_waiting_for_players, editor, ingame_waiting_for_players_func)
self:add_transition(ingame_lobby, editor, ingame_lobby_func)
end
end)
|
Fixed #189
|
Fixed #189
|
Lua
|
mit
|
simon-wh/PAYDAY-2-BeardLib-Editor
|
57571d2183ddce17e8d03bc44718826a695d8ee0
|
lua/settings/init.lua
|
lua/settings/init.lua
|
local nvim = require'nvim'
local sys = require'sys'
-- local select_grep = require'tools'.helpers.select_grep
local set_grep = require'tools'.helpers.set_grep
local parent = sys.data
local plugins = nvim.plugins
local mkdir = require'tools'.files.mkdir
local is_dir = require'tools'.files.is_dir
local executable = require'tools'.files.executable
local function isempty(s)
return (s == nil or s == '') and true or false
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if dirname == 'undo' and not nvim.has('nvim-0.5') then
dirname = 'undo_vim'
end
if not is_dir(parent .. '/' .. dirname) then
mkdir(parent .. '/' .. dirname)
end
if not isempty(dir_setting) then
nvim.o[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 0
nvim.g.c_comment_strings = 1
nvim.g.c_curly_error = 1
nvim.g.c_no_if0 = 0
nvim.g.tex_flavor = 'latex'
nvim.g.terminal_scrollback_buffer_size = 100000
if nvim.g.started_by_firenvim ~= nil then
nvim.o.laststatus = 0
end
nvim.o.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
if sys.name == 'windows' then
nvim.o.shada = nvim.o.shada .. ",rA:,rB:,rC:/Temp/"
-- nvim.o.completeslash = 'slash'
else
nvim.o.shada = nvim.o.shada .. ",r/tmp/"
end
nvim.o.expandtab = true
nvim.o.shiftround = true
nvim.o.tabstop = 4
nvim.o.shiftwidth = 0
nvim.o.softtabstop = -1
nvim.o.scrollback = -1
nvim.o.updatetime = 100
nvim.o.sidescrolloff = 5
nvim.o.scrolloff = 1
nvim.o.undolevels = 10000
nvim.o.inccommand = 'split'
nvim.o.winaltkeys = 'no'
nvim.o.virtualedit = 'block'
nvim.o.formatoptions = 'tcqrolnj'
nvim.o.backupcopy = 'yes'
nvim.o.complete = '.,w,b,u,t'
nvim.o.completeopt = 'menu,menuone,noselect,noinsert'
nvim.o.tags = '.git/tags,./tags;,tags'
nvim.o.display = 'lastline,msgsep'
nvim.o.fileformats = 'unix,dos'
nvim.o.wildmenu = true
nvim.o.wildmode = 'full'
nvim.o.pumblend = 20
nvim.o.winblend = 10
nvim.o.showbreak = '↪\\'
nvim.o.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.o.cpoptions = 'aAceFs_B'
nvim.o.shortmess = nvim.o.shortmess..'ac'
nvim.o.lazyredraw = true
nvim.o.showmatch = true
nvim.o.splitright = true
nvim.o.splitbelow = true
nvim.o.backup = true
nvim.o.undofile = true
nvim.o.termguicolors = true
nvim.o.infercase = true
nvim.o.ignorecase = true
nvim.o.smartcase = false
nvim.o.smartindent = true
nvim.o.copyindent = true
nvim.o.expandtab = true
nvim.o.joinspaces = false
nvim.o.showmode = false
nvim.o.visualbell = true
nvim.o.shiftround = true
nvim.o.hidden = true
nvim.o.autowrite = true
nvim.o.autowriteall = true
nvim.o.fileencoding = 'utf-8'
nvim.o.pastetoggle = '<f3>'
if nvim.g.gonvim_running ~= nil then
nvim.o.showmode = false
nvim.o.ruler = false
else
nvim.o.titlestring = '%t (%f)'
nvim.o.title = true
end
-- Default should be internal,filler,closeoff
nvim.o.diffopt = nvim.o.diffopt .. ',vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience,hiddenoff'
if plugins['vim-airline'] == nil then
nvim.o.statusline = [[%< [%f]%=%-5.(%y%r%m%w%q%) %-14.(%l,%c%V%) %P ]]
end
set_grep(false, false)
-- Window options
-- Use set to modify global and window value
nvim.command('set breakindent')
nvim.command('set relativenumber')
nvim.command('set number')
nvim.command('set list')
nvim.command('set nowrap')
nvim.command('set nofoldenable')
nvim.command('set colorcolumn=80')
nvim.command('set foldmethod=syntax')
nvim.command('set numberwidth=1')
nvim.command('set foldlevel=99')
if nvim.has('nvim-0.5') then
nvim.command('set signcolumn=auto:2')
else
nvim.command('set signcolumn=auto')
end
-- Changes in nvim master
-- nvim.wo.foldcolumn = 'auto'
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.o.wildignore = table.concat(wildignores, ',')
nvim.o.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.o.mouse = 'a'
nvim.o.clipboard = 'unnamedplus,unnamed'
else
nvim.o.mouse = ''
end
if executable('nvr') then
nvim.env.nvr = 'nvr --servername '.. nvim.v.servername ..' --remote-silent'
nvim.env.tnvr = 'nvr --servername '.. nvim.v.servername ..' --remote-tab-silent'
nvim.env.vnvr = 'nvr --servername '.. nvim.v.servername ..' -cc vsplit --remote-silent'
nvim.env.snvr = 'nvr --servername '.. nvim.v.servername ..' -cc split --remote-silent'
end
if nvim.has('nvim-0.5') then
require'tools'.system.get_ssh_hosts()
end
pcall(require, 'host')
|
local nvim = require'nvim'
local sys = require'sys'
-- local select_grep = require'tools'.helpers.select_grep
local set_grep = require'tools'.helpers.set_grep
local parent = sys.data
local plugins = nvim.plugins
local mkdir = require'tools'.files.mkdir
local is_dir = require'tools'.files.is_dir
local executable = require'tools'.files.executable
local function isempty(s)
return (s == nil or s == '') and true or false
end
local dirpaths = {
backup = 'backupdir',
swap = 'directory',
undo = 'undodir',
cache = '',
sessions = '',
}
for dirname,dir_setting in pairs(dirpaths) do
if dirname == 'undo' and not nvim.has('nvim-0.5') then
dirname = 'undo_vim'
end
if not is_dir(parent .. '/' .. dirname) then
mkdir(parent .. '/' .. dirname)
end
if not isempty(dir_setting) then
nvim.o[dir_setting] = parent .. '/' .. dirname
end
end
nvim.g.lua_complete_omni = 1
nvim.g.c_syntax_for_h = 0
nvim.g.c_comment_strings = 1
nvim.g.c_curly_error = 1
nvim.g.c_no_if0 = 0
nvim.g.tex_flavor = 'latex'
nvim.g.terminal_scrollback_buffer_size = 100000
if nvim.g.started_by_firenvim ~= nil then
nvim.o.laststatus = 0
end
nvim.o.shada = "!,/1000,'1000,<1000,:1000,s10000,h"
if sys.name == 'windows' then
nvim.o.shada = nvim.o.shada .. ",rA:,rB:,rC:/Temp/"
-- nvim.o.completeslash = 'slash'
else
nvim.o.shada = nvim.o.shada .. ",r/tmp/"
end
if sys.name == 'windows' then
nvim.o.swapfile = false
nvim.bo.swapfile = false
nvim.o.backup = false
end
nvim.o.backupcopy = 'yes'
nvim.o.undofile = true
nvim.o.expandtab = true
nvim.o.shiftround = true
nvim.o.tabstop = 4
nvim.o.shiftwidth = 0
nvim.o.softtabstop = -1
nvim.o.scrollback = -1
nvim.o.updatetime = 100
nvim.o.sidescrolloff = 5
nvim.o.scrolloff = 1
nvim.o.undolevels = 10000
nvim.o.inccommand = 'split'
nvim.o.winaltkeys = 'no'
nvim.o.virtualedit = 'block'
nvim.o.formatoptions = 'tcqrolnj'
nvim.o.complete = '.,w,b,u,t'
nvim.o.completeopt = 'menu,menuone,noselect,noinsert'
nvim.o.tags = '.git/tags,./tags;,tags'
nvim.o.display = 'lastline,msgsep'
nvim.o.fileformats = 'unix,dos'
nvim.o.wildmenu = true
nvim.o.wildmode = 'full'
nvim.o.pumblend = 20
nvim.o.winblend = 10
nvim.o.showbreak = '↪\\'
nvim.o.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮'
nvim.o.cpoptions = 'aAceFs_B'
nvim.o.shortmess = nvim.o.shortmess..'ac'
nvim.o.lazyredraw = true
nvim.o.showmatch = true
nvim.o.splitright = true
nvim.o.splitbelow = true
nvim.o.termguicolors = true
nvim.o.infercase = true
nvim.o.ignorecase = true
nvim.o.smartcase = false
nvim.o.smartindent = true
nvim.o.copyindent = true
nvim.o.expandtab = true
nvim.o.joinspaces = false
nvim.o.showmode = false
nvim.o.visualbell = true
nvim.o.shiftround = true
nvim.o.hidden = true
nvim.o.autowrite = true
nvim.o.autowriteall = true
nvim.o.fileencoding = 'utf-8'
nvim.o.pastetoggle = '<f3>'
if nvim.g.gonvim_running ~= nil then
nvim.o.showmode = false
nvim.o.ruler = false
else
nvim.o.titlestring = '%t (%f)'
nvim.o.title = true
end
-- Default should be internal,filler,closeoff
nvim.o.diffopt = nvim.o.diffopt .. ',vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience,hiddenoff'
if plugins['vim-airline'] == nil then
nvim.o.statusline = [[%< [%f]%=%-5.(%y%r%m%w%q%) %-14.(%l,%c%V%) %P ]]
end
set_grep(false, false)
-- Window options
-- Use set to modify global and window value
nvim.command('set breakindent')
nvim.command('set relativenumber')
nvim.command('set number')
nvim.command('set list')
nvim.command('set nowrap')
nvim.command('set nofoldenable')
nvim.command('set colorcolumn=80')
nvim.command('set foldmethod=syntax')
nvim.command('set numberwidth=1')
nvim.command('set foldlevel=99')
if nvim.has('nvim-0.5') then
nvim.command('set signcolumn=auto:2')
else
nvim.command('set signcolumn=auto')
end
-- Changes in nvim master
-- nvim.wo.foldcolumn = 'auto'
local wildignores = {
'*.spl',
'*.aux',
'*.out',
'*.o',
'*.pyc',
'*.gz',
'*.pdf',
'*.sw',
'*.swp',
'*.swap',
'*.com',
'*.exe',
'*.so',
'*/cache/*',
'*/__pycache__/*',
}
local no_backup = {
'.git/*',
'.svn/*',
'.xml',
'*.log',
'*.bin',
'*.7z',
'*.dmg',
'*.gz',
'*.iso',
'*.jar',
'*.rar',
'*.tar',
'*.zip',
'TAGS',
'tags',
'GTAGS',
'COMMIT_EDITMSG',
}
nvim.o.wildignore = table.concat(wildignores, ',')
nvim.o.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',')
if nvim.env.SSH_CONNECTION == nil then
nvim.o.mouse = 'a'
nvim.o.clipboard = 'unnamedplus,unnamed'
else
nvim.o.mouse = ''
end
if executable('nvr') then
nvim.env.nvr = 'nvr --servername '.. nvim.v.servername ..' --remote-silent'
nvim.env.tnvr = 'nvr --servername '.. nvim.v.servername ..' --remote-tab-silent'
nvim.env.vnvr = 'nvr --servername '.. nvim.v.servername ..' -cc vsplit --remote-silent'
nvim.env.snvr = 'nvr --servername '.. nvim.v.servername ..' -cc split --remote-silent'
end
if nvim.has('nvim-0.5') then
require'tools'.system.get_ssh_hosts()
end
pcall(require, 'host')
|
fix: Turn off some write-to-disk options in windows
|
fix: Turn off some write-to-disk options in windows
Remove swapfile and permanent backupfile from windows options
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
5178d3021f7b54401228ac719bcee5d5faafff56
|
nyagos.d/catalog/subcomplete.lua
|
nyagos.d/catalog/subcomplete.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share.maincmds = {}
-- git
local githelp=io.popen("git help -a 2>nul","r")
if githelp then
local gitcmds={}
for line in githelp:lines() do
local word = string.match(line,"^ +(%S+)")
if nil ~= word then
gitcmds[ #gitcmds+1 ] = word
end
end
githelp:close()
if #gitcmds > 1 then
local maincmds = share.maincmds
maincmds["git"] = gitcmds
maincmds["git.exe"] = gitcmds
share.maincmds = maincmds
end
end
-- Subversion
local svnhelp=io.popen("svn help 2>nul","r")
if svnhelp then
local svncmds={}
for line in svnhelp:lines() do
local m=string.match(line,"^ +([a-z]+)")
if m then
svncmds[ #svncmds+1 ] = m
end
end
svnhelp:close()
if #svncmds > 1 then
local maincmds = share.maincmds
maincmds["svn"] = svncmds
maincmds["svn.exe"] = svncmds
share.maincmds = maincmds
end
end
-- Mercurial
local hghelp=nyagos.eval("hg debugcomplete 2>nul","r")
if string.len(hghelp) > 5 then
local hgcmds={}
for line in string.gmatch(hghelp,"[^\n]+") do
for word in string.gmatch(line,"[a-z]+") do
hgcmds[#hgcmds+1] = word
end
end
if #hgcmds > 1 then
local maincmds=share.maincmds
maincmds["hg"] = hgcmds
maincmds["hg.exe"] = hgcmds
share.maincmds = maincmds
end
end
-- Rclone
local rclonehelp=io.popen("rclone --help 2>nul","r")
if rclonehelp then
local rclonecmds={}
local startflag = false
local flagsfound=false
for line in rclonehelp:lines() do
if not flagsfound then
if string.match(line,"Available Commands:") then
startflag = true
end
if string.match(line,"Flags:") then
flagsfound = true
end
if startflag then
local m=string.match(line,"^%s+([a-z]+)")
if m then
rclonecmds[ #rclonecmds+1 ] = m
end
end
end
end
rclonehelp:close()
if #rclonecmds > 1 then
local maincmds=share.maincmds
maincmds["rclone"] = rclonecmds
maincmds["rclone.exe"] = rclonecmds
share.maincmds = maincmds
end
end
if next(share.maincmds) then
nyagos.completion_hook = function(c)
if c.pos <= 1 then
return nil
end
local cmdname = string.match(c.text,"^%S+")
if not cmdname then
return nil
end
--[[
2nd command completion like :git bisect go[od]
user define-able
local subcommands={"good", "bad"}
local maincmds=share.maincmds
maincmds["git bisect"] = subcommands
share.maincmds = maincmds
--]]
local cmd2nd = string.match(c.text,"^%S+%s+%S+")
if share.maincmds[cmd2nd] then
cmdname = cmd2nd
end
local subcmds = {}
local subcmdData = share.maincmds[cmdname]
if not subcmdData then
return nil
end
local subcmdType = type(subcmdData)
if "table" == subcmdType then
subcmds = subcmdData
elseif "function" == subcmdType then
subcmds = subcmdData()
end
for i=1,#subcmds do
table.insert(c.list,subcmds[i])
end
return c.list
end
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share.maincmds = {}
-- git
local githelp=io.popen("git help -a 2>nul","r")
if githelp then
local gitcmds={}
for line in githelp:lines() do
local word = string.match(line,"^ +(%S+)")
if nil ~= word then
gitcmds[ #gitcmds+1 ] = word
end
end
githelp:close()
if #gitcmds > 1 then
local maincmds = share.maincmds
maincmds["git"] = gitcmds
maincmds["git.exe"] = gitcmds
share.maincmds = maincmds
end
end
-- Subversion
local svnhelp=nyagos.eval("svn help 2>nul","r")
if string.len(svnhelp) > 5 then
local svncmds={}
for line in string.gmatch(svnhelp,"[^\n]+") do
local m=string.match(line,"^ +([a-z]+)")
if m then
svncmds[ #svncmds+1 ] = m
end
end
if #svncmds > 1 then
local maincmds = share.maincmds
maincmds["svn"] = svncmds
maincmds["svn.exe"] = svncmds
share.maincmds = maincmds
end
end
-- Mercurial
local hghelp=nyagos.eval("hg debugcomplete 2>nul","r")
if string.len(hghelp) > 5 then
local hgcmds={}
for line in string.gmatch(hghelp,"[^\n]+") do
for word in string.gmatch(line,"[a-z]+") do
hgcmds[#hgcmds+1] = word
end
end
if #hgcmds > 1 then
local maincmds=share.maincmds
maincmds["hg"] = hgcmds
maincmds["hg.exe"] = hgcmds
share.maincmds = maincmds
end
end
-- Rclone
local rclonehelp=io.popen("rclone --help 2>nul","r")
if rclonehelp then
local rclonecmds={}
local startflag = false
local flagsfound=false
for line in rclonehelp:lines() do
if not flagsfound then
if string.match(line,"Available Commands:") then
startflag = true
end
if string.match(line,"Flags:") then
flagsfound = true
end
if startflag then
local m=string.match(line,"^%s+([a-z]+)")
if m then
rclonecmds[ #rclonecmds+1 ] = m
end
end
end
end
rclonehelp:close()
if #rclonecmds > 1 then
local maincmds=share.maincmds
maincmds["rclone"] = rclonecmds
maincmds["rclone.exe"] = rclonecmds
share.maincmds = maincmds
end
end
if next(share.maincmds) then
nyagos.completion_hook = function(c)
if c.pos <= 1 then
return nil
end
local cmdname = string.match(c.text,"^%S+")
if not cmdname then
return nil
end
--[[
2nd command completion like :git bisect go[od]
user define-able
local subcommands={"good", "bad"}
local maincmds=share.maincmds
maincmds["git bisect"] = subcommands
share.maincmds = maincmds
--]]
local cmd2nd = string.match(c.text,"^%S+%s+%S+")
if share.maincmds[cmd2nd] then
cmdname = cmd2nd
end
local subcmds = {}
local subcmdData = share.maincmds[cmdname]
if not subcmdData then
return nil
end
local subcmdType = type(subcmdData)
if "table" == subcmdType then
subcmds = subcmdData
elseif "function" == subcmdType then
subcmds = subcmdData()
end
for i=1,#subcmds do
table.insert(c.list,subcmds[i])
end
return c.list
end
end
|
(#345) fix: subcomplete.lua: sub command completion for svn did notwork
|
(#345) fix: subcomplete.lua: sub command completion for svn did notwork
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos,nocd5/nyagos,zetamatta/nyagos
|
c26c3a166ea7bcd88abf69bf4808334c55693ae2
|
Modules/Debug/Draw.lua
|
Modules/Debug/Draw.lua
|
---
-- @module Draw
local Workspace = game:GetService("Workspace")
local lib = {}
lib._defaultColor = Color3.new(1, 0, 0)
function lib.SetColor(color)
lib._defaultColor = color
end
function lib.SetRandomColor()
lib.SetColor(Color3.fromHSV(math.random(), 0.5+0.5*math.random(), 1))
end
--- Draws a ray for debugging
-- @param ray The ray to draw
function lib.Ray(ray, color, parent, meshDiameter, diameter)
color = color or lib._defaultColor
parent = parent or Workspace.CurrentCamera
meshDiameter = meshDiameter or 0.2
diameter = diameter or 0.2
local rayCenter = ray.Origin + ray.Direction/2
local part = Instance.new("Part")
part.Anchored = true
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.CanCollide = false
part.CFrame = CFrame.new(rayCenter, ray.Origin + ray.Direction) * CFrame.Angles(math.pi/2, 0, 0)
part.Color = color
part.Name = "DebugRay"
part.Shape = Enum.PartType.Cylinder
part.Size = Vector3.new(1 * diameter, ray.Direction.magnitude, 1 * diameter)
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
local mesh = Instance.new("SpecialMesh")
mesh.Scale = Vector3.new(0, 1, 0) + Vector3.new(meshDiameter, 0, meshDiameter) / diameter
mesh.parent = part
part.parent = parent
return part
end
--- Draws a point for debugging
-- @param vector3 Point to draw
function lib.Point(vector3, color, parent, diameter)
assert(vector3)
color = color or lib._defaultColor
parent = parent or Workspace.CurrentCamera
diameter = diameter or 1
local part = Instance.new("Part")
part.Anchored = true
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.CanCollide = false
part.CFrame = CFrame.new(vector3)
part.Color = color
part.Name = "DebugPoint"
part.Shape = Enum.PartType.Ball
part.Size = Vector3.new(diameter, diameter, diameter)
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
local sphereHandle = Instance.new("SphereHandleAdornment")
sphereHandle.Archivable = false
sphereHandle.Radius = diameter/4
sphereHandle.Color3 = color
sphereHandle.AlwaysOnTop = true
sphereHandle.Adornee = part
sphereHandle.ZIndex = 1
sphereHandle.Parent = part
part.Parent = parent
return part
end
function lib.Box(cframe, size, color)
color = color or lib._defaultColor
cframe = typeof(cframe) == "Vector3" and CFrame.new(cframe) or cframe
local part = Instance.new("Part")
part.Color= color
part.Name = "DebugPart"
part.Anchored = true
part.CanCollide = false
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
part.Size = size
part.CFrame = cframe
part.Parent = Workspace.CurrentCamera
return part
end
return lib
|
--- Debug drawing library useful for debugging 3D abstractions
-- @module Draw
local Workspace = game:GetService("Workspace")
local lib = {}
lib._defaultColor = Color3.new(1, 0, 0)
--- Sets the lib's drawing color
-- @tparam {Color3} color The color to set
function lib.SetColor(color)
lib._defaultColor = color
end
--- Sets the draw library to use a random color
function lib.SetRandomColor()
lib.SetColor(Color3.fromHSV(math.random(), 0.5+0.5*math.random(), 1))
end
--- Draws a ray for debugging
-- @param ray The ray to draw
-- @tparam[opt] {color3} color The color to draw in
-- @tparam[opt] {Instance} parent
-- @tparam[opt] {number} diameter
-- @tparam[opt] {number} meshDiameter
function lib.Ray(ray, color, parent, meshDiameter, diameter)
color = color or lib._defaultColor
parent = parent or Workspace.CurrentCamera
meshDiameter = meshDiameter or 0.2
diameter = diameter or 0.2
local rayCenter = ray.Origin + ray.Direction/2
local part = Instance.new("Part")
part.Anchored = true
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.CanCollide = false
part.CFrame = CFrame.new(rayCenter, ray.Origin + ray.Direction) * CFrame.Angles(math.pi/2, 0, 0)
part.Color = color
part.Name = "DebugRay"
part.Shape = Enum.PartType.Cylinder
part.Size = Vector3.new(1 * diameter, ray.Direction.magnitude, 1 * diameter)
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
local mesh = Instance.new("SpecialMesh")
mesh.Scale = Vector3.new(0, 1, 0) + Vector3.new(meshDiameter, 0, meshDiameter) / diameter
mesh.Parent = part
part.Parent = parent
return part
end
--- Draws a point for debugging
-- @tparam {Vector3} vector3 Point to draw
-- @tparam[opt] {color3} color The color to draw in
-- @tparam[opt] {Instance} parent
-- @tparam[opt] {number} diameter
function lib.Point(vector3, color, parent, diameter)
assert(vector3)
color = color or lib._defaultColor
parent = parent or Workspace.CurrentCamera
diameter = diameter or 1
local part = Instance.new("Part")
part.Anchored = true
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.CanCollide = false
part.CFrame = CFrame.new(vector3)
part.Color = color
part.Name = "DebugPoint"
part.Shape = Enum.PartType.Ball
part.Size = Vector3.new(diameter, diameter, diameter)
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
local sphereHandle = Instance.new("SphereHandleAdornment")
sphereHandle.Archivable = false
sphereHandle.Radius = diameter/4
sphereHandle.Color3 = color
sphereHandle.AlwaysOnTop = true
sphereHandle.Adornee = part
sphereHandle.ZIndex = 1
sphereHandle.Parent = part
part.Parent = parent
return part
end
function lib.Box(cframe, size, color)
color = color or lib._defaultColor
cframe = typeof(cframe) == "Vector3" and CFrame.new(cframe) or cframe
local part = Instance.new("Part")
part.Color= color
part.Name = "DebugPart"
part.Anchored = true
part.CanCollide = false
part.Archivable = false
part.BottomSurface = Enum.SurfaceType.Smooth
part.TopSurface = Enum.SurfaceType.Smooth
part.Transparency = 0.5
part.Size = size
part.CFrame = cframe
part.Parent = Workspace.CurrentCamera
return part
end
return lib
|
Add documentation to draw, fix minor issues
|
Add documentation to draw, fix minor issues
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
c51d87183396295bf602ad68fa1290c00fcdbbd3
|
MY_Toolbox/src/MY_ArenaHelper.lua
|
MY_Toolbox/src/MY_ArenaHelper.lua
|
--------------------------------------------------------
-- This file is part of the JX3 Mingyi Plugin.
-- @link : https://jx3.derzh.com/
-- @desc : ԶлŶƵ
-- @author : @˫ @Ӱ
-- @modifier : Emil Zhai ([email protected])
-- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = 'MY_Toolbox'
local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = 'MY_Toolbox'
local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then
return
end
--------------------------------------------------------------------------
local O = X.CreateUserSettingsModule('MY_ArenaHelper', _L['General'], {
bRestoreAuthorityInfo = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
bAutoShowModel = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bAutoShowModelBattlefield = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
})
local D = {}
-- auto restore team authourity info in arena
do local l_tTeamInfo, l_bConfigEnd
X.RegisterEvent('ARENA_START', function() l_bConfigEnd = true end)
X.RegisterEvent('LOADING_ENDING', function() l_bConfigEnd = false end)
X.RegisterEvent('PARTY_DELETE_MEMBER', function() l_bConfigEnd = false end)
local function RestoreTeam()
local me, team = GetClientPlayer(), GetClientTeam()
if not l_tTeamInfo
or not O.bRestoreAuthorityInfo
or not X.IsLeader()
or not me.IsInParty() or not X.IsInArena() then
return
end
X.SetTeamInfo(l_tTeamInfo)
end
X.RegisterEvent('PARTY_ADD_MEMBER', RestoreTeam)
local function SaveTeam()
local me, team = GetClientPlayer(), GetClientTeam()
if not me.IsInParty() or not X.IsInArena() or l_bConfigEnd then
return
end
l_tTeamInfo = X.GetTeamInfo()
end
X.RegisterEvent({'TEAM_AUTHORITY_CHANGED', 'PARTY_SET_FORMATION_LEADER', 'TEAM_CHANGE_MEMBER_GROUP'}, SaveTeam)
end
-- JJCԶʾ
do local l_bHideNpc, l_bHidePlayer, l_bShowParty, l_lock
X.RegisterEvent('ON_REPRESENT_CMD', function()
if l_lock then
return
end
if arg0 == 'show npc' or arg0 == 'hide npc' then
l_bHideNpc = arg0 == 'hide npc'
elseif arg0 == 'show player' or arg0 == 'hide player' then
l_bHidePlayer = arg0 == 'hide player'
elseif arg0 == 'show or hide party player 0' or 'show or hide party player 1' then
l_bShowParty = arg0 == 'show or hide party player 1'
end
end)
X.RegisterEvent('LOADING_END', function()
if not O.bAutoShowModel and not O.bAutoShowModelBattlefield then
return
end
if (X.IsInArena() and O.bAutoShowModel) or (X.IsInBattleField() and O.bAutoShowModelBattlefield) then
l_lock = true
rlcmd('show npc')
rlcmd('show player')
rlcmd('show or hide party player 0')
else
l_lock = true
if l_bHideNpc then
rlcmd('hide npc')
else
rlcmd('show npc')
end
if l_bHidePlayer then
rlcmd('hide player')
else
rlcmd('show player')
end
if l_bShowParty then
rlcmd('show or hide party player 1')
else
rlcmd('show or hide party player 0')
end
l_lock = false
end
end)
end
function D.OnPanelActivePartial(ui, nPaddingX, nPaddingY, nW, nH, nX, nY, nLH)
-- ԶָϢ
ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto restore team info in arena'],
checked = MY_ArenaHelper.bRestoreAuthorityInfo,
oncheck = function(bChecked)
MY_ArenaHelper.bRestoreAuthorityInfo = bChecked
end,
})
nY = nY + nLH
-- սԶȡ
nX = nX + ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto cancel hide player in arena'],
checked = MY_ArenaHelper.bAutoShowModel,
oncheck = function(bChecked)
MY_ArenaHelper.bAutoShowModel = bChecked
end,
}):Width() + 5
-- սԶȡ
nX = nX + ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto cancel hide player in battlefield'],
checked = MY_ArenaHelper.bAutoShowModelBattlefield,
oncheck = function(bChecked)
MY_ArenaHelper.bAutoShowModelBattlefield = bChecked
end,
}):Width() + 5
return nX, nY
end
-- Global exports
do
local settings = {
name = 'MY_ArenaHelper',
exports = {
{
fields = {
'OnPanelActivePartial',
},
root = D,
},
{
fields = {
'bRestoreAuthorityInfo',
'bAutoShowModel',
'bAutoShowModelBattlefield',
},
root = O,
},
},
imports = {
{
fields = {
'bRestoreAuthorityInfo',
'bAutoShowModel',
'bAutoShowModelBattlefield',
},
root = O,
},
},
}
MY_ArenaHelper = X.CreateModule(settings)
end
|
--------------------------------------------------------
-- This file is part of the JX3 Mingyi Plugin.
-- @link : https://jx3.derzh.com/
-- @desc : ԶлŶƵ
-- @author : @˫ @Ӱ
-- @modifier : Emil Zhai ([email protected])
-- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = 'MY_Toolbox'
local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = 'MY_Toolbox'
local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then
return
end
--------------------------------------------------------------------------
local O = X.CreateUserSettingsModule('MY_ArenaHelper', _L['General'], {
bRestoreAuthorityInfo = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
bAutoShowModel = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
bAutoShowModelBattlefield = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Toolbox'],
xSchema = X.Schema.Boolean,
xDefaultValue = false,
},
})
local D = {}
-- auto restore team authourity info in arena
do local l_tTeamInfo, l_bConfigEnd
X.RegisterEvent('ARENA_START', function() l_bConfigEnd = true end)
X.RegisterEvent('LOADING_ENDING', function() l_bConfigEnd = false end)
X.RegisterEvent('PARTY_DELETE_MEMBER', function() l_bConfigEnd = false end)
local function RestoreTeam()
local me, team = GetClientPlayer(), GetClientTeam()
if not l_tTeamInfo
or not O.bRestoreAuthorityInfo
or not X.IsLeader()
or not me.IsInParty() or not X.IsInArena() then
return
end
X.SetTeamInfo(l_tTeamInfo)
end
X.RegisterEvent('PARTY_ADD_MEMBER', RestoreTeam)
local function SaveTeam()
local me, team = GetClientPlayer(), GetClientTeam()
if not me.IsInParty() or not X.IsInArena() or l_bConfigEnd then
return
end
l_tTeamInfo = X.GetTeamInfo()
end
X.RegisterEvent({'TEAM_AUTHORITY_CHANGED', 'PARTY_SET_FORMATION_LEADER', 'TEAM_CHANGE_MEMBER_GROUP'}, SaveTeam)
end
-- JJCԶʾ
do local l_bHideNpc, l_bHidePlayer, l_bShowParty, l_lock
X.RegisterEvent('ON_REPRESENT_CMD', function()
if l_lock then
return
end
if arg0 == 'show npc' or arg0 == 'hide npc' then
l_bHideNpc = arg0 == 'hide npc'
elseif arg0 == 'show player' or arg0 == 'hide player' then
l_bHidePlayer = arg0 == 'hide player'
elseif arg0 == 'show or hide party player 0' or 'show or hide party player 1' then
l_bShowParty = arg0 == 'show or hide party player 1'
end
end)
X.RegisterEvent('LOADING_END', function()
if not O.bAutoShowModel and not O.bAutoShowModelBattlefield then
return
end
if (X.IsInArena() and O.bAutoShowModel) or (X.IsInBattleField() and O.bAutoShowModelBattlefield) then
l_lock = true
rlcmd('show npc')
rlcmd('show player')
rlcmd('show or hide party player 0')
else
l_lock = true
if l_bHideNpc then
rlcmd('hide npc')
else
rlcmd('show npc')
end
if l_bHidePlayer then
rlcmd('hide player')
else
rlcmd('show player')
end
if l_bShowParty then
rlcmd('show or hide party player 1')
else
rlcmd('show or hide party player 0')
end
l_lock = false
end
end)
end
function D.OnPanelActivePartial(ui, nPaddingX, nPaddingY, nW, nH, nX, nY, nLH)
if GLOBAL.GAME_BRANCH ~= 'classic' then
-- ԶָϢ
ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto restore team info in arena'],
checked = MY_ArenaHelper.bRestoreAuthorityInfo,
oncheck = function(bChecked)
MY_ArenaHelper.bRestoreAuthorityInfo = bChecked
end,
})
nY = nY + nLH
-- սԶȡ
nX = nX + ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto cancel hide player in arena'],
checked = MY_ArenaHelper.bAutoShowModel,
oncheck = function(bChecked)
MY_ArenaHelper.bAutoShowModel = bChecked
end,
}):Width() + 5
end
-- սԶȡ
nX = nX + ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Auto cancel hide player in battlefield'],
checked = MY_ArenaHelper.bAutoShowModelBattlefield,
oncheck = function(bChecked)
MY_ArenaHelper.bAutoShowModelBattlefield = bChecked
end,
}):Width() + 5
return nX, nY
end
-- Global exports
do
local settings = {
name = 'MY_ArenaHelper',
exports = {
{
fields = {
'OnPanelActivePartial',
},
root = D,
},
{
fields = {
'bRestoreAuthorityInfo',
'bAutoShowModel',
'bAutoShowModelBattlefield',
},
root = O,
},
},
imports = {
{
fields = {
'bRestoreAuthorityInfo',
'bAutoShowModel',
'bAutoShowModelBattlefield',
},
root = O,
},
},
}
MY_ArenaHelper = X.CreateModule(settings)
end
|
fix: 修复常用工具名剑大会助手屏蔽问题
|
fix: 修复常用工具名剑大会助手屏蔽问题
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
4840d5eed72e0fd840a53003ba3352038ad77a36
|
Peripherals/Audio/ctunethread.lua
|
Peripherals/Audio/ctunethread.lua
|
--Chiptune Thread
local chIn = ...
require("love.audio")
require("love.sound")
require("love.timer")
local QSource = require("Peripherals.Audio.QueueableSource")
local qs = QSource:new()
local rate = 44100
local buffer_size = rate/4
local wave, freq, amp
local waves = {}
--Sin
waves[0] = function(samples)
local r = 0
return function()
r = r + math.pi/(samples/2)
return math.sin(r)*amp
end
end
--Square
waves[1] = function(samples)
local c = 0
local flag = false
return function()
c = (c+1)%(samples/2)
if c == 0 then flag = not flag end
return (flag and amp or -amp)
end
end
--Sawtooth
waves[2] = function(samples)
local c = 0
local inc = 2/samples
return function()
c = (c+inc)%2 -1
return c
end
end
waves[3] = function(samples)
local c = samples/2
local v = math.random()
local flag = flag
return function()
--[[c = c -1
if c == 0 then
c = samples/2
flag = not flag
v = math.random()*2
if flag then v = -v end
end
return v*amp
]]
return math.random()*2-1
end
end
local function pullParams()
return chIn:pop()
end
while true do
for params in pullParams do
if type(params) == "string" and params == "stop" then
return
else
local ofreq = freq
wave, freq, amp = unpack(params)
if ofreq then
--error(ofreq.." -> "..freq)
end
--error(tostring(wave).."_"..tostring(freq).."_"..tostring(amp))
--amp = amp or 1
qs:clear()
qs = QSource:new()
chIn:clear()
end
end
--Generate audio.
if wave then
qs:step()
if qs:getFreeBufferCount() > 0 then
local sd = love.sound.newSoundData(buffer_size, rate, 16, 1)
local gen = waves[wave](rate/freq)
for i=0,buffer_size-1 do
sd:setSample(i,gen())
end
qs:queue(sd)
qs:play()
end
end
end
|
--Chiptune Thread
local chIn = ...
require("love.audio")
require("love.sound")
require("love.timer")
local QSource = require("Peripherals.Audio.QueueableSource")
local qs = QSource:new()
local rate = 44100
local buffer_size = rate/4
local sleeptime = 0.9/(rate/buffer_size)
local wave, freq, amp
local waves = {}
--Sin
waves[0] = function(samples)
local r = 0
return function()
r = r + math.pi/(samples/2)
return math.sin(r)*amp
end
end
--Square
waves[1] = function(samples)
local c = 0
local flag = false
return function()
c = (c+1)%(samples/2)
if c == 0 then flag = not flag end
return (flag and amp or -amp)
end
end
--Sawtooth
waves[2] = function(samples)
local c = 0
local inc = 2/samples
return function()
c = (c+inc)%2 -1
return c
end
end
waves[3] = function(samples)
local c = samples/2
local v = math.random()
local flag = flag
return function()
--[[c = c -1
if c == 0 then
c = samples/2
flag = not flag
v = math.random()*2
if flag then v = -v end
end
return v*amp
]]
return math.random()*2-1
end
end
local function pullParams()
if wave then
return chIn:pop()
else
return chIn:demand()
end
end
while true do
for params in pullParams do
if type(params) == "string" and params == "stop" then
return
else
local ofreq = freq
wave, freq, amp = unpack(params)
if ofreq then
--error(ofreq.." -> "..freq)
end
--error(tostring(wave).."_"..tostring(freq).."_"..tostring(amp))
--amp = amp or 1
qs:clear()
qs = QSource:new()
chIn:clear()
end
end
--Generate audio.
if wave then
qs:step()
if qs:getFreeBufferCount() > 0 then
local sd = love.sound.newSoundData(buffer_size, rate, 16, 1)
local gen = waves[wave](rate/freq)
for i=0,buffer_size-1 do
sd:setSample(i,gen())
end
qs:queue(sd)
qs:play()
end
end
love.timer.sleep(sleeptime)
end
|
Bugfix Real CPU being completely used by chiptune thread
|
Bugfix Real CPU being completely used by chiptune thread
Former-commit-id: 5c6f102953092d02044e0dc010235cc4672095a5
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7ffecf756cd9914c2fedc9c42d3f79d3afbd1275
|
Quadtastic/tableplus.lua
|
Quadtastic/tableplus.lua
|
local table = table
-- Returns table[key][...]
-- That is, get(t, k1, k2, k3) is another way to write t[k1][k2][k3]
-- but there is no built-in way in Lua to do this in an automated way
function table.get(tab, key, ...)
if tab == nil then return nil
elseif select("#", ...) == 0 then
return tab[key]
else
-- apply recursively
return table.get(tab[key], ...)
end
end
-- Sets table[key][...] to value
-- That is, _set(t, v, k1, k2, k3) is another way to write t[k1][k2][k3] = v
-- but there is no built-in way in Lua to do this in an automated way
function table.set(tab, value, key, ...)
if value == nil then return
elseif select("#", ...) == 0 then
tab[key] = value
else
-- apply recursively
table.set(tab[key], value, ...)
end
end
-- Tries to find the list of keys that point to a specific value.
-- Performs a depth-first-search through the given table.
-- Therefore matching items that are nested deeper in the table might be
-- returned even though matching items on higher levels exist.
function table.find_key(tab, value)
for k,v in pairs(tab) do
if v == value then return k
elseif type(v) == "table" then -- search recursively
-- Return a list of keys
local result = {table.find_key(v, value)}
if #result > 0 then return k, unpack(result) end
end
end
return nil
end
function table.keys(tab)
local keys = {}
for k, _ in pairs(tab) do
table.insert(keys, k)
end
return keys
end
function table.values(tab)
local values = {}
for _, v in pairs(tab) do
table.insert(values, v)
end
return values
end
return table
|
local table = table
-- Returns table[key][...]
-- That is, get(t, k1, k2, k3) is another way to write t[k1][k2][k3]
-- but there is no built-in way in Lua to do this in an automated way
function table.get(tab, key, ...)
if tab == nil then return nil
elseif select("#", ...) == 0 then
return tab[key]
else
-- apply recursively
return table.get(tab[key], ...)
end
end
-- Sets table[key][...] to value
-- That is, _set(t, v, k1, k2, k3) is another way to write t[k1][k2][k3] = v
-- but there is no built-in way in Lua to do this in an automated way
function table.set(tab, value, key, ...)
if select("#", ...) == 0 then
tab[key] = value
else
-- apply recursively
table.set(tab[key], value, ...)
end
end
-- Tries to find the list of keys that point to a specific value.
-- Performs a depth-first-search through the given table.
-- Therefore matching items that are nested deeper in the table might be
-- returned even though matching items on higher levels exist.
function table.find_key(tab, value)
for k,v in pairs(tab) do
if v == value then return k
elseif type(v) == "table" then -- search recursively
-- Return a list of keys
local result = {table.find_key(v, value)}
if #result > 0 then return k, unpack(result) end
end
end
return nil
end
function table.keys(tab)
local keys = {}
for k, _ in pairs(tab) do
table.insert(keys, k)
end
return keys
end
function table.values(tab)
local values = {}
for _, v in pairs(tab) do
table.insert(values, v)
end
return values
end
return table
|
Fix set method in tableplus
|
Fix set method in tableplus
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
b7aa5d19be520b3886d235de32d43520f6d14ea2
|
announce.lua
|
announce.lua
|
local mod = EPGP:NewModule("announce")
local Debug = LibStub("LibDebug-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
function mod:AnnounceTo(medium, fmt, ...)
if not medium then return end
local channel = self.db.profile.channel or 0
-- Override raid and party if we are not grouped
if medium == "RAID" and not UnitInRaid("player") then
medium = "GUILD"
elseif medium == "PARTY" and not UnitInRaid("player") then
medium = "GUILD"
end
local msg = string.format(fmt, ...)
local str = "EPGP:"
for _,s in pairs({strsplit(" ", msg)}) do
if #str + #s >= 250 then
if ChatThrottleLib then
ChatThrottleLib:SendChatMessage(
"NORMAL", "EPGP", str, medium, nil, GetChannelName(channel))
else
SendChatMessage(str, medium, nil, GetChannelName(channel))
end
str = "EPGP:"
end
str = str .. " " .. s
end
SendChatMessage(str, medium, nil, GetChannelName(channel))
end
function mod:Announce(fmt, ...)
local medium = self.db.profile.medium
return mod:AnnounceTo(medium, fmt, ...)
end
function mod:EPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name)
end
function mod:GPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name)
end
function mod:BankedItem(event_name, name, reason, amount, mass)
mod:Announce(L["%s to %s"], reason, name)
end
local function MakeCommaSeparated(t)
local first = true
local awarded = ""
for name in pairs(t) do
if first then
awarded = name
first = false
else
awarded = awarded..", "..name
end
end
return awarded
end
function mod:MassEPAward(event_name, names, reason, amount,
extras_names, extras_reason, extras_amount)
local normal = MakeCommaSeparated(names)
local extras = MakeCommaSeparated(extras_names)
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal)
mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras)
end
function mod:Decay(event_name, decay_p)
mod:Announce(L["Decay of EP/GP by %d%%"], decay_p)
end
function mod:StartRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:ResumeRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:StopRecurringAward(event_name)
mod:Announce(L["Stop recurring award"])
end
function mod:EPGPReset(event_name)
mod:Announce(L["EP/GP are reset"])
end
mod.dbDefaults = {
profile = {
enabled = true,
medium = "GUILD",
events = {
['*'] = true,
},
}
}
mod.optionsName = L["Announce"]
mod.optionsDesc = L["Announcement of EPGP actions"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Announces EPGP actions to the specified medium."],
},
medium = {
order = 10,
type = "select",
name = L["Announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["OFFICER"] = CHAT_MSG_OFFICER,
["RAID"] = CHAT_MSG_RAID,
["PARTY"] = CHAT_MSG_PARTY,
["CHANNEL"] = CUSTOM,
},
},
channel = {
order = 11,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end,
},
events = {
order = 12,
type = "multiselect",
name = L["Announce when:"],
values = {
EPAward = L["A member is awarded EP"],
MassEPAward = L["Guild or Raid are awarded EP"],
GPAward = L["A member is credited GP"],
BankedItem = L["An item was disenchanted or deposited into the guild bank"],
Decay = L["EPGP decay"],
StartRecurringAward = L["Recurring awards start"],
StopRecurringAward = L["Recurring awards stop"],
ResumeRecurringAward = L["Recurring awards resume"],
EPGPReset = L["EPGP reset"],
},
width = "full",
get = "GetEvent",
set = "SetEvent",
},
}
function mod:GetEvent(i, e)
return self.db.profile.events[e]
end
function mod:SetEvent(i, e, v)
if v then
Debug("Enabling announce of: %s", e)
EPGP.RegisterCallback(self, e)
else
Debug("Disabling announce of: %s", e)
EPGP.UnregisterCallback(self, e)
end
self.db.profile.events[e] = v
end
function mod:OnEnable()
for e, _ in pairs(mod.optionsArgs.events.values) do
if self.db.profile.events[e] then
Debug("Enabling announce of: %s (startup)", e)
EPGP.RegisterCallback(self, e)
end
end
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
local mod = EPGP:NewModule("announce")
local Debug = LibStub("LibDebug-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
function mod:AnnounceTo(medium, fmt, ...)
if not medium then return end
local channel = self.db.profile.channel or 0
-- Override raid and party if we are not grouped
if medium == "RAID" and not UnitInRaid("player") then
medium = "GUILD"
elseif medium == "PARTY" and not UnitInRaid("player") then
medium = "GUILD"
end
local msg = string.format(fmt, ...)
local str = "EPGP:"
for _,s in pairs({strsplit(" ", msg)}) do
if #str + #s >= 250 then
if ChatThrottleLib then
ChatThrottleLib:SendChatMessage(
"NORMAL", "EPGP", str, medium, nil, GetChannelName(channel))
else
SendChatMessage(str, medium, nil, GetChannelName(channel))
end
str = "EPGP:"
end
str = str .. " " .. s
end
SendChatMessage(str, medium, nil, GetChannelName(channel))
end
function mod:Announce(fmt, ...)
local medium = self.db.profile.medium
return mod:AnnounceTo(medium, fmt, ...)
end
function mod:EPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name)
end
function mod:GPAward(event_name, name, reason, amount, mass)
if mass then return end
mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name)
end
function mod:BankedItem(event_name, name, reason, amount, mass)
mod:Announce(L["%s to %s"], reason, name)
end
local function MakeCommaSeparated(t)
local first = true
local awarded = ""
for name in pairs(t) do
if first then
awarded = name
first = false
else
awarded = awarded..", "..name
end
end
return awarded
end
function mod:MassEPAward(event_name, names, reason, amount,
extras_names, extras_reason, extras_amount)
local normal = MakeCommaSeparated(names)
mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal)
if extras_names then
local extras = MakeCommaSeparated(extras_names)
mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras)
end
end
function mod:Decay(event_name, decay_p)
mod:Announce(L["Decay of EP/GP by %d%%"], decay_p)
end
function mod:StartRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:ResumeRecurringAward(event_name, reason, amount, mins)
local fmt, val = SecondsToTimeAbbrev(mins * 60)
mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val))
end
function mod:StopRecurringAward(event_name)
mod:Announce(L["Stop recurring award"])
end
function mod:EPGPReset(event_name)
mod:Announce(L["EP/GP are reset"])
end
mod.dbDefaults = {
profile = {
enabled = true,
medium = "GUILD",
events = {
['*'] = true,
},
}
}
mod.optionsName = L["Announce"]
mod.optionsDesc = L["Announcement of EPGP actions"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Announces EPGP actions to the specified medium."],
},
medium = {
order = 10,
type = "select",
name = L["Announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["OFFICER"] = CHAT_MSG_OFFICER,
["RAID"] = CHAT_MSG_RAID,
["PARTY"] = CHAT_MSG_PARTY,
["CHANNEL"] = CUSTOM,
},
},
channel = {
order = 11,
type = "input",
name = L["Custom announce channel name"],
desc = L["Sets the custom announce channel name used to announce EPGP actions."],
disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end,
},
events = {
order = 12,
type = "multiselect",
name = L["Announce when:"],
values = {
EPAward = L["A member is awarded EP"],
MassEPAward = L["Guild or Raid are awarded EP"],
GPAward = L["A member is credited GP"],
BankedItem = L["An item was disenchanted or deposited into the guild bank"],
Decay = L["EPGP decay"],
StartRecurringAward = L["Recurring awards start"],
StopRecurringAward = L["Recurring awards stop"],
ResumeRecurringAward = L["Recurring awards resume"],
EPGPReset = L["EPGP reset"],
},
width = "full",
get = "GetEvent",
set = "SetEvent",
},
}
function mod:GetEvent(i, e)
return self.db.profile.events[e]
end
function mod:SetEvent(i, e, v)
if v then
Debug("Enabling announce of: %s", e)
EPGP.RegisterCallback(self, e)
else
Debug("Disabling announce of: %s", e)
EPGP.UnregisterCallback(self, e)
end
self.db.profile.events[e] = v
end
function mod:OnEnable()
for e, _ in pairs(mod.optionsArgs.events.values) do
if self.db.profile.events[e] then
Debug("Enabling announce of: %s (startup)", e)
EPGP.RegisterCallback(self, e)
end
end
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
Check that we actually have a list of extras before we attempt to announce them. This fixes issue 462.
|
Check that we actually have a list of extras before we attempt to announce them. This fixes issue 462.
|
Lua
|
bsd-3-clause
|
protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,hayword/tfatf_epgp
|
9f9212630b33e9b5d641cd83257ad234d867232d
|
configdir/awesome/widgets/temp.lua
|
configdir/awesome/widgets/temp.lua
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local TempWidget = BaseWidget.derive()
function TempWidget:create(args)
args = args or {}
args.critical = args.critical or 80
args.critcolor = args.critcolor or "#FF0000"
args.settings = function()
local t = coretemp_now
if t >= args.critical then
widget:set_markup(string.format('<span color="%s">%s°C</span>',
args.critcolor, coretemp_now))
else
widget:set_markup(t .. "°C")
end
end
self.lainwidget = lain.widget.temp(args)
local box = self:init(self.lainwidget.widget, args.icon or icons.temp)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run("psensor") end)
))
end
return TempWidget
|
local awful = require("awful")
local utils = require("utils")
local lain = require("lain")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local TempWidget = BaseWidget.derive()
function TempWidget:create(args)
args = args or {}
args.critical = args.critical or 80
args.critcolor = args.critcolor or "#FF0000"
args.settings = function()
if not t then
return
end
local t = coretemp_now
if t >= args.critical then
widget:set_markup(string.format('<span color="%s">%s°C</span>',
args.critcolor, coretemp_now))
else
widget:set_markup(t .. "°C")
end
end
self.lainwidget = lain.widget.temp(args)
local box = self:init(self.lainwidget.widget, args.icon or icons.temp)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run("psensor") end)
))
end
return TempWidget
|
Fix possible crash in temperature widget
|
Fix possible crash in temperature widget
|
Lua
|
mit
|
mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles
|
0350dac73470b157902887edbef241a06b5ca4dd
|
item/cauldron.lua
|
item/cauldron.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.cauldron' WHERE itm_id IN (1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018);
local common = require("base.common")
local M = {}
local cauldronContents
function M.UseItem(User, SourceItem)
if (User:getQuestProgress(539) == 1) and SourceItem:getData("ratmanCauldron") ~= "" then--OK, the player does the quest 1
cauldronContents(User, SourceItem)
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(594, 172, -3) then --OK, the player does the quest 2 yellow
User:inform(
"Irgendwie schaffst du es, eine Flasche mit dem gelben Trank von Kaefity zu klauen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the yellow potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 1)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(594, 172, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(596, 173, -3) then --OK, the player does the quest 2 orange
User:inform(
"Du siehst verdutzt zu, wie sich die Flasche in deinen Hnden auflst. Diesen Trank wirst du wohl nicht abfllen knnen. Du solltest es woanders versuchen.",
"You look on in amazement as the bottle dissolves in your hands. There will be no obtaining this potion you should try elsewhere.")
world:gfx(52, User.pos) -- swirly
world:makeSound(13, User.pos)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(596, 173, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(598, 175, -3) then --OK, the player does the quest 2 blue
User:inform(
"Als der Inhalt des Kessels deine Flasche berhrt, fngt der Trank an, Blasen zu werfen und explodiert. Glasscherben fliegen durch die Gegend und verletzen dich.",
"When the contents of the cauldron hit your bottle the potion bubbles then causes an explosion. Glass shards fly causing you harm.")
world:gfx(44, User.pos) -- explosion gfx
world:makeSound(5, User.pos) --a loud boom
User:increaseAttrib("hitpoints", -1000) -- player loses health
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(598, 175, -3) then -- player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(598, 177, -3) then --OK, the player does the quest 2 dark green
User:inform(
"Irgendwie schaffst du es, eine Flasche des dunkelgrnen Tranks von Kaefity zu stehlen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the dark green potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 3)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(598, 177, -3) then -- player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(597, 180, -3) then --OK, the player does the quest 2 pink
User:inform(
"Irgendwie schaffst du es, eine Flasche des rosanen Tranks von Kaefity zu klauen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the pink potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 1)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(597, 180, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
end
function cauldronContents(User, cauldronItem)
-- skip if already tripped in the last 5 minutes
local serverTime = world:getTime("unix")
local trippingTime = cauldronItem:getData("tripping_time")
if (trippingTime ~= "" and ((tonumber(trippingTime) + 300) > serverTime)) then
User:inform("Du findest dieses mal keinerlei Mnzen im Kessel. Vielleicht hat der verrckte Rattenalchemist vor, spter mehr zu machen.",
"You don't find any coins in the cauldron at this time. Maybe the crazy rat alchemist will make more later.")
return
end
-- safe tripping time
cauldronItem:setData("tripping_time", serverTime)
world:changeItem(cauldronItem)
User:inform("Du findest eine Gifttaler.","You discover a poison coin.")
local notCreated = User:createItem(3078, 1, 333, nil) -- silver coin
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(3078, notCreated, User.pos, true, 333, nil)
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.")
end
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.cauldron' WHERE itm_id IN (1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018);
local common = require("base.common")
local M = {}
local cauldronContents
function M.UseItem(User, SourceItem)
if (User:getQuestProgress(539) == 1) and SourceItem:getData("ratmanCauldron") ~= "" then--OK, the player does the quest 1
cauldronContents(User, SourceItem)
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(594, 172, -3) then --OK, the player does the quest 2 yellow
User:inform(
"Irgendwie schaffst du es, eine Flasche mit dem gelben Trank von Kaefity zu klauen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the yellow potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 1)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(594, 172, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(596, 173, -3) then --OK, the player does the quest 2 orange
User:inform(
"Du siehst verdutzt zu, wie sich die Flasche in deinen Hnden auflst. Diesen Trank wirst du wohl nicht abfllen knnen. Du solltest es woanders versuchen.",
"You look on in amazement as the bottle dissolves in your hands. There will be no obtaining this potion you should try elsewhere.")
world:gfx(52, User.pos) -- swirly
world:makeSound(13, User.pos)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(596, 173, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(598, 175, -3) then --OK, the player does the quest 2 blue
User:inform(
"Als der Inhalt des Kessels deine Flasche berhrt, fngt der Trank an, Blasen zu werfen und explodiert. Glasscherben fliegen durch die Gegend und verletzen dich.",
"When the contents of the cauldron hit your bottle the potion bubbles then causes an explosion. Glass shards fly causing you harm.")
world:gfx(44, User.pos) -- explosion gfx
world:makeSound(5, User.pos) --a loud boom
User:increaseAttrib("hitpoints", -1000) -- player loses health
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(598, 175, -3) then -- player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(598, 177, -3) then --OK, the player does the quest 2 dark green
User:inform(
"Irgendwie schaffst du es, eine Flasche des dunkelgrnen Tranks von Kaefity zu stehlen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the dark green potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 3)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(598, 177, -3) then -- player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
if (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) == 0) and SourceItem.pos == position(597, 180, -3) then --OK, the player does the quest 2 pink
User:inform(
"Irgendwie schaffst du es, eine Flasche des rosanen Tranks von Kaefity zu klauen. Du solltest sie zu Pasinn bringen.",
"You manage somehow to steal a bottle of the pink potion from Kaefity, You should take it to Pasinn.")
User:setQuestProgress(542, 1)
return
elseif (User:getQuestProgress(539) == 3) and (User:getQuestProgress(542) >= 0) and SourceItem.pos == position(597, 180, -3) then --player has a bottle
User:inform(
"Du hast bereits eine Flasche, du solltest sie Pasinn zeigen, ehe du mehr sammelst.",
"You already have a bottle, you should show it to Pasinn before collecting more.")
return
end
end
function cauldronContents(User, cauldronItem)
-- skip if already tripped in the last 5 minutes
local serverTime = world:getTime("unix")
local trippingTime = cauldronItem:getData("tripping_time")
if (trippingTime ~= "" and ((tonumber(trippingTime) + 300) > serverTime)) then
User:inform("Du findest dieses mal keinerlei Mnzen im Kessel. Vielleicht hat der verrckte Rattenalchemist vor, spter mehr zu machen.",
"You don't find any coins in the cauldron at this time. Maybe the crazy rat alchemist will make more later.")
return
end
-- safe tripping time
cauldronItem:setData("tripping_time", serverTime)
world:changeItem(cauldronItem)
User:inform("Du findest eine Gifttaler.","You discover a poison coin.")
local notCreated = User:createItem(3078, 1, 333, nil) -- silver coin
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(3078, notCreated, User.pos, true, 333, nil)
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.")
end
end
return M
|
fix duplicate
|
fix duplicate
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
|
975f15a46f6abbcae1d5667460b250619fac9733
|
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
|
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 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 uci = require "luci.model.uci".cursor()
local tools = require "luci.tools.ffwizard"
local util = require "luci.util"
local io = require "io"
-------------------- View --------------------
f = SimpleForm("siitwizward", "4over6-Assistent",
"Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.")
mode = f:field(ListValue, "mode", "Betriebsmodus")
mode:value("gateway", "Gateway")
mode:value("client", "Client")
dev = f:field(ListValue, "device", "WLAN-Gerät")
uci:foreach("network", "interface",
function(section)
if section[".name"] ~= "siit0" then
dev:value(section[".name"])
end
end)
-------------------- Control --------------------
LL_PREFIX = luci.ip.IPv6("fe80::/16")
--
-- find link-local address
--
function find_ll(dev)
for _, r in ipairs(luci.sys.net.routes6()) do
if r.device == dev and LL_PREFIX:contains(r.dest) then
return r.dest:sub(LL_PREFIX)
end
end
return luci.ip.IPv6("::")
end
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
elseif state == FORM_INVALID then
self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen."
end
return true
end
function mode.write(self, section, value)
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "defaults", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "defaults", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "defaults", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "defaults", "siit_prefix") or "::ffff:ffff:0000:0000"
local siit_route = luci.ip.IPv6(siit_prefix .. "/96")
-- Find wifi interface
local device = dev:formvalue(section)
--
-- Generate ULA
--
local ula = luci.ip.IPv6("::")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(luci.ip.IPv6(prefix))
end
ula = ula:add(find_ll(uci:get("network", device, "ifname") or device))
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
uci:set("network", "wan", "mtu", 1400)
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
local lan_ip = luci.ip.IPv4(
uci:get("network", "lan", "ipaddr"),
uci:get("network", "lan", "netmask")
)
siit_route = luci.ip.IPv6(
siit_prefix .. "/" .. (96 + lan_ip:prefix())
):add(lan_ip[2])
end
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "static",
ipaddr = "169.254.42.42",
netmask = "255.255.255.0"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = device,
target = siit_route:string()
})
-- interface
uci:set("network", device, "ip6addr", ula:string())
uci:set("network", "lan", "mtu", 1400)
uci:set("olsrd", "general", "IpVersion", 6)
uci:foreach("olsrd", "Interface",
function(s)
if s.interface == device then
uci:set("olsrd", s[".name"], "Ip6AddrType", "global")
end
uci:delete("olsrd", s[".name"], "Ip4Boradcast")
end)
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s)
if s.netaddr and s.prefix then
return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix))
end
end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
uci:save("network")
uci:save("olsrd")
end
return f
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 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 uci = require "luci.model.uci".cursor()
local tools = require "luci.tools.ffwizard"
local util = require "luci.util"
local io = require "io"
-------------------- View --------------------
f = SimpleForm("siitwizward", "4over6-Assistent",
"Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.")
mode = f:field(ListValue, "mode", "Betriebsmodus")
mode:value("gateway", "Gateway")
mode:value("client", "Client")
dev = f:field(ListValue, "device", "WLAN-Gerät")
uci:foreach("network", "interface",
function(section)
if section[".name"] ~= "siit0" then
dev:value(section[".name"])
end
end)
-------------------- Control --------------------
LL_PREFIX = luci.ip.IPv6("fe80::/16")
--
-- find link-local address
--
function find_ll(dev)
for _, r in ipairs(luci.sys.net.routes6()) do
if r.device == dev and LL_PREFIX:contains(r.dest) then
return r.dest:sub(LL_PREFIX)
end
end
return luci.ip.IPv6("::")
end
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
elseif state == FORM_INVALID then
self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen."
end
return true
end
function mode.write(self, section, value)
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "defaults", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "defaults", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "defaults", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "defaults", "siit_prefix") or "::ffff:ffff:0000:0000"
local siit_route = luci.ip.IPv6(siit_prefix .. "/96")
-- Find wifi interface
local device = dev:formvalue(section)
--
-- Generate ULA
--
local ula = luci.ip.IPv6("::")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(luci.ip.IPv6(prefix))
end
ula = ula:add(find_ll(uci:get("network", device, "ifname") or device))
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
uci:set("network", "wan", "mtu", 1400)
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
local lan_ip = luci.ip.IPv4(
uci:get("network", "lan", "ipaddr"),
uci:get("network", "lan", "netmask")
)
siit_route = luci.ip.IPv6(
siit_prefix .. "/" .. (96 + lan_ip:prefix())
):add(lan_ip[2])
end
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "static",
ipaddr = "169.254.42.42",
netmask = "255.255.255.0"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = device,
target = siit_route:string()
})
-- interface
uci:set("network", device, "ip6addr", ula:string())
uci:set("network", "lan", "mtu", 1400)
uci:set("olsrd", "general", "IpVersion", 6)
uci:foreach("olsrd", "Interface",
function(s)
if s.interface == device then
uci:set("olsrd", s[".name"], "Ip6AddrType", "global")
end
uci:delete("olsrd", s[".name"], "Ip4Broadcast")
end)
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s)
if s.netaddr and s.prefix then
return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix))
end
end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
uci:save("network")
uci:save("olsrd")
end
return f
|
applications/siitwizard: whitespace and typo fixes, svn property fixup
|
applications/siitwizard: whitespace and typo fixes, svn property fixup
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3842 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
stephank/luci,saraedum/luci-packages-old,8devices/carambola2-luci,freifunk-gluon/luci,phi-psi/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,alxhh/piratenluci,jschmidlapp/luci,eugenesan/openwrt-luci,alxhh/piratenluci,phi-psi/luci,Flexibity/luci,jschmidlapp/luci,Canaan-Creative/luci,stephank/luci,alxhh/piratenluci,Flexibity/luci,Flexibity/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,ch3n2k/luci,alxhh/piratenluci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,gwlim/luci,alxhh/piratenluci,8devices/carambola2-luci,stephank/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,jschmidlapp/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,gwlim/luci,jschmidlapp/luci,Flexibity/luci,ch3n2k/luci,zwhfly/openwrt-luci,gwlim/luci,stephank/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,phi-psi/luci,Flexibity/luci,gwlim/luci,freifunk-gluon/luci,freifunk-gluon/luci,projectbismark/luci-bismark,vhpham80/luci,projectbismark/luci-bismark,ch3n2k/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,vhpham80/luci,Canaan-Creative/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,Canaan-Creative/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ch3n2k/luci,Flexibity/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,gwlim/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,jschmidlapp/luci,gwlim/luci,yeewang/openwrt-luci,phi-psi/luci,jschmidlapp/luci,zwhfly/openwrt-luci,phi-psi/luci,ch3n2k/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,stephank/luci,jschmidlapp/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,vhpham80/luci,freifunk-gluon/luci,vhpham80/luci,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,alxhh/piratenluci
|
e2e49bf2f520c319b033bdceda027d26801a9b29
|
durden/tools/advfloat/spawnctl.lua
|
durden/tools/advfloat/spawnctl.lua
|
gconfig_register("advfloat_spawn", "auto");
gconfig_register("advfloat_actionreg", false);
local pending, pending_vid;
local function setup_cursor_pick(wm, wnd)
wnd:hide();
pending = wnd;
local w = math.ceil(wm.width * 0.15);
local h = math.ceil(wm.height * 0.15);
pending_vid = null_surface(w, h);
link_image(pending_vid, mouse_state().cursor);
image_sharestorage(wnd.canvas, pending_vid);
blend_image(pending_vid, 1.0, 10);
image_inherit_order(pending_vid, true);
order_image(pending_vid, -1);
nudge_image(pending_vid,
mouse_state().size[1] * 0.75, mouse_state().size[2] * 0.75);
shader_setup(pending_vid, "ui", "regmark", "active");
end
local function activate_pending()
delete_image(pending_vid);
pending = nil;
end
local function wnd_attach(wm, wnd)
wnd:ws_attach(true);
if (wnd.wm:active_space().mode ~= "float") then
return;
end
if (pending) then
activate_pending();
if (DURDEN_REGIONSEL_TRIGGER) then
suppl_region_stop();
end
end
local mode = gconfig_get("advfloat_spawn");
if (mode == "click") then
setup_cursor_pick(wm, wnd);
iostatem_save();
local col = null_surface(1, 1);
mouse_select_begin(col);
dispatch_meta_reset();
dispatch_symbol_lock();
durden_input = durden_regionsel_input;
-- the region setup and accept/fail is really ugly, but reworking it
-- right now is not really an option
DURDEN_REGIONFAIL_TRIGGER = function()
activate_pending();
wnd:show();
DURDEN_REGIONFAIL_TRIGGER = nil;
end
DURDEN_REGIONSEL_TRIGGER = function()
activate_pending();
if (wnd.show) then
wnd:show();
end
DURDEN_REGIONFAIL_TRIGGER = nil;
end
elseif (mode == "draw") then
setup_cursor_pick(wm, wnd);
DURDEN_REGIONFAIL_TRIGGER = function()
activate_pending();
DURDEN_REGIONFAIL_TRIGGER = nil;
end
suppl_region_select(200, 198, 36, function(x1, y1, x2, y2)
activate_pending();
local w = x2 - x1;
local h = y2 - y1;
if (w > 64 and h > 64) then
wnd:resize(w, h);
-- get control of the 'spawn' animation used here, might fight with flair later
instant_image_transform(wnd.anchor);
instant_image_transform(wnd.canvas);
instant_image_transform(wnd.border);
wnd.titlebar:resize(wnd.titlebar.width, wnd.titlebar.height, 0);
end
wnd:move(x1, y1, false, true, 0);
wnd:show();
end);
-- auto should really be to try and calculate the best fitting free space
elseif (mode == "cursor") then
local x, y = mouse_xy();
if (x + wnd.width > wnd.wm.effective_width) then
x = wnd.wm.effective_width - wnd.width;
end
if (y + wnd.width > wnd.wm.effective_height) then
y = wnd.wm.effective_height - wnd.height;
end
wnd:move(x, y, false, true, true);
else
end
end
--- hook displays so we can decide spawn mode between things like
--- spawn hidden, cursor-click to position, draw to spawn
display_add_listener(
function(event, name, tiler, id)
if (event == "added" and tiler) then
tiler.attach_hook = wnd_attach;
end
end
);
|
gconfig_register("advfloat_spawn", "auto");
gconfig_register("advfloat_actionreg", false);
local pending, pending_vid;
local function setup_cursor_pick(wm, wnd)
wnd:hide();
pending = wnd;
local w = math.ceil(wm.width * 0.15);
local h = math.ceil(wm.height * 0.15);
pending_vid = null_surface(w, h);
link_image(pending_vid, mouse_state().cursor);
image_sharestorage(wnd.canvas, pending_vid);
blend_image(pending_vid, 1.0, 10);
image_inherit_order(pending_vid, true);
order_image(pending_vid, -1);
nudge_image(pending_vid,
mouse_state().size[1] * 0.75, mouse_state().size[2] * 0.75);
shader_setup(pending_vid, "ui", "regmark", "active");
end
local function activate_pending()
delete_image(pending_vid);
pending = nil;
end
local function wnd_attach(wm, wnd)
local res = wnd:ws_attach(true);
if (wnd.wm:active_space().mode ~= "float") then
return res;
end
if (pending) then
activate_pending();
if (DURDEN_REGIONSEL_TRIGGER) then
suppl_region_stop();
end
end
local mode = gconfig_get("advfloat_spawn");
if (mode == "click") then
setup_cursor_pick(wm, wnd);
iostatem_save();
local col = null_surface(1, 1);
mouse_select_begin(col);
dispatch_meta_reset();
dispatch_symbol_lock();
durden_input = durden_regionsel_input;
-- the region setup and accept/fail is really ugly, but reworking it
-- right now is not really an option
DURDEN_REGIONFAIL_TRIGGER = function()
activate_pending();
wnd:show();
DURDEN_REGIONFAIL_TRIGGER = nil;
end
DURDEN_REGIONSEL_TRIGGER = function()
activate_pending();
if (wnd.show) then
wnd:show();
end
DURDEN_REGIONFAIL_TRIGGER = nil;
end
elseif (mode == "draw") then
setup_cursor_pick(wm, wnd);
DURDEN_REGIONFAIL_TRIGGER = function()
activate_pending();
DURDEN_REGIONFAIL_TRIGGER = nil;
end
suppl_region_select(200, 198, 36, function(x1, y1, x2, y2)
activate_pending();
local w = x2 - x1;
local h = y2 - y1;
if (w > 64 and h > 64) then
wnd:resize(w, h);
-- get control of the 'spawn' animation used here, might fight with flair later
instant_image_transform(wnd.anchor);
instant_image_transform(wnd.canvas);
instant_image_transform(wnd.border);
wnd.titlebar:resize(wnd.titlebar.width, wnd.titlebar.height, 0);
end
wnd:move(x1, y1, false, true, 0);
wnd:show();
end);
-- auto should really be to try and calculate the best fitting free space
elseif (mode == "cursor") then
local x, y = mouse_xy();
if (x + wnd.width > wnd.wm.effective_width) then
x = wnd.wm.effective_width - wnd.width;
end
if (y + wnd.width > wnd.wm.effective_height) then
y = wnd.wm.effective_height - wnd.height;
end
wnd:move(x, y, false, true, true);
else
end
return res;
end
--- hook displays so we can decide spawn mode between things like
--- spawn hidden, cursor-click to position, draw to spawn
display_add_listener(
function(event, name, tiler, id)
if (event == "added" and tiler) then
tiler.attach_hook = wnd_attach;
end
end
);
|
first-frame resize disappearance solved
|
first-frame resize disappearance solved
This one was surprisingly gnarly and a follow up to the arcan fix in 14e74da68.
The interception done by the spawnctl/advfloat failed to forward-chain the
result, causing a missing window structure reference that then never received
the origo_ll flag.
|
Lua
|
bsd-3-clause
|
letoram/durden
|
a119cf4f29b714c2bc4c6875712a37fce1645c4e
|
luapak/luarocks/site_config.lua
|
luapak/luarocks/site_config.lua
|
local log = require 'luapak.logging'
local utils = require 'luapak.utils'
local concat = table.concat
local find = utils.find
local is_windows -- initialized later
--- Returns true if there's system command `name` on PATH, false otherwise.
local function has_command (name)
local command = (is_windows and 'where ' or 'command -v ')..name
-- Note: It behaves differently on Lua 5.1 and 5.2+.
local first, _, third = os.execute(command)
return third == 0 or first == 0
end
local function find_command (subject, commands)
local cmd = find(has_command, commands)
if not cmd then
log.error('Cound not find %s, tried: %s', subject, concat(commands, ', '))
end
return cmd
end
local site_config; do
local version_suffix = utils.LUA_VERSION:gsub('%.', '_')
local ok
ok, site_config = pcall(require, 'luarocks.site_config_'..version_suffix)
if not ok or type(site_config) ~= 'table' then
ok, site_config = pcall(require, 'luarocks.site_config')
end
if not ok or type(site_config) ~= 'table' then
site_config = {}
package.loaded['luarocks.site_config'] = site_config
end
end
site_config.LUAROCKS_SYSCONFDIR = nil
site_config.LUAROCKS_ROCKS_TREE = nil
site_config.LUAROCKS_ROCKS_SUBDIR = nil
site_config.LUA_DIR_SET = nil
if not site_config.LUAROCKS_UNAME_S then
site_config.LUAROCKS_UNAME_S = io.popen('uname -s'):read('*l')
end
is_windows = site_config.LUAROCKS_UNAME_S
:gsub('^MINGW', 'Windows')
:match('^Windows') ~= nil
if not site_config.LUAROCKS_DOWNLOADER then
site_config.LUAROCKS_DOWNLOADER =
find_command('a downloader helper program', { 'curl', 'wget', 'fetch' })
end
if not site_config.LUAROCKS_MD5CHECKER then
site_config.LUAROCKS_MD5CHECKER =
find_command('a MD5 checksum calculator', { 'md5sum', 'openssl', 'md5' })
end
site_config.LUAROCKS_FAKE_PREFIX = 'C:\\Fake-Prefix'
if is_windows then
-- Set specified LUAROCKS_PREFIX so we can strip it in cfg_extra.
if not site_config.LUAROCKS_PREFIX then
site_config.LUAROCKS_PREFIX = site_config.LUAROCKS_FAKE_PREFIX
end
end
return site_config
|
local log = require 'luapak.logging'
local utils = require 'luapak.utils'
local concat = table.concat
local find = utils.find
local is_windows -- initialized later
--- Returns true if there's system command `name` on PATH, false otherwise.
local function has_command (name)
local cmd_tmpl = is_windows
and 'where %s 2> NUL 1> NUL'
or 'command -v %s >/dev/null'
-- Note: It behaves differently on Lua 5.1 and 5.2+.
local first, _, third = os.execute(cmd_tmpl:format(name))
return third == 0 or first == 0
end
local function find_command (subject, commands)
local cmd = find(has_command, commands)
if not cmd then
log.error('Cound not find %s, tried: %s', subject, concat(commands, ', '))
end
return cmd
end
local site_config; do
local version_suffix = utils.LUA_VERSION:gsub('%.', '_')
local ok
ok, site_config = pcall(require, 'luarocks.site_config_'..version_suffix)
if not ok or type(site_config) ~= 'table' then
ok, site_config = pcall(require, 'luarocks.site_config')
end
if not ok or type(site_config) ~= 'table' then
site_config = {}
package.loaded['luarocks.site_config'] = site_config
end
end
site_config.LUAROCKS_SYSCONFDIR = nil
site_config.LUAROCKS_ROCKS_TREE = nil
site_config.LUAROCKS_ROCKS_SUBDIR = nil
site_config.LUA_DIR_SET = nil
if not site_config.LUAROCKS_UNAME_S then
site_config.LUAROCKS_UNAME_S = io.popen('uname -s'):read('*l')
end
is_windows = site_config.LUAROCKS_UNAME_S
:gsub('^MINGW', 'Windows')
:match('^Windows') ~= nil
if not site_config.LUAROCKS_DOWNLOADER then
site_config.LUAROCKS_DOWNLOADER =
find_command('a downloader helper program', { 'curl', 'wget', 'fetch' })
end
if not site_config.LUAROCKS_MD5CHECKER then
site_config.LUAROCKS_MD5CHECKER =
find_command('a MD5 checksum calculator', { 'md5sum', 'openssl', 'md5' })
end
site_config.LUAROCKS_FAKE_PREFIX = 'C:\\Fake-Prefix'
if is_windows then
-- Set specified LUAROCKS_PREFIX so we can strip it in cfg_extra.
if not site_config.LUAROCKS_PREFIX then
site_config.LUAROCKS_PREFIX = site_config.LUAROCKS_FAKE_PREFIX
end
end
return site_config
|
Fix site_config to not print output of which/where commands
|
Fix site_config to not print output of which/where commands
|
Lua
|
mit
|
jirutka/luapak,jirutka/luapak
|
dac2c7ebfe6c79583020d5cc48c4fd9b8aa73acb
|
premake.lua
|
premake.lua
|
require ('premake-xbox360/xbox360')
require ("vstudio")
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64_GCC = "Linux64_GCC"
PlatformLinux64_Clang = "Linux64_Clang"
PlatformARM = "MSVC ARM"
PlatformARM64 = "MSVC ARM64"
Platform360 = "Xbox 360"
PlatformAndroidARM = "Android ARM"
PlatformAndroidARM64 = "Android ARM64"
UnitTestProject = "unit_tests"
AndroidProject = "hlsl++_android"
-- Directories
srcDir = "src"
includeDir = "include"
premake.override(premake.vstudio.vc2010.elements, "clCompile", function(oldfn, cfg)
local calls = oldfn(cfg)
table.insert(calls, function(cfg)
premake.vstudio.vc2010.element("SupportJustMyCode", nil, "false")
end)
return calls
end)
workspace("hlsl++")
configurations { "Debug", "Release" }
location (Workspace)
flags
{
"multiprocessorcompile", -- /MP
}
includedirs
{
includeDir,
}
vectorextensions ("sse4.1")
cppdialect("c++11")
if(_ACTION == "xcode4") then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
linkoptions { "-stdlib=libc++" }
elseif(_ACTION == "gmake") then
platforms { PlatformLinux64_GCC, PlatformLinux64_Clang }
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
filter { "platforms:"..PlatformLinux64_GCC }
toolset("gcc")
filter { "platforms:"..PlatformLinux64_Clang }
toolset("clang")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32, PlatformARM, PlatformARM64, PlatformAndroidARM, PlatformAndroidARM64, Platform360 }
local llvmToolset;
if (_ACTION == "vs2015") then
llvmToolset = "msc-llvm-vs2014";
else
llvmToolset = "msc-llvm";
end
startproject(UnitTestProject)
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
vectorextensions("avx")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
vectorextensions("avx")
filter { "platforms:"..PlatformLLVM64 }
toolset(llvmToolset)
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset(llvmToolset)
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformARM }
architecture("arm")
vectorextensions ("neon")
filter { "platforms:"..PlatformARM64 }
architecture("arm64")
vectorextensions ("neon")
filter { "platforms:"..PlatformAndroidARM }
system("android")
architecture("arm")
vectorextensions("neon")
buildoptions { "-Wno-unused-variable" }
linkoptions { "-lm" } -- Link against the standard math library
filter { "platforms:"..PlatformAndroidARM64 }
system("android")
architecture("arm64")
vectorextensions("neon")
buildoptions { "-Wno-unused-variable" }
linkoptions { "-lm" } -- Link against the standard math library
filter { "platforms:"..Platform360 }
system("xbox360")
vectorextensions ("default")
defines("_XBOX")
filter{}
end
--defines { "HLSLPP_SCALAR" }
configuration "Debug"
defines { "DEBUG" }
symbols "full"
inlining("auto") -- hlslpp relies on inlining for speed, big gains in debug builds without losing legibility
optimize("debug")
configuration "Release"
defines { "NDEBUG" }
optimize "on"
inlining("auto")
optimize("speed")
project ("hlsl++")
kind("staticlib")
language("c++")
files
{
includeDir.."/**.h",
includeDir.."/*.natvis"
}
project (UnitTestProject)
kind("consoleapp")
--links { "hlsl++" }
files
{
srcDir.."/*.cpp",
srcDir.."/*.h",
}
filter { "platforms:"..PlatformAndroidARM.." or ".. PlatformAndroidARM64}
kind("sharedlib")
files
{
"src/android/android_native_app_glue.h",
"src/android/android_native_app_glue.c",
}
filter{}
includedirs
{
srcDir.."/**.h"
}
project (AndroidProject)
removeplatforms("*")
platforms { PlatformAndroidARM, PlatformAndroidARM64 }
kind("Packaging") -- This type of project builds the apk
links (UnitTestProject) -- Android needs to link to the main project which was built as a dynamic library
androidapplibname(UnitTestProject)
files
{
"src/android/AndroidManifest.xml",
"src/android/build.xml",
"src/android/project.properties",
"src/android/res/values/strings.xml",
}
|
require ('premake-xbox360/xbox360')
require ("vstudio")
Workspace = "workspace/".._ACTION
-- Compilers
PlatformMSVC64 = "MSVC 64"
PlatformMSVC32 = "MSVC 32"
PlatformLLVM64 = "LLVM 64"
PlatformLLVM32 = "LLVM 32"
PlatformOSX64 = "OSX 64"
PlatformLinux64_GCC = "Linux64_GCC"
PlatformLinux64_Clang = "Linux64_Clang"
PlatformARM = "MSVC ARM"
PlatformARM64 = "MSVC ARM64"
Platform360 = "Xbox 360"
PlatformAndroidARM = "Android ARM"
PlatformAndroidARM64 = "Android ARM64"
UnitTestProject = "unit_tests"
AndroidProject = "hlsl++_android"
isMacBuild = _ACTION == "xcode4"
isLinuxBuild = _ACTION == "gmake"
isWindowsBuild = not isMacBuild and not isLinuxBuild
-- Directories
srcDir = "src"
includeDir = "include"
premake.override(premake.vstudio.vc2010.elements, "clCompile", function(oldfn, cfg)
local calls = oldfn(cfg)
table.insert(calls, function(cfg)
premake.vstudio.vc2010.element("SupportJustMyCode", nil, "false")
end)
return calls
end)
workspace("hlsl++")
configurations { "Debug", "Release" }
location (Workspace)
flags
{
"multiprocessorcompile", -- /MP
}
includedirs
{
includeDir,
}
vectorextensions ("sse4.1")
cppdialect("c++11")
if(isMacBuild) then
platforms { PlatformOSX64 }
toolset("clang")
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
linkoptions { "-stdlib=libc++" }
elseif(isLinuxBuild) then
platforms { PlatformLinux64_GCC, PlatformLinux64_Clang }
architecture("x64")
buildoptions { "-std=c++11 -msse4.1 -Wno-unused-variable" }
filter { "platforms:"..PlatformLinux64_GCC }
toolset("gcc")
filter { "platforms:"..PlatformLinux64_Clang }
toolset("clang")
else
platforms { PlatformMSVC64, PlatformMSVC32, PlatformLLVM64, PlatformLLVM32, PlatformARM, PlatformARM64, PlatformAndroidARM, PlatformAndroidARM64, Platform360 }
local llvmToolset;
if (_ACTION == "vs2015") then
llvmToolset = "msc-llvm-vs2014";
else
llvmToolset = "msc-llvm";
end
startproject(UnitTestProject)
filter { "platforms:"..PlatformMSVC64 }
toolset("msc")
architecture("x64")
vectorextensions("avx")
filter { "platforms:"..PlatformMSVC32 }
toolset("msc")
vectorextensions("avx")
filter { "platforms:"..PlatformLLVM64 }
toolset(llvmToolset)
architecture("x64")
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformLLVM32 }
toolset(llvmToolset)
buildoptions { "-Wno-unused-variable -msse4.1" }
filter { "platforms:"..PlatformARM }
architecture("arm")
vectorextensions ("neon")
filter { "platforms:"..PlatformARM64 }
architecture("arm64")
vectorextensions ("neon")
filter { "platforms:"..PlatformAndroidARM }
system("android")
architecture("arm")
vectorextensions("neon")
buildoptions { "-Wno-unused-variable" }
linkoptions { "-lm" } -- Link against the standard math library
filter { "platforms:"..PlatformAndroidARM64 }
system("android")
architecture("arm64")
vectorextensions("neon")
buildoptions { "-Wno-unused-variable" }
linkoptions { "-lm" } -- Link against the standard math library
filter { "platforms:"..Platform360 }
system("xbox360")
vectorextensions ("default")
defines("_XBOX")
filter{}
end
--defines { "HLSLPP_SCALAR" }
configuration "Debug"
defines { "DEBUG" }
symbols "full"
inlining("auto") -- hlslpp relies on inlining for speed, big gains in debug builds without losing legibility
optimize("debug")
configuration "Release"
defines { "NDEBUG" }
optimize "on"
inlining("auto")
optimize("speed")
project ("hlsl++")
kind("staticlib")
language("c++")
files
{
includeDir.."/**.h",
includeDir.."/*.natvis"
}
project (UnitTestProject)
kind("consoleapp")
--links { "hlsl++" }
files
{
srcDir.."/*.cpp",
srcDir.."/*.h",
}
filter { "platforms:"..PlatformAndroidARM.." or ".. PlatformAndroidARM64}
kind("sharedlib")
files
{
"src/android/android_native_app_glue.h",
"src/android/android_native_app_glue.c",
}
filter{}
includedirs
{
srcDir.."/**.h"
}
if (isWindowsBuild) then
project (AndroidProject)
removeplatforms("*")
platforms { PlatformAndroidARM, PlatformAndroidARM64 }
kind("Packaging") -- This type of project builds the apk
links (UnitTestProject) -- Android needs to link to the main project which was built as a dynamic library
androidapplibname(UnitTestProject)
files
{
"src/android/AndroidManifest.xml",
"src/android/build.xml",
"src/android/project.properties",
"src/android/res/values/strings.xml",
}
end
|
Fix premake.lua for Linux and Mac builds
|
Fix premake.lua for Linux and Mac builds
|
Lua
|
mit
|
redorav/hlslpp,redorav/hlslpp,redorav/hlslpp
|
2589bc5fb0ca32029dd61798a69c149db707a8e5
|
LuaSource/frame/cppobjectbase.lua
|
LuaSource/frame/cppobjectbase.lua
|
require "luaclass"
CppObjectBase = Class(ObjectBase)
CppSingleton = Class(CppObjectBase)
addfunc(CppSingleton, Singleton)
local LinkAgainstGC = {}
local LevelActors = {}
function CppObjectBase:EndPlay(Reason)
if not self.m_HasEndPlay then
self.m_HasEndPlay = true
self:Release()
end
end
function CppObjectBase:Destroy()
for v in pairs(self._gc_list) do
if v.Release then
v:Release()
end
end
LinkAgainstGC[self] = nil
local _cppinstance_ = rawget(self, "_cppinstance_")
if _cppinstance_ then
if _cppinstance_.Destroy then
_cppinstance_:Destroy()
end
rawset(self, "_cppinstance_", nil)
end
LevelActors[self] = nil
end
function CppObjectBase:BeginPlay()
if not self.m_HasBeginPlay then
self.m_HasBeginPlay = true
-- actor
local OnEndPlayDelegate = self.OnEndPlay
if OnEndPlayDelegate then
self:GC(OnEndPlayDelegate)
OnEndPlayDelegate:Add(InsCallBack(self.EndPlay, self))
end
if UActorComponent.Cast(self) then
self:Link(self:GetOwner())
end
end
end
function CppObjectBase:GetName()
return ULuautils.GetName(self)
end
function CppObjectBase:NewCpp(...)
if not rawget(self, "_meta_") then
error("not class")
end
return self._cppclass.New(...)
end
CppObjectBase.New = CppObjectBase.NewCpp
CppObjectBase.__iscppclass = true
function CppObjectBase:Ctor()
rawset(self, "_gc_list", {})
if AActor.Cast(self) then
LevelActors[self] = true
end
end
function CppObjectBase:GC(obj)
if obj then
self._gc_list[obj] = true
end
end
function CppObjectBase:Link(Actor)
if AActor.Cast(Actor) then
if type(Actor) == "table" then
Actor:GC(self)
else
LinkAgainstGC[self] = true
local destroy_delegate = Actor.OnEndPlay
self:GC(destroy_delegate)
local function f(ins)
ins:Release()
end
destroy_delegate:Add(InsCallBack(f, self))
end
else
-- error("can only link to Actor")
end
end
function CppObjectBase:Property(property)
return rawget(self._meta_, property)
end
local setexisttable = _setexisttable
function CppObjectBase:NewOn(inscpp, ...)
local ins = self:Ins()
rawset(ins, "_cppinstance_", inscpp)
rawset(ins, "_cppinstance_meta_", getmetatable(inscpp))
setexisttable(inscpp, ins)
ins:Initialize(...)
return ins
end
function CppObjectBase:IsAuth()
return self.Role == ENetRole.ROLE_Authority
end
function CppSingleton:NewOn(...)
if self:GetRaw() then
error("CppSingleton NewOn error")
else
local ins = CppObjectBase.NewOn(self, ...)
self._meta_._ins = ins
return ins
end
end
function CppSingleton:Get(...)
local meta = self._meta_
if rawget(meta, "_ins") == nil then
rawset(meta, "_ins", self:NewCpp(...))
end
return meta._ins
end
function OnWorldCleanup(World, bSessionEnded, bCleanupResources)
local ActorToDelete = {}
for Actor in pairs(LevelActors) do
local ActorWorld = ULuautils.GetActorWorld(Actor)
if not ActorWorld or ActorWorld == World then
table.insert(ActorToDelete, Actor)
end
end
for i, Actor in ipairs(ActorToDelete) do
Actor:Release()
LevelActors[Actor] = nil
end
ActorToDelete = nil
World = nil
for bpclassname in pairs(NeedGcBpClassName) do
_G[bpclassname] = nil
end
collectgarbage("collect")
-- delegate function may reference actor in their's upvalue,So need twice collect
collectgarbage("collect")
end
return CppObjectBase
|
require "luaclass"
CppObjectBase = Class(ObjectBase)
CppSingleton = Class(CppObjectBase)
addfunc(CppSingleton, Singleton)
local setexisttable = _setexisttable
local LinkAgainstGC = {}
local LevelActors = {}
function CppObjectBase:EndPlay(Reason)
if not self.m_HasEndPlay then
self.m_HasEndPlay = true
self:Release()
end
end
function CppObjectBase:Destroy()
for v in pairs(self._gc_list) do
if v.Release then
v:Release()
end
end
LinkAgainstGC[self] = nil
local _cppinstance_ = rawget(self, "_cppinstance_")
if _cppinstance_ then
if _cppinstance_.Destroy then
_cppinstance_:Destroy()
end
setexisttable(_cppinstance_, nil)
rawset(self, "_cppinstance_", nil)
end
LevelActors[self] = nil
end
function CppObjectBase:BeginPlay()
if not self.m_HasBeginPlay then
self.m_HasBeginPlay = true
-- actor
local OnEndPlayDelegate = self.OnEndPlay
if OnEndPlayDelegate then
self:GC(OnEndPlayDelegate)
OnEndPlayDelegate:Add(InsCallBack(self.EndPlay, self))
end
if UActorComponent.Cast(self) then
self:Link(self:GetOwner())
end
end
end
function CppObjectBase:GetName()
return ULuautils.GetName(self)
end
function CppObjectBase:NewCpp(...)
if not rawget(self, "_meta_") then
error("not class")
end
return self._cppclass.New(...)
end
CppObjectBase.New = CppObjectBase.NewCpp
CppObjectBase.__iscppclass = true
function CppObjectBase:Ctor()
rawset(self, "_gc_list", {})
if AActor.Cast(self) then
LevelActors[self] = true
end
end
function CppObjectBase:GC(obj)
if obj then
self._gc_list[obj] = true
end
end
function CppObjectBase:Link(Actor)
if AActor.Cast(Actor) then
if type(Actor) == "table" then
Actor:GC(self)
else
LinkAgainstGC[self] = true
local destroy_delegate = Actor.OnEndPlay
self:GC(destroy_delegate)
local function f(ins)
ins:Release()
end
destroy_delegate:Add(InsCallBack(f, self))
end
else
-- error("can only link to Actor")
end
end
function CppObjectBase:Property(property)
return rawget(self._meta_, property)
end
function CppObjectBase:NewOn(inscpp, ...)
local ins = self:Ins()
rawset(ins, "_cppinstance_", inscpp)
rawset(ins, "_cppinstance_meta_", getmetatable(inscpp))
setexisttable(inscpp, ins)
ins:Initialize(...)
return ins
end
function CppObjectBase:IsAuth()
return self.Role == ENetRole.ROLE_Authority
end
function CppSingleton:NewOn(...)
if self:GetRaw() then
error("CppSingleton NewOn error")
else
local ins = CppObjectBase.NewOn(self, ...)
self._meta_._ins = ins
return ins
end
end
function CppSingleton:Get(...)
local meta = self._meta_
if rawget(meta, "_ins") == nil then
rawset(meta, "_ins", self:NewCpp(...))
end
return meta._ins
end
function OnWorldCleanup(World, bSessionEnded, bCleanupResources)
local ActorToDelete = {}
for Actor in pairs(LevelActors) do
local ActorWorld = ULuautils.GetActorWorld(Actor)
if not ActorWorld or ActorWorld == World then
table.insert(ActorToDelete, Actor)
end
end
for i, Actor in ipairs(ActorToDelete) do
Actor:Release()
LevelActors[Actor] = nil
end
ActorToDelete = nil
World = nil
for bpclassname in pairs(NeedGcBpClassName) do
_G[bpclassname] = nil
end
collectgarbage("collect")
-- delegate function may reference actor in their's upvalue,So need twice collect
collectgarbage("collect")
end
return CppObjectBase
|
cpp memory reuse bug
|
cpp memory reuse bug
|
Lua
|
mit
|
asqbtcupid/unreal.lua,asqbtcupid/unreal.lua,asqbtcupid/unreal.lua
|
bea8e082da513d90660de84f9213a4fd9552d2eb
|
src/lua-factory/sources/grl-appletrailers.lua
|
src/lua-factory/sources/grl-appletrailers.lua
|
--[[
* Copyright (C) 2015 Grilo Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-appletrailers-lua",
name = "Apple Movie Trailers",
description = "Apple Trailers",
supported_media = 'video',
supported_keys = { 'author', 'publication-date', 'description', 'duration', 'genre', 'id', 'thumbnail', 'title', 'url', 'certificate', 'studio', 'license', 'performer', 'size' },
config_keys = {
optional = { 'definition' },
},
icon = 'resource:///org/gnome/grilo/plugins/appletrailers/trailers.svg',
tags = { 'country:us', 'cinema', 'net:internet', 'net:plaintext' },
}
-- Global table to store config data
ldata = {}
-- Global table to store parse results
cached_xml = nil
function grl_source_init(configs)
ldata.hd = (configs.definition and configs.definition == 'hd')
return true
end
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
APPLE_TRAILERS_CURRENT_SD = "http://trailers.apple.com/trailers/home/xml/current_480p.xml"
APPLE_TRAILERS_CURRENT_HD = "http://trailers.apple.com/trailers/home/xml/current_720p.xml"
function grl_source_browse()
local skip = grl.get_options("skip")
local count = grl.get_options("count")
-- Make sure to reset the cache when browsing again
if skip == 0 then
cached_xml = nil
end
if cached_xml then
parse_results(cached_xml)
else
local url = APPLE_TRAILERS_CURRENT_SD
if ldata.hd then
url = APPLE_TRAILERS_CURRENT_HD
end
grl.debug('Fetching URL: ' .. url .. ' (count: ' .. count .. ' skip: ' .. skip .. ')')
grl.fetch(url, "fetch_results_cb")
end
end
---------------
-- Utilities --
---------------
function fetch_results_cb(results)
if not results then
grl.warning('Failed to fetch XML file')
grl.callback()
return
end
cached_xml = grl.lua.xml.string_to_table(results)
parse_results(cached_xml)
end
function parse_results(results)
local count = grl.get_options("count")
local skip = grl.get_options("skip")
for i, item in pairs(results.records.movieinfo) do
local media = {}
media.type = 'video'
media.id = item.id
if item.cast then
media.performer = {}
for j, cast in pairs(item.cast.name) do
table.insert(media.performer, cast.xml)
end
end
if item.genre then
media.genre = {}
for j, genre in pairs(item.genre.name) do
table.insert(media.genre, genre.xml)
end
end
media.license = item.info.copyright.xml
media.description = item.info.description.xml
media.director = item.info.director.xml
media.publication_date = item.info.releasedate.xml
media.certificate = item.info.rating.xml
media.studio = item.info.studio.xml
media.title = item.info.title.xml
media.thumbnail = item.poster.xlarge.xml
media.url = item.preview.large.xml
media.size = item.preview.large.filesize
local mins, secs = item.info.runtime.xml:match('(%d):(%d)')
media.duration = tonumber(mins) * 60 + tonumber(secs)
if skip > 0 then
skip = skip - 1
else
count = count - 1
grl.callback(media, count)
if count == 0 then
return
end
end
end
if count ~= 0 then
grl.callback()
end
end
|
--[[
* Copyright (C) 2015 Grilo Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-appletrailers-lua",
name = "Apple Movie Trailers",
description = "Apple Trailers",
supported_media = 'video',
supported_keys = { 'author', 'publication-date', 'description', 'duration', 'genre', 'id', 'thumbnail', 'title', 'url', 'certificate', 'studio', 'license', 'performer', 'size' },
config_keys = {
optional = { 'definition' },
},
icon = 'resource:///org/gnome/grilo/plugins/appletrailers/trailers.svg',
tags = { 'country:us', 'cinema', 'net:internet', 'net:plaintext' },
}
-- Global table to store config data
ldata = {}
-- Global table to store parse results
cached_xml = nil
function grl_source_init(configs)
ldata.hd = (configs.definition and configs.definition == 'hd')
return true
end
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
APPLE_TRAILERS_CURRENT_SD = "http://trailers.apple.com/trailers/home/xml/current_480p.xml"
APPLE_TRAILERS_CURRENT_HD = "http://trailers.apple.com/trailers/home/xml/current_720p.xml"
function grl_source_browse(media, options, callback)
local skip = options.skip
local count = options.count
local userdata = {callback = callback, skip = skip, count = count}
-- Make sure to reset the cache when browsing again
if skip == 0 then
cached_xml = nil
end
if cached_xml then
parse_results(cached_xml, userdata)
else
local url = APPLE_TRAILERS_CURRENT_SD
if ldata.hd then
url = APPLE_TRAILERS_CURRENT_HD
end
grl.debug('Fetching URL: ' .. url .. ' (count: ' .. count .. ' skip: ' .. skip .. ')')
grl.fetch(url, fetch_results_cb, userdata)
end
end
---------------
-- Utilities --
---------------
function fetch_results_cb(results, userdata)
if not results then
grl.warning('Failed to fetch XML file')
userdata.callback()
return
end
cached_xml = grl.lua.xml.string_to_table(results)
parse_results(cached_xml, userdata)
end
function parse_results(results, userdata)
for i, item in pairs(results.records.movieinfo) do
local media = {}
media.type = 'video'
media.id = item.id
if item.cast then
media.performer = {}
for j, cast in pairs(item.cast.name) do
table.insert(media.performer, cast.xml)
end
end
if item.genre then
media.genre = {}
for j, genre in pairs(item.genre.name) do
table.insert(media.genre, genre.xml)
end
end
media.license = item.info.copyright.xml
media.description = item.info.description.xml
media.director = item.info.director.xml
media.publication_date = item.info.releasedate.xml
media.certificate = item.info.rating.xml
media.studio = item.info.studio.xml
media.title = item.info.title.xml
media.thumbnail = item.poster.xlarge.xml
media.url = item.preview.large.xml
media.size = item.preview.large.filesize
local mins, secs = item.info.runtime.xml:match('(%d):(%d)')
media.duration = tonumber(mins) * 60 + tonumber(secs)
if userdata.skip > 0 then
userdata.skip = userdata.skip - 1
else
userdata.count = userdata.count - 1
userdata.callback(media, userdata.count)
if userdata.count == 0 then
return
end
end
end
if userdata.count ~= 0 then
userdata.callback()
end
end
|
lua-factory: port grl-appletrailers.lua to the new lua system
|
lua-factory: port grl-appletrailers.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,grilofw/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins
|
36e28061216ee749843f54a87956607545b106dd
|
lib/dxjob.lua
|
lib/dxjob.lua
|
local dxjob = {}
local cxjob = require('cxjob')
function dxjob.new(targetConf)
if type(targetConf) ~= 'table' then
errorlog('[Error] failed dxjob new')
return
end
local inst = {
m_jobque = {}, -- job queue
m_submitque = {}, -- submitting job
m_doneque = {}, -- ended job
m_maxsubmitnum = 5,
m_targetconf = targetConf,
m_jobstartdate = "",
}
inst.m_jobmgr = cxjob.new(targetConf)
setmetatable(inst, {__index = dxjob})
return inst;
end
function dxjob:SetMaxSubmit(num)
self.m_maxsubmitnum = num
end
function dxjob:Cancel()
for i,v in pairs(self.m_submitque) do
self.m_jobmgr:remoteJobDel(v)
end
self.m_submitque = {}
self.m_jobque = {}
self.m_doneque = {}
end
function dxjob:AddJob(job)
self.m_jobque[#self.m_jobque + 1] = job
end
function dxjob:GenerateBootSh(run)
for i,v in pairs(self.m_jobque) do
print(v.path, v.name, v.job)
if (v.path == nil) then
print('[Error] not found job.path')
return
end
local placenum = string.find(v.path, "/")
if placenum == nil then
placenum = string.find(v.path, "\\")
end
if (placenum == nil or placenum ~= v.path:len()) then
v.path = v.path .. "/"
end
local bootsh = '.' .. getBasePath() .. '/' .. v.path .. 'boot.sh'
print('write: ' .. bootsh)
local f = io.open(bootsh, "wb")
if f == nil then
errorlog('faild write:' .. bootsh)
else
local str = self.m_jobmgr:getBootSh() --self.m_targetconf.bootsh;
-- replace template
str = str:gsub("JOB.NODE", v.node)
str = str:gsub("JOB.CORE", v.core)
str = str:gsub("JOB.NAME", v.name)
if run == false then
str = str:gsub("JOB.JOB", '--version')
else
str = str:gsub("JOB.JOB", v.job)
end
--print('-------\n' .. str .. '-------\n')
f:write(str)
f:close()
end
end
end
function getDirAndName(fullpath)
local str = string.reverse(fullpath)
local placenum = string.find(str, "/")
if placenum == nil then
placenum = string.find(str, "\\")
end
if placenum == fullpath:len() then
str = string.sub(str, 0, placenum - 1)
placenum = string.find(str, "/")
if placenum == nil then
placenum = string.find(str, "\\")
end
end
local name = string.sub(str, 0, placenum-1):reverse()
local dirpath = string.sub(str, placenum):reverse()
return dirpath, name
end
--[[
function getJobCaseName(casename)
return casename .. os.date("_%Y%m%d_%H%M%S")
end
--]]
function getRelativeCasePath()
local p = getBasePath()
if (p == "") then
local uppath
local casename
local caseDir = getCurrentDir()
uppath, casename = getDirAndName(caseDir)
return casename
else
local projDir = getCurrentDir()
local uppath
local projname
uppath, projname = getDirAndName(projDir)
return projname .. p
end
end
function gettempTarFile()
if getPlatform() == 'Windows' then
return '..' .. os.tmpname() .. 'tar.gz'
else
return os.tmpname() .. '.tar.gz'
end
end
function dxjob:SendDir(localdir)
print('PATH='..localdir)
local temptar = gettempTarFile()
print('temptar = ' .. temptar)
local dirpath, casename = getDirAndName(localdir)
local exist = self.m_jobmgr:isExistFile(casename)
if exist == true then
print('Already exist case directory:', casename);
--
-- TODO: backup directry
--
-- DELETE now.
self.m_jobmgr:remoteWorkDeleteDir(casename)
end
compressFile(casename, temptar, true, '-C '..dirpath) -- compress
self.m_jobmgr:sendFile(temptar, 'HPCPF_case.tar.gz') -- send
deleteFile(temptar) -- delete localtar file
self.m_jobmgr:remoteExtractFile('HPCPF_case.tar.gz', true) -- extract
self.m_jobmgr:remoteDeleteFile ('HPCPF_case.tar.gz') -- delete temp file
return true
end
function dxjob:GetDir(remotedir, basedir)
print('get:'..remotedir)
local remotetarfile = 'HPCPF_case.tar.gz'
--self.m_jobmgr:remoteCompressFile(remotedir, remotetarfile, true)
local newdate = self.m_jobstartdate
-- TODO: newer date
print('NEWDATE:',newdate)
if newdate == '' then
self.m_jobmgr:remoteCompressFile(remotedir, remotetarfile, true)
else
self.m_jobmgr:remoteCompressNewerFile(remotedir, remotetarfile, newdate, true)
end
local temptar = gettempTarFile()
print('temptar = ' .. temptar)
self.m_jobmgr:getFile(temptar, remotetarfile) -- get
--local dirpath, casename = getDirAndName(localdir)
extractFile(temptar, true, '-C '..basedir) -- compress
self.m_jobmgr:remoteDeleteFile (remotetarfile) -- delete temp file
deleteFile(temptar)
end
function dxjob:SubmitAndWait(remoteCasePath)
--self.m_jobstartdate = os.date('20%y-%m-%d %H:%M:%S')
self.m_jobstartdate = self.m_jobmgr:remoteDate()
while #self.m_jobque > 0 or #self.m_submitque > 0 do
-- check ended job
for i = #self.m_submitque, 1, -1 do
local v = self.m_submitque[i]
if self.m_jobmgr:remoteJobStat(v) == 'END' then
self.m_doneque[#self.m_doneque + 1] = v
table.remove(self.m_submitque, i)
end
sleep(1) -- wait
end
-- submit new job
if #self.m_jobque > 0 then
if #self.m_submitque >= self.m_maxsubmitnum then
sleep(10)
else
local job = self.m_jobque[1]
table.remove(self.m_jobque, 1)
self.m_submitque[#self.m_submitque + 1] = job
self.m_jobmgr:remoteJobSubmit(job, remoteCasePath, 'boot.sh')
end
else
sleep(10)
end
print('JOB: QUE='.. #self.m_jobque .. ' / SUBMIT='.. #self.m_submitque .. ' DONE=' .. #self.m_doneque)
end
end
return dxjob
|
local dxjob = {}
local cxjob = require('cxjob')
function dxjob.new(targetConf)
if type(targetConf) ~= 'table' then
errorlog('[Error] failed dxjob new')
return
end
local inst = {
m_jobque = {}, -- job queue
m_submitque = {}, -- submitting job
m_doneque = {}, -- ended job
m_maxsubmitnum = 5,
m_targetconf = targetConf,
m_jobstartdate = "",
}
inst.m_jobmgr = cxjob.new(targetConf)
setmetatable(inst, {__index = dxjob})
return inst;
end
function dxjob:SetMaxSubmit(num)
self.m_maxsubmitnum = num
end
function dxjob:Cancel()
for i,v in pairs(self.m_submitque) do
self.m_jobmgr:remoteJobDel(v)
end
self.m_submitque = {}
self.m_jobque = {}
self.m_doneque = {}
end
function dxjob:AddJob(job)
self.m_jobque[#self.m_jobque + 1] = job
end
function dxjob:GenerateBootSh(run)
for i,v in pairs(self.m_jobque) do
print(v.path, v.name, v.job)
if (v.path == nil) then
print('[Error] not found job.path')
return
end
local placenum = string.find(v.path, "/")
if placenum == nil then
placenum = string.find(v.path, "\\")
end
if (placenum == nil or placenum ~= v.path:len()) then
v.path = v.path .. "/"
end
local bootsh = '.' .. getBasePath() .. '/' .. v.path .. 'boot.sh'
print('write: ' .. bootsh)
local f = io.open(bootsh, "wb")
if f == nil then
errorlog('faild write:' .. bootsh)
else
local str = self.m_jobmgr:getBootSh() --self.m_targetconf.bootsh;
-- replace template
str = str:gsub("JOB.NODE", v.node)
str = str:gsub("JOB.CORE", v.core)
str = str:gsub("JOB.NAME", v.name)
if run == false then
str = str:gsub("JOB.JOB", '--version')
else
str = str:gsub("JOB.JOB", v.job)
end
--print('-------\n' .. str .. '-------\n')
f:write(str)
f:close()
end
end
end
function getDirAndName(fullpath)
local str = string.reverse(fullpath)
local placenum = string.find(str, "/")
if placenum == nil then
placenum = string.find(str, "\\")
end
if placenum == fullpath:len() then
str = string.sub(str, 0, placenum - 1)
placenum = string.find(str, "/")
if placenum == nil then
placenum = string.find(str, "\\")
end
end
local name = string.sub(str, 0, placenum-1):reverse()
local dirpath = string.sub(str, placenum):reverse()
return dirpath, name
end
--[[
function getJobCaseName(casename)
return casename .. os.date("_%Y%m%d_%H%M%S")
end
--]]
function getRelativeCasePath()
local p = getBasePath()
if (p == "") then
local uppath
local casename
local caseDir = getCurrentDir()
uppath, casename = getDirAndName(caseDir)
return casename
else
local projDir = getCurrentDir()
local uppath
local projname
uppath, projname = getDirAndName(projDir)
return projname .. p
end
end
function gettempTarFile()
if getPlatform() == 'Windows' then
return '..' .. os.tmpname() .. 'tar.gz'
else
return os.tmpname() .. '.tar.gz'
end
end
function dxjob:SendDir(localdir)
print('PATH='..localdir)
local temptar = gettempTarFile()
print('temptar = ' .. temptar)
local dirpath, casename = getDirAndName(localdir)
local exist = self.m_jobmgr:isExistFile(casename)
if exist == true then
print('Already exist case directory:', casename);
--
-- TODO: backup directry
--
-- DELETE now.
self.m_jobmgr:remoteWorkDeleteDir(casename)
end
compressFile(casename, temptar, true, '-C '..dirpath) -- compress
self.m_jobmgr:sendFile(temptar, 'HPCPF_case.tar.gz') -- send
deleteFile(temptar) -- delete localtar file
self.m_jobmgr:remoteExtractFile('HPCPF_case.tar.gz', true) -- extract
self.m_jobmgr:remoteDeleteFile ('HPCPF_case.tar.gz') -- delete temp file
return true
end
function dxjob:GetDir(remotedir, basedir)
print('get:'..remotedir)
local remotedir_asta = remotedir .. '/*';
local remotetarfile = 'HPCPF_case.tar.gz'
--self.m_jobmgr:remoteCompressFile(remotedir_asta, remotetarfile, true)
local newdate = self.m_jobstartdate
-- TODO: newer date
print('NEWDATE:',newdate)
if newdate == '' then
self.m_jobmgr:remoteCompressFile(remotedir_asta, remotetarfile, true)
else
self.m_jobmgr:remoteCompressNewerFile(remotedir_asta, remotetarfile, newdate, true)
end
local temptar = gettempTarFile()
print('temptar = ' .. temptar)
self.m_jobmgr:getFile(temptar, remotetarfile) -- get
--local dirpath, casename = getDirAndName(localdir)
extractFile(temptar, true, '-C '..basedir) -- compress
self.m_jobmgr:remoteDeleteFile (remotetarfile) -- delete temp file
deleteFile(temptar)
end
function dxjob:SubmitAndWait(remoteCasePath)
--self.m_jobstartdate = os.date('20%y-%m-%d %H:%M:%S')
self.m_jobstartdate = self.m_jobmgr:remoteDate()
while #self.m_jobque > 0 or #self.m_submitque > 0 do
-- check ended job
for i = #self.m_submitque, 1, -1 do
local v = self.m_submitque[i]
if self.m_jobmgr:remoteJobStat(v) == 'END' then
self.m_doneque[#self.m_doneque + 1] = v
table.remove(self.m_submitque, i)
end
sleep(1) -- wait
end
-- submit new job
if #self.m_jobque > 0 then
if #self.m_submitque >= self.m_maxsubmitnum then
sleep(10)
else
local job = self.m_jobque[1]
table.remove(self.m_jobque, 1)
self.m_submitque[#self.m_submitque + 1] = job
self.m_jobmgr:remoteJobSubmit(job, remoteCasePath, 'boot.sh')
end
else
sleep(10)
end
print('JOB: QUE='.. #self.m_jobque .. ' / SUBMIT='.. #self.m_submitque .. ' DONE=' .. #self.m_doneque)
end
end
return dxjob
|
fix tar compress
|
fix tar compress
|
Lua
|
bsd-2-clause
|
avr-aics-riken/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI
|
8464001e75933758214707c21321a5dbb0368fe0
|
quest/explorersguild.lua
|
quest/explorersguild.lua
|
-- This module holds the core functions for the explorers guild.
-- The questIDs start at 130 and go to 150.
-- Written by Martin
require("base.common")
module("quest.explorersguild", package.seeall)
function CheckStone(Char,StoneNumber)
retVal=false;
StoneBase=130+math.floor((StoneNumber-1)/32); -- Stone 0 to 31 -> 0, 32-.. ->2 etc.
StoneBaseOffset=math.mod(StoneNumber-1,32); -- StoneNr inside range
HasStones=Char:getQuestProgress(StoneBase)+2^31;
GotStone=LuaAnd(2^(StoneNumber),HasStones);
if GotStone>0 then
retVal=true;
end
return retVal;
end
function CountStones(Char)
nrStones=0;
StoneBase=130;
StoneEnd=149;
for i=StoneBase,StoneEnd do
stones=Char:getQuestProgress(i)+2^31;
while stones~=0 do
nrStones=nrStones+math.mod(stones,2);
stones=math.floor(stones/2);
end
end
return nrStones
end
function WriteStone(Char,StoneNumber)
StoneBase=130+math.floor(StoneNumber/32); -- Stone 0 to 31 -> 0, 32-.. ->2 etc.
StoneBaseOffset=math.mod(StoneNumber,32); -- StoneNr inside range
--Char:inform("Base offset: " .. StoneBase .. " Stone Nr "..StoneBaseOffset .. " for stone "..StoneNumber);
currentStones=Char:getQuestProgress(StoneBase)+2^31;
Char:setQuestProgress(StoneBase,LuaOr(2^StoneBaseOffset,currentStones)-2^31);
end
-- reward[x] = {y,z} - x = stones to have collected, y = item id , z= amount of y
reward = {}
reward[1] = {{3077, 2}}; -- 2 silver coins (3077)
reward[5] = {{3077, 10},{49,1},{841,1},{463,1},{27,1}}; -- items worth 10 silver coins
reward[10] = {{3077, 20},{455, 10},{21,20},{325,1},{230,1}} -- items worth 20 silver coins
reward[20] = {{3077, 30},{322,50},{1,1},{9,1},{2922,1}} -- items worth 30 silver coins
reward[50] = {{3077, 60},{1062, 6},{353,3},{811,1},{297,1}} -- items worth 60 silver coins
reward[100] = {{61, 1},{2390,1},{2647,5},{557,4},{2675,1}} -- items worth 1 gold coin
reward[200] = {{61,2},{2369,1},{164,30},{2718,1},{547,1}} -- items worth 2 gold coins
reward[350] = {{61,3},{193,1},{2685,1},{559,7},{2360,1}} -- items worth 3 gold coins
reward[500] = {{61,5},{2551,10},{2552,10},{2553,10},{2554,10}} -- items worth 5 gold coins
reward[750] = {{61,8},{2367,1},{2693,1},{2662,1},{559,10}} -- items worth 8 gold coins
function getReward(Char)
local nrStones = CountStones(Char)
if reward[nrStones] ~= nil then
if table.getn(reward[nrStones]) == 1 then
Char:createItem(reward[nrStones][1][1],reward[nrStones][1][2],333,nil);
Char:inform("Du hast 2 Silberstcke erhalten, da du den ersten Markierungsstein entdeckt hast. Weiter so!", "You received 2 silver coins for discovering the first marker stone. Keep it up!");
else
rewardDialog(Char, nrStones)
end
end
end
function rewardDialog(Char, nrStones)
local title = base.common.GetNLS(Char,"Entdeckergilde Belohnung","Explorerguild reward")
local text = base.common.GetNLS(Char,"Du hast "..nrStones.." Markierungssteine entdeckt, daher kannst du dir nun eine Belohnung aussuchen.", "You discovered "..nrStones.." marker stones, therefor you can pick a reward.")
local callback = function(dialog)
local success = dialog:getSuccess()
if success then
selected = dialog:getSelectedIndex()+1
Char:createItem(reward[nrStones][selected][1],reward[nrStones][selected][2], 800, nil);
end
end
local dialog = SelectionDialog(title, text, callback);
local itemName;
local language = Char:getPlayerLanguage();
for i=1, #(reward[nrStones]) do
itemName = world:getItemName(reward[nrStones][i][1],language);
dialog:addOption(reward[nrStones][i][1], reward[nrStones][i][2].." "..itemName);
end
Char:requestSelectionDialog(dialog);
end
|
-- This module holds the core functions for the explorers guild.
-- The questIDs start at 130 and go to 150.
-- Written by Martin
require("base.common")
module("quest.explorersguild", package.seeall)
function CheckStone(Char,StoneNumber)
retVal=false;
StoneBase=130+math.floor((StoneNumber-1)/32); -- Stone 0 to 31 -> 0, 32-.. ->2 etc.
Char:inform("Stonebase: "..StoneBase);
StoneBaseOffset=math.mod(StoneNumber-1,32); -- StoneNr inside range
Char:inform("Offset: "..StoneBaseOffset);
HasStones=Char:getQuestProgress(StoneBase)+2^31;
Char:inform("HasStones: "..HasStones);
GotStone=LuaAnd(2^(StoneBaseOffset),HasStones);
if GotStone>0 then
retVal=true;
end
return retVal;
end
function CountStones(Char)
nrStones=0;
StoneBase=130;
StoneEnd=149;
for i=StoneBase,StoneEnd do
stones=Char:getQuestProgress(i)+2^31;
while stones~=0 do
nrStones=nrStones+math.mod(stones,2);
stones=math.floor(stones/2);
end
end
return nrStones
end
function WriteStone(Char,StoneNumber)
StoneBase=130+math.floor(StoneNumber/32); -- Stone 0 to 31 -> 0, 32-.. ->2 etc.
StoneBaseOffset=math.mod(StoneNumber,32); -- StoneNr inside range
--Char:inform("Base offset: " .. StoneBase .. " Stone Nr "..StoneBaseOffset .. " for stone "..StoneNumber);
currentStones=Char:getQuestProgress(StoneBase)+2^31;
Char:setQuestProgress(StoneBase,LuaOr(2^StoneBaseOffset,currentStones)-2^31);
end
-- reward[x] = {y,z} - x = stones to have collected, y = item id , z= amount of y
reward = {}
reward[1] = {{3077, 2}}; -- 2 silver coins (3077)
reward[5] = {{3077, 10},{49,1},{841,1},{463,1},{27,1}}; -- items worth 10 silver coins
reward[10] = {{3077, 20},{455, 10},{21,20},{325,1},{230,1}} -- items worth 20 silver coins
reward[20] = {{3077, 30},{322,50},{1,1},{9,1},{2922,1}} -- items worth 30 silver coins
reward[50] = {{3077, 60},{1062, 6},{353,3},{811,1},{297,1}} -- items worth 60 silver coins
reward[100] = {{61, 1},{2390,1},{2647,5},{557,4},{2675,1}} -- items worth 1 gold coin
reward[200] = {{61,2},{2369,1},{164,30},{2718,1},{547,1}} -- items worth 2 gold coins
reward[350] = {{61,3},{193,1},{2685,1},{559,7},{2360,1}} -- items worth 3 gold coins
reward[500] = {{61,5},{2551,10},{2552,10},{2553,10},{2554,10}} -- items worth 5 gold coins
reward[750] = {{61,8},{2367,1},{2693,1},{2662,1},{559,10}} -- items worth 8 gold coins
function getReward(Char)
local nrStones = CountStones(Char)
if reward[nrStones] ~= nil then
if table.getn(reward[nrStones]) == 1 then
Char:createItem(reward[nrStones][1][1],reward[nrStones][1][2],333,nil);
Char:inform("Du hast 2 Silberstcke erhalten, da du den ersten Markierungsstein entdeckt hast. Weiter so!", "You received 2 silver coins for discovering the first marker stone. Keep it up!");
else
rewardDialog(Char, nrStones)
end
end
end
function rewardDialog(Char, nrStones)
local title = base.common.GetNLS(Char,"Entdeckergilde Belohnung","Explorerguild reward")
local text = base.common.GetNLS(Char,"Du hast "..nrStones.." Markierungssteine entdeckt, daher kannst du dir nun eine Belohnung aussuchen.", "You discovered "..nrStones.." marker stones, therefor you can pick a reward.")
local callback = function(dialog)
local success = dialog:getSuccess()
if success then
selected = dialog:getSelectedIndex()+1
Char:createItem(reward[nrStones][selected][1],reward[nrStones][selected][2], 800, nil);
end
end
local dialog = SelectionDialog(title, text, callback);
local itemName;
local language = Char:getPlayerLanguage();
for i=1, #(reward[nrStones]) do
itemName = world:getItemName(reward[nrStones][i][1],language);
dialog:addOption(reward[nrStones][i][1], reward[nrStones][i][2].." "..itemName);
end
Char:requestSelectionDialog(dialog);
end
|
Fixed check markerstones
|
Fixed check markerstones
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content
|
3b8db05d54d912849215cf90b66109b082875521
|
share/lua/website/bikeradar.lua
|
share/lua/website/bikeradar.lua
|
-- libquvi-scripts
-- Copyright (C) 2011-2012 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 = "bikeradar%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain})
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 = "bikeradar"
self.id = self.page_url:match('bikeradar.com/.+-(%d+)$')
or error("no match: media ID")
local p = quvi.fetch(self.page_url)
self.title = p:match('"og:title" content="(.-)"/>')
or error("no match: media title")
self.thumbnail_url = p:match('"og:image" content="(.-)"') or ''
local fn = p:match('<param name="flashvars" value="vcode=(%w+)&')
or error("no match: file name")
self.url = {string.format("http://cdn.video.bikeradar.com/%s.flv",fn)}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2011-2012 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 = "bikeradar%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {'/videos/.-%-%w+$'})
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 = "bikeradar"
local p = quvi.fetch(self.page_url)
self.redirect_url = p:match('"embedURL" href="(.-)"')
or error('no match: embedURL')
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: website/bikeradar.lua: Look for embedURL
|
FIX: website/bikeradar.lua: Look for embedURL
Check page HTML for embedded URL, since bikeshed apparently uses YouTube
to host their media. Set `self.redirect_url' or croak.
* ident: Update media URL pattern
* parse: Set `self.redirect_url' only, do not parse anything else
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
|
0d112c4fa5fd6a008c3b2c51e35c8fc1265bbd60
|
frontend/ui/networkmgr.lua
|
frontend/ui/networkmgr.lua
|
local ConfirmBox = require("ui/widget/confirmbox")
local UIManager = require("ui/uimanager")
local Device = require("ui/device")
local DEBUG = require("dbg")
local _ = require("gettext")
local NetworkMgr = {}
local function kindleEnableWifi(toggle)
local lipc = require("liblipclua")
local lipc_handle = nil
if lipc then
lipc_handle = lipc.init("com.github.koreader.networkmgr")
end
if lipc_handle then
lipc_handle:set_int_property("com.lab126.cmd", "wirelessEnable", toggle)
lipc_handle:close()
end
end
local function koboEnableWifi(toggle)
if toggle == 1
local path = "/etc/wpa_supplicant/wpa_supplicant.conf"
os.execute("insmod /drivers/ntx508/wifi/sdio_wifi_pwr.ko 2>/dev/null")
os.execute("insmod /drivers/ntx508/wifi/dhd.ko")
os.execute("ifconfig eth0 up")
os.execute("wlarm_le -i eth0 up")
os.execute("wpa_supplicant -s -i eth0 -c "..path.." -C /var/run/wpa_supplicant -B")
os.execute("udhcpc -S -i eth0 -s /etc/udhcpc.d/default.script -t15 -T10 -A3 -b -q >/dev/null 2>&1")
else
os.execute("killall udhcpc wpa_supplicant 2>/dev/null")
os.execute("wlarm_le -i eth0 down")
os.execute("ifconfig eth0 down")
os.execute("rmmod -r dhd")
os.execute("rmmod -r sdio_wifi_pwr")
end
end
function NetworkMgr:turnOnWifi()
if Device:isKindle() then
kindleEnableWifi(1)
elseif Device:isKobo() then
koboEnableWifi(1)
end
end
function NetworkMgr:turnOffWifi()
if Device:isKindle() then
kindleEnableWifi(0)
elseif Device:isKobo() then
koboEnableWifi(0)
end
end
function NetworkMgr:promptWifiOn()
UIManager:show(ConfirmBox:new{
text = _("Do you want to Turn on Wifi?"),
ok_callback = function()
self:turnOnWifi()
end,
})
end
function NetworkMgr:promptWifiOff()
UIManager:show(ConfirmBox:new{
text = _("Do you want to Turn off Wifi?"),
ok_callback = function()
self:turnOffWifi()
end,
})
end
return NetworkMgr
|
local ConfirmBox = require("ui/widget/confirmbox")
local UIManager = require("ui/uimanager")
local Device = require("ui/device")
local DEBUG = require("dbg")
local _ = require("gettext")
local NetworkMgr = {}
local function kindleEnableWifi(toggle)
local lipc = require("liblipclua")
local lipc_handle = nil
if lipc then
lipc_handle = lipc.init("com.github.koreader.networkmgr")
end
if lipc_handle then
lipc_handle:set_int_property("com.lab126.cmd", "wirelessEnable", toggle)
lipc_handle:close()
end
end
local function koboEnableWifi(toggle)
if toggle == 1 then
local path = "/etc/wpa_supplicant/wpa_supplicant.conf"
os.execute("insmod /drivers/ntx508/wifi/sdio_wifi_pwr.ko 2>/dev/null")
os.execute("insmod /drivers/ntx508/wifi/dhd.ko")
os.execute("ifconfig eth0 up")
os.execute("wlarm_le -i eth0 up")
os.execute("wpa_supplicant -s -i eth0 -c "..path.." -C /var/run/wpa_supplicant -B")
os.execute("udhcpc -S -i eth0 -s /etc/udhcpc.d/default.script -t15 -T10 -A3 -b -q >/dev/null 2>&1")
else
os.execute("killall udhcpc wpa_supplicant 2>/dev/null")
os.execute("wlarm_le -i eth0 down")
os.execute("ifconfig eth0 down")
os.execute("rmmod -r dhd")
os.execute("rmmod -r sdio_wifi_pwr")
end
end
function NetworkMgr:turnOnWifi()
if Device:isKindle() then
kindleEnableWifi(1)
elseif Device:isKobo() then
koboEnableWifi(1)
end
end
function NetworkMgr:turnOffWifi()
if Device:isKindle() then
kindleEnableWifi(0)
elseif Device:isKobo() then
koboEnableWifi(0)
end
end
function NetworkMgr:promptWifiOn()
UIManager:show(ConfirmBox:new{
text = _("Do you want to Turn on Wifi?"),
ok_callback = function()
self:turnOnWifi()
end,
})
end
function NetworkMgr:promptWifiOff()
UIManager:show(ConfirmBox:new{
text = _("Do you want to Turn off Wifi?"),
ok_callback = function()
self:turnOffWifi()
end,
})
end
return NetworkMgr
|
fix koboEnableWifi
|
fix koboEnableWifi
|
Lua
|
agpl-3.0
|
ashhher3/koreader,frankyifei/koreader,chihyang/koreader,poire-z/koreader,poire-z/koreader,apletnev/koreader,ashang/koreader,koreader/koreader,Hzj-jie/koreader,houqp/koreader,NiLuJe/koreader,noname007/koreader,mihailim/koreader,Frenzie/koreader,chrox/koreader,NickSavage/koreader,NiLuJe/koreader,lgeek/koreader,Markismus/koreader,koreader/koreader,pazos/koreader,Frenzie/koreader,robert00s/koreader,mwoz123/koreader
|
faff8b9847df7686f1640b0f28edf3f3f1696449
|
lib/json.lua
|
lib/json.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local yajl = require('yajl')
local table = require('table')
local JSON = {
null = yajl.null
}
function JSON.parse(string, options)
local root = {}
local current = root
local key
local null = JSON.null
local stack = {}
local null = options and options.use_null and JSON.null
local parser = yajl.newParser({
onNull = function ()
current[key or #current + 1] = null
end,
onBoolean = function (value)
current[key or #current + 1] = value
end,
onNumber = function (value)
current[key or #current + 1] = value
end,
onString = function (value)
current[key or #current + 1] = value
end,
onStartMap = function ()
local new = {}
table.insert(stack, current)
current[key or #current + 1] = new
key = nil
current = new
end,
onMapKey = function (value)
key = value
end,
onEndMap = function ()
key = nil
current = table.remove(stack)
end,
onStartArray = function ()
local new = {}
table.insert(stack, current)
current[key or #current + 1] = new
key = nil
current = new
end,
onEndArray = function ()
current = table.remove(stack)
end
})
if options then
options.use_null = nil
if options then
for k,v in pairs(options) do
parser:config(k, v)
end
end
end
parser:parse(string)
parser:complete()
return unpack(root)
end
function JSON.stringify(value, options)
local generator = yajl.newGenerator();
if options then
for k,v in pairs(options) do
generator:config(k, v)
end
end
function add(o)
local t = type(o)
if t == 'nil' or o == JSON.null then
generator:null()
elseif t == "boolean" then
generator:boolean(o)
elseif t == "number" then
generator:number(o)
elseif t == "string" then
generator:string(o)
elseif t == "table" then
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
if is_array then
generator:arrayOpen()
for i,v in ipairs(o) do
add(v)
end
generator:arrayClose()
else
generator:mapOpen()
for k,v in pairs(o) do
if not (type(k) == "string") then
error("Keys must be strings to stringify as JSON")
end
generator:string(k)
add(v)
end
generator:mapClose()
end
else
error("Cannot stringify " .. type .. " value")
end
end
add(value)
return generator:getBuf()
end
return JSON
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Yajl = require('yajl')
local Table = require('table')
local JSON = {
null = Yajl.null
}
function JSON.streamingParser(callback, options)
local current
local key
local stack = {}
local null = options.use_null and Yajl.null
local function emit(value, open, close)
if current then
current[key or #current + 1] = value
else
callback(value)
end
end
function open(value)
if current then
current[key or #current + 1] = value
end
end
function close(value)
if not current then
callback(value)
end
end
local parser = Yajl.newParser({
onNull = function ()
emit(null)
end,
onBoolean = function (value)
emit(value)
end,
onNumber = function (value)
emit(value)
end,
onString = function (value)
emit(value)
end,
onStartMap = function ()
local new = {}
open(new)
Table.insert(stack, current)
key = nil
current = new
end,
onMapKey = function (value)
key = value
end,
onEndMap = function ()
key = nil
local map = current
current = Table.remove(stack)
close(map)
end,
onStartArray = function ()
local new = {}
open(new)
Table.insert(stack, current)
key = nil
current = new
end,
onEndArray = function ()
local array = current
current = Table.remove(stack)
close(array)
end
})
if options then
options.use_null = nil
if options then
for k,v in pairs(options) do
parser:config(k, v)
end
end
end
return parser
end
function JSON.parse(string, options)
local values = {}
local parser = JSON.streamingParser(function (value)
Table.insert(values, value)
end, options)
parser:parse(string)
parser:complete()
return unpack(values)
end
function JSON.stringify(value, options)
local generator = Yajl.newGenerator();
if options then
for k,v in pairs(options) do
generator:config(k, v)
end
end
function add(o)
local t = type(o)
if t == 'nil' or o == JSON.null then
generator:null()
elseif t == "boolean" then
generator:boolean(o)
elseif t == "number" then
generator:number(o)
elseif t == "string" then
generator:string(o)
elseif t == "table" then
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
if is_array then
generator:arrayOpen()
for i,v in ipairs(o) do
add(v)
end
generator:arrayClose()
else
generator:mapOpen()
for k,v in pairs(o) do
if not (type(k) == "string" or type(k) == "number") then
error("Keys must be strings to stringify as JSON")
end
generator:string(k)
add(v)
end
generator:mapClose()
end
else
error("Cannot stringify " .. type .. " value")
end
end
add(value)
return generator:getBuf()
end
return JSON
|
Fix json to allow encoding numbers as keys. Also add streaming parser helper
|
Fix json to allow encoding numbers as keys. Also add streaming parser helper
|
Lua
|
apache-2.0
|
zhaozg/luvit,rjeli/luvit,boundary/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,DBarney/luvit,connectFree/lev,luvit/luvit,boundary/luvit,zhaozg/luvit,AndrewTsao/luvit,kaustavha/luvit,luvit/luvit,sousoux/luvit,sousoux/luvit,AndrewTsao/luvit,boundary/luvit,AndrewTsao/luvit,boundary/luvit,boundary/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,DBarney/luvit,kaustavha/luvit,bsn069/luvit,sousoux/luvit,boundary/luvit,connectFree/lev,kaustavha/luvit,rjeli/luvit,sousoux/luvit,bsn069/luvit,bsn069/luvit,rjeli/luvit,sousoux/luvit
|
7a9a7c2f08fc15a52bdab5bbcfd633451d439b73
|
home/.hammerspoon/jira.lua
|
home/.hammerspoon/jira.lua
|
-- Requirements and local vars
local utils = require('utils')
local jiraAccount = require ('jiraAccount')
local log = hs.logger.new('init.lua', 'debug')
local jira = {}
-- Returns a Jira URL to browse the given issue Key
function jira.getBrowseUrl(key)
return string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key)
end
-- Type JIRA issue browsing base url
function jira.typeBrowseUrl()
local url = jira.getBrowseUrl(utils.getTrimmedSelectedText())
hs.eventtap.keyStrokes(url)
end
-- Type a JIRA bug template
function jira.typeBugTemplate()
local source=[[
# *Steps to reproduce*
##
##
# *Expected result*
##
##
# *Actual*
##
##
# *Reproducibility*
## 100%
# *Traces*
## File attached foobar.log
## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code}
## !Foobar Sreenshot.png|thumbnail!
# *Extra Information*
##
##
]]
hs.eventtap.keyStrokes(source)
end
-- Search the highlighted selection in Request.jira.com
function jira.search()
local url = jiraAccount.getBaseUrl() .. "issues/?jql=project IN " .. jiraAccount.getDefaultSearchProjects() .. " AND summary ~ \"" .. utils.getTrimmedSelectedText() .. "\" ORDER BY issueKey DESC"
log.f("Searching '%s'", url)
-- TODO: if empty, pop-up a chooser
utils.browseUrl(url)
end
-- Browse the issue key currently highlighted selection, or pop up a chooser
function jira.browseIssue()
local key = utils.getTrimmedSelectedText()
if key == "" then
log.f("browseIssue: no selection: invoking graphical chooser")
lookupJiraIssue()
else
-- Does the key starts with only a digit ?
local c1 = string.sub(key, 1,1)
if string.match(c1, "^%d") ~= nil then
-- Yes: add the default project prefix !
log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix())
key = jiraAccount.getDefaultProjectPrefix() .. key
end
log.f("browseIssue: browse issue '%s'", key)
utils.browseUrl(jira.getBrowseUrl(key))
end
end
-- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua
-- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial)
function createAuthorisationRequestBody()
return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword())
end
function getSession()
log.f("getSession(): entering")
data = createAuthorisationRequestBody()
headers = {["Content-Type"] = "application/json"}
status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers)
log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
result = hs.json.decode(body)
session = result["session"]
return session["name"], session["value"]
else
return nil, nil
end
end
function lookupJiraIssue()
sessionName, sessionValue = getSession()
if (sessionName ~= nil and sessionValue ~= nil) then
log.f("lookupJiraIssue(): got a valid session.")
local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"}
local picker = hs.chooser.new(function(userInput)
if userInput ~= nil then
log.f("chooser: user chose '%s'",userInput)
if userInput["key"] ~= Nil then
local url = jira.getBrowseUrl(userInput["key"])
log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url)
hs.execute("open " .. url)
end
end
end)
picker:query(jiraAccount.getDefaultIssueSearch())
picker:queryChangedCallback(
function(query)
log.f("queryChangedCallback(): query is '%s'", query)
if string.len(query) > 3 then
log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query)
hs.http.asyncGet(
getJiraQueryUrl(query),
cookieHeaders,
function(status, body, headers)
log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
searchResult = hs.json.decode(body)
if searchResult["fields"] ~= nil then
local results = {}
local key = searchResult["key"]
local summary = searchResult["fields"]["summary"]
table.insert(results, {text = key, subText = summary, key = key})
picker:choices(results)
end
end
end
)
else
log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query)
end
end
)
picker:rows(1)
picker:show()
else
log.f("lookupJiraIssue(): could not get a valid session.")
notify = hs.notify.new()
notify:title("Jira")
notify:informativeText("Could not get authorization")
notify:send()
end
end
function getJiraQueryUrl(query)
local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query)
log.f("jiraQuey(): return url '%s'", url)
return url
end
return jira
|
-- Requirements and local vars
local utils = require('utils')
local jiraAccount = require ('jiraAccount')
local log = hs.logger.new('init.lua', 'debug')
local jira = {}
-- Returns a Jira URL to browse the given issue Key
function jira.getBrowseUrl(key)
local url = "";
-- Accordig to the issue key, we use either the base or alt URL
local c2 = string.sub(key, 1, 2)
if string.match(c2, "^" .. jiraAccount.getDefaultProjectPrefix()) ~= nil then
url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key)
else
url = string.format("%s%s%s", jiraAccount.getAltBaseUrl(), "browse/", key)
end
return url -- IRN-23450
end
-- Type JIRA issue browsing base url
function jira.typeBrowseUrl()
local url = jira.getBrowseUrl(utils.getTrimmedSelectedText())
hs.eventtap.keyStrokes(url)
end
-- Type a JIRA bug template
function jira.typeBugTemplate()
local source=[[
# *Steps to reproduce*
##
##
# *Expected result*
##
##
# *Actual*
##
##
# *Reproducibility*
## 100%
# *Traces*
## File attached foobar.log
## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code}
## !Foobar Sreenshot.png|thumbnail!
# *Extra Information*
##
##
]]
hs.eventtap.keyStrokes(source)
end
-- Search the highlighted selection in Request.jira.com
function jira.search()
local url = jiraAccount.getBaseUrl() .. "issues/?jql=project IN " .. jiraAccount.getDefaultSearchProjects() .. " AND summary ~ \"" .. utils.getTrimmedSelectedText() .. "\" ORDER BY issueKey DESC"
log.f("Searching '%s'", url)
-- TODO: if empty, pop-up a chooser
utils.browseUrl(url)
end
-- Browse the issue key currently highlighted selection, or pop up a chooser
function jira.browseIssue()
local key = utils.getTrimmedSelectedText()
if key == "" then
log.f("browseIssue: no selection: invoking graphical chooser")
lookupJiraIssue()
else
-- Does the key starts with only a digit ?
local c1 = string.sub(key, 1, 1)
if string.match(c1, "^%d") ~= nil then
-- Yes: add the default project prefix !
log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix())
key = jiraAccount.getDefaultProjectPrefix() .. key
end
log.f("browseIssue: browse issue '%s'", key)
utils.browseUrl(jira.getBrowseUrl(key))
end
end
-- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua
-- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial)
function createAuthorisationRequestBody()
return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword())
end
function getSession()
log.f("getSession(): entering")
data = createAuthorisationRequestBody()
headers = {["Content-Type"] = "application/json"}
status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers)
log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
result = hs.json.decode(body)
session = result["session"]
return session["name"], session["value"]
else
return nil, nil
end
end
function lookupJiraIssue()
sessionName, sessionValue = getSession()
if (sessionName ~= nil and sessionValue ~= nil) then
log.f("lookupJiraIssue(): got a valid session.")
local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"}
local picker = hs.chooser.new(function(userInput)
if userInput ~= nil then
log.f("chooser: user chose '%s'",userInput)
if userInput["key"] ~= Nil then
local url = jira.getBrowseUrl(userInput["key"])
log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url)
hs.execute("open " .. url)
end
end
end)
picker:query(jiraAccount.getDefaultIssueSearch())
picker:queryChangedCallback(
function(query)
log.f("queryChangedCallback(): query is '%s'", query)
if string.len(query) > 3 then
log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query)
hs.http.asyncGet(
getJiraQueryUrl(query),
cookieHeaders,
function(status, body, headers)
log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers)
if status == 200 then
searchResult = hs.json.decode(body)
if searchResult["fields"] ~= nil then
local results = {}
local key = searchResult["key"]
local summary = searchResult["fields"]["summary"]
table.insert(results, {text = key, subText = summary, key = key})
picker:choices(results)
end
end
end
)
else
log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query)
end
end
)
picker:rows(1)
picker:show()
else
log.f("lookupJiraIssue(): could not get a valid session.")
notify = hs.notify.new()
notify:title("Jira")
notify:informativeText("Could not get authorization")
notify:send()
end
end
function getJiraQueryUrl(query)
local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query)
log.f("jiraQuey(): return url '%s'", url)
return url
end
return jira
|
feat: Can now browse to base or alternative JIRA url, based on default project prefix
|
feat: Can now browse to base or alternative JIRA url, based on default
project prefix
|
Lua
|
mit
|
maanuair/dotfiles,maanuair/dotfiles_tmp
|
b84da68a79738f6e9623bdb76b55e647dd81ab69
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/14_average_min_max.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/14_average_min_max.lua
|
print("Sampling average/min/max: Read AIN1 at set rate for certain number of samples. Outputs average, minimum, and maximum")
--Example program that samples an analog input at a set frequency for a certain number of samples.
--Takes the average, minimum, and maximum of sampled data and prints it to the console as well as saving them to the first 3 addresses of user RAM
--------------------------------------------------------------
--Change scanRate and numScans to achive desired time interval
--Desired sampling time in seconds = numScans/scanRate
--Change the AIN_RESOLUTION_INDEX if faster speeds are desired
--------------------------------------------------------------
local scanRate = 500 --Rate that data will be read in Hz
local numScans = 5000 --number of scans to collect
local mbWrite=MB.W --create local functions for reading/writing at faster speeds
local mbRead=MB.R
mbWrite(48005, 0, 1) --Ensure analog is on
devType = MB.R(60000, 3)
if devType == 7 then--if T7
mbWrite(43903, 0, 8) --set AIN_ALL_RESOLUTION_INDEX to 8 (default is 8 on t7, 9 on PRO)
mbWrite(43900, 3,10) --set range to +-10V
elseif devType == 4 then--if T4
mbWrite(43903, 0, 0) --set AIN_ALL_RESOLUTION_INDEX to Automatic (Usually highest available)
end
local avgData=0
local iter=0
local minV=1000 --set large value so the minimum check sets first value
local maxV=(-1000) --set small value so the maximum check sets first value
LJ.IntervalConfig(0, 1000/scanRate) --Define the scan interval in ms.
local checkInterval=LJ.CheckInterval --create local function to check the interval for faster loop time
print("Estimated time to execute (s): ",numScans/scanRate)
while iter<numScans do --loop as fast as possible until number of scans has been aquired
if checkInterval(0) then --if interval time has been reached, add 1 to iter and take data reading
iter=1+iter
local data0 = mbRead(2,3) --take a reading on the AIN1 line
if(data0>maxV) then --maximum check, sets maxV if data is above previous maxV
maxV=data0
end
if(data0<=minV) then --minimum check, sets minV if data is below previous minV
minV=data0
end
avgData=data0+avgData --add data to previous data readings (divide to get average later)
end
end
local avg=avgData/numScans --divide added data by the number of scans to get average
mbWrite(46000,3,avg) --Write average, min, and max into userRAM
mbWrite(46002,3,maxV)
mbWrite(46004,3,minV)
print("Average voltage: ",avg)
print("Min voltage: ",minV)
print("Max voltage: ",maxV)
|
--[[
Name: 14_average_min_max.lua
Desc: Example program that samples an analog input at a set frequency for a
certain number of samples. It takes the average, minimum, and maximum
of sampled data and prints it to the console as well as saving them
to the first 3 addresses of user RAM
Note: Change scanrate and numscans to achieve a desired time interval
The desired sampling time in seconds = numscans/scanrate
Change the AIN_RESOLUTION_INDEX if faster speeds are desired
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
--]]
print("Sampling average/min/max: Read AIN1 at set rate for certain number of samples. Outputs average, minimum, and maximum")
-- Ensure analog is on
MB.writeName("POWER_AIN", 1)
local devtype = MB.readName("PRODUCT_ID")
-- If using a T7
if devtype == 7 then
-- Set the resolution index to 8 (the default value is 8 on the T7, 9 on the PRO)
MB.writeName("AIN_ALL_RESOLUTION_INDEX", 8)
--set the input voltage range to +-10V
MB.writeName("AIN_ALL_RANGE",10)
-- If using a T4
elseif devtype == 4 then
-- Set the resolution index to Automatic (usually the highest available)
MB.writeName("AIN_ALL_RESOLUTION_INDEX", 0)
end
local alldata = 0
local iter = 0
-- Initialize min to a large value so the first data value is set to min
local minv = 1000
-- Initialize max to a small value so the first data value is set to max
local maxv = -1000
-- The rate that data will be read in Hz
local scanrate = 50
-- The number of scans to collect
local numscans = 5000
-- Configure an interval (in ms) to wait before acquiring new data
LJ.IntervalConfig(0, 1000 / scanrate)
print("Estimated time to execute (s): ",numscans / scanrate)
-- Loop as fast as possible until the desired number of scans have been acquired
while iter < numscans do
-- If an interval is done increase iter and read data from AIN
if LJ.CheckInterval(0) then
iter = 1 + iter
-- Read AIN1
local newdata = MB.readName("AIN1")
-- Check if the new data is the new maximum
if (newdata > maxv) then
maxv = newdata
end
-- Check if the new data is the new minimum
if (newdata <= minv) then
minv = newdata
end
-- Keep a summation of all acquired data in order to get an average later
alldata = newdata + alldata
end
end
-- Calculate the average of all of the acquired data
local avg = alldata / numscans
-- Write the average, min, and max values to USER RAM
MB.writeName("USER_RAM0_F32",avg)
MB.writeName("USER_RAM1_F32",maxv)
MB.writeName("USER_RAM2_F32",minv)
print("Average voltage: ",avg)
print("Min voltage: ",minv)
print("Max voltage: ",maxv)
print("")
print("Stopping script")
-- Writing 0 to LUA_RUN stops the script
MB.writeName("LUA_RUN", 0)
|
Fixed up the formatting of the AIN average, min, max example
|
Fixed up the formatting of the AIN average, min, max example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
79c52bed8ac40529d79671cdc2dc17cf707e6e86
|
third_party/bullet/premake5.lua
|
third_party/bullet/premake5.lua
|
dofile("../../tools/premake/options.lua")
dofile("../../tools/premake/globals.lua")
link_cmd = ""
build_cmd = ""
solution "bullet_build"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
-- Project
project "bullet_monolithic"
setup_env()
location ("build\\" .. platform_dir)
kind "StaticLib"
language "C++"
includedirs
{
"src\\",
}
if _ACTION == "vs2017" or _ACTION == "vs2015" or ACTION == "vs2019" then
systemversion(windows_sdk_version())
disablewarnings { "4267", "4305", "4244" }
end
setup_env()
files
{
"src\\Bullet3Collision\\**.*",
"src\\Bullet3Common\\**.*",
"src\\Bullet3Dynamics\\**.*",
"src\\Bullet3Geometry\\**.*",
"src\\Bullet3Serialize\\**.*",
"src\\BulletDynamics\\**.*",
"src\\BulletCollision\\**.*",
"src\\LinearMath\\**.*",
}
includedirs { "include" }
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
linkoptions { link_cmd }
buildoptions { build_cmd }
symbols "On"
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic_d"
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
linkoptions { link_cmd }
buildoptions { build_cmd }
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic"
|
dofile("../../tools/premake/options.lua")
dofile("../../tools/premake/globals.lua")
link_cmd = ""
build_cmd = ""
if platform_dir == "osx" then
xcodebuildsettings {
["MACOSX_DEPLOYMENT_TARGET"] = "10.13"
}
end
solution "bullet_build"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
-- Project
project "bullet_monolithic"
setup_env()
location ("build\\" .. platform_dir)
kind "StaticLib"
language "C++"
includedirs
{
"src\\",
}
if _ACTION == "vs2017" or _ACTION == "vs2015" or ACTION == "vs2019" then
systemversion(windows_sdk_version())
disablewarnings { "4267", "4305", "4244" }
end
setup_env()
files
{
"src\\Bullet3Collision\\**.*",
"src\\Bullet3Common\\**.*",
"src\\Bullet3Dynamics\\**.*",
"src\\Bullet3Geometry\\**.*",
"src\\Bullet3Serialize\\**.*",
"src\\BulletDynamics\\**.*",
"src\\BulletCollision\\**.*",
"src\\LinearMath\\**.*",
}
includedirs { "include" }
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
linkoptions { link_cmd }
buildoptions { build_cmd }
symbols "On"
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic_d"
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
linkoptions { link_cmd }
buildoptions { build_cmd }
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic"
|
- fix warning
|
- fix warning
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
2392842948b114670334eabbb593b66e1427747c
|
mods/fire/init.lua
|
mods/fire/init.lua
|
-- minetest/fire/init.lua
fire = {}
minetest.register_node("fire:basic_flame", {
description = "Fire",
drawtype = "firelike",
tiles = {{
name="fire_basic_flame_animated.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=1},
}},
inventory_image = "fire_basic_flame.png",
light_source = 14,
groups = {igniter=2,dig_immediate=3},
drop = '',
walkable = false,
buildable_to = true,
damage_per_second = 4,
on_construct = function(pos)
minetest.after(0, fire.on_flame_add_at, pos)
end,
on_destruct = function(pos)
minetest.after(0, fire.on_flame_remove_at, pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
fire.D = 6
-- key: position hash of low corner of area
-- value: {handle=sound handle, name=sound name}
fire.sounds = {}
function fire.get_area_p0p1(pos)
local p0 = {
x=math.floor(pos.x/fire.D)*fire.D,
y=math.floor(pos.y/fire.D)*fire.D,
z=math.floor(pos.z/fire.D)*fire.D,
}
local p1 = {
x=p0.x+fire.D-1,
y=p0.y+fire.D-1,
z=p0.z+fire.D-1
}
return p0, p1
end
function fire.update_sounds_around(pos)
local p0, p1 = fire.get_area_p0p1(pos)
local cp = {x=(p0.x+p1.x)/2, y=(p0.y+p1.y)/2, z=(p0.z+p1.z)/2}
local flames_p = minetest.find_nodes_in_area(p0, p1, {"fire:basic_flame"})
--print("number of flames at "..minetest.pos_to_string(p0).."/"
-- ..minetest.pos_to_string(p1)..": "..#flames_p)
local should_have_sound = (#flames_p > 0)
local wanted_sound = nil
if #flames_p >= 9 then
wanted_sound = {name="fire_large", gain=1.5}
elseif #flames_p > 0 then
wanted_sound = {name="fire_small", gain=1.5}
end
local p0_hash = minetest.hash_node_position(p0)
local sound = fire.sounds[p0_hash]
if not sound then
if should_have_sound then
fire.sounds[p0_hash] = {
handle = minetest.sound_play(wanted_sound, {pos=cp, max_hear_distance = 16, loop=true}),
name = wanted_sound.name,
}
end
else
if not wanted_sound then
minetest.sound_stop(sound.handle)
fire.sounds[p0_hash] = nil
elseif sound.name ~= wanted_sound.name then
minetest.sound_stop(sound.handle)
fire.sounds[p0_hash] = {
handle = minetest.sound_play(wanted_sound, {pos=cp, max_hear_distance = 16, loop=true}),
name = wanted_sound.name,
}
end
end
end
function fire.on_flame_add_at(pos)
fire.update_sounds_around(pos)
end
function fire.on_flame_remove_at(pos)
fire.update_sounds_around(pos)
end
function fire.find_pos_for_flame_around(pos)
return minetest.find_node_near(pos, 1, {"air"})
end
function fire.flame_should_extinguish(pos)
if minetest.setting_getbool("disable_fire") then return true end
--return minetest.find_node_near(pos, 1, {"group:puts_out_fire"})
local p0 = {x=pos.x-2, y=pos.y, z=pos.z-2}
local p1 = {x=pos.x+2, y=pos.y, z=pos.z+2}
local ps = minetest.find_nodes_in_area(p0, p1, {"group:puts_out_fire"})
return (#ps ~= 0)
end
-- Ignite neighboring nodes
minetest.register_abm({
nodenames = {"group:flammable"},
neighbors = {"group:igniter"},
interval = 5,
chance = 2,
action = function(p0, node, _, _)
-- If there is water or stuff like that around flame, don't ignite
if fire.flame_should_extinguish(p0) then
return
end
local p = fire.find_pos_for_flame_around(p0)
if p then
minetest.set_node(p, {name="fire:basic_flame"})
end
end,
})
-- Rarely ignite things from far
minetest.register_abm({
nodenames = {"group:igniter"},
neighbors = {"air"},
interval = 5,
chance = 10,
action = function(p0, node, _, _)
local reg = minetest.registered_nodes[node.name]
if not reg or not reg.groups.igniter or reg.groups.igniter < 2 then
return
end
local d = reg.groups.igniter
local p = minetest.find_node_near(p0, d, {"group:flammable"})
if p then
-- If there is water or stuff like that around flame, don't ignite
if fire.flame_should_extinguish(p) then
return
end
local p2 = fire.find_pos_for_flame_around(p)
if p2 then
minetest.set_node(p2, {name="fire:basic_flame"})
end
end
end,
})
-- Remove flammable nodes and flame
minetest.register_abm({
nodenames = {"fire:basic_flame"},
interval = 3,
chance = 2,
action = function(p0, node, _, _)
-- If there is water or stuff like that around flame, remove flame
if fire.flame_should_extinguish(p0) then
minetest.remove_node(p0)
return
end
-- Make the following things rarer
if math.random(1,3) == 1 then
return
end
-- If there are no flammable nodes around flame, remove flame
if not minetest.find_node_near(p0, 1, {"group:flammable"}) then
minetest.remove_node(p0)
return
end
if math.random(1,4) == 1 then
-- remove a flammable node around flame
local p = minetest.find_node_near(p0, 1, {"group:flammable"})
if p then
-- If there is water or stuff like that around flame, don't remove
if fire.flame_should_extinguish(p0) then
return
end
minetest.remove_node(p)
nodeupdate(p)
end
else
-- remove flame
minetest.remove_node(p0)
end
end,
})
|
-- minetest/fire/init.lua
-- Global namespace for functions
fire = {}
-- Register flame node
minetest.register_node("fire:basic_flame", {
description = "Fire",
drawtype = "firelike",
tiles = {{
name = "fire_basic_flame_animated.png",
animation = {type = "vertical_frames",
aspect_w = 16, aspect_h = 16, length = 1},
}},
inventory_image = "fire_basic_flame.png",
light_source = 14,
groups = {igniter = 2, dig_immediate = 3},
drop = '',
walkable = false,
buildable_to = true,
damage_per_second = 4,
on_construct = function(pos)
minetest.after(0, fire.on_flame_add_at, pos)
end,
on_destruct = function(pos)
minetest.after(0, fire.on_flame_remove_at, pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
-- Fire sounds table
-- key: position hash of low corner of area
-- value: {handle=sound handle, name=sound name}
fire.sounds = {}
-- Get sound area of position
-- size of sound areas
fire.D = 6
function fire.get_area_p0p1(pos)
local p0 = {
x = math.floor(pos.x / fire.D) * fire.D,
y = math.floor(pos.y / fire.D) * fire.D,
z = math.floor(pos.z / fire.D) * fire.D,
}
local p1 = {
x = p0.x + fire.D - 1,
y = p0.y + fire.D - 1,
z = p0.z + fire.D - 1
}
return p0, p1
end
-- Update fire sounds in sound area of position
function fire.update_sounds_around(pos)
local p0, p1 = fire.get_area_p0p1(pos)
local cp = {x = (p0.x + p1.x) / 2, y = (p0.y + p1.y) / 2, z = (p0.z + p1.z) / 2}
local flames_p = minetest.find_nodes_in_area(p0, p1, {"fire:basic_flame"})
--print("number of flames at "..minetest.pos_to_string(p0).."/"
-- ..minetest.pos_to_string(p1)..": "..#flames_p)
local should_have_sound = (#flames_p > 0)
local wanted_sound = nil
if #flames_p >= 9 then
wanted_sound = {name = "fire_large", gain = 1.5}
elseif #flames_p > 0 then
wanted_sound = {name = "fire_small", gain = 1.5}
end
local p0_hash = minetest.hash_node_position(p0)
local sound = fire.sounds[p0_hash]
if not sound then
if should_have_sound then
fire.sounds[p0_hash] = {
handle = minetest.sound_play(wanted_sound,
{pos = cp, max_hear_distance = 16, loop = true}),
name = wanted_sound.name,
}
end
else
if not wanted_sound then
minetest.sound_stop(sound.handle)
fire.sounds[p0_hash] = nil
elseif sound.name ~= wanted_sound.name then
minetest.sound_stop(sound.handle)
fire.sounds[p0_hash] = {
handle = minetest.sound_play(wanted_sound,
{pos = cp, max_hear_distance = 16, loop = true}),
name = wanted_sound.name,
}
end
end
end
-- Update fire sounds on flame node construct or destruct
function fire.on_flame_add_at(pos)
fire.update_sounds_around(pos)
end
function fire.on_flame_remove_at(pos)
fire.update_sounds_around(pos)
end
-- Return positions for flames around a burning node
function fire.find_pos_for_flame_around(pos)
return minetest.find_node_near(pos, 1, {"air"})
end
-- Detect nearby extinguishing nodes
function fire.flame_should_extinguish(pos)
if minetest.setting_getbool("disable_fire") then return true end
--return minetest.find_node_near(pos, 1, {"group:puts_out_fire"})
local p0 = {x = pos.x - 1, y = pos.y, z = pos.z - 1}
local p1 = {x = pos.x + 1, y = pos.y + 1, z = pos.z + 1}
local ps = minetest.find_nodes_in_area(p0, p1, {"group:puts_out_fire"})
return (#ps ~= 0)
end
-- Ignite neighboring nodes
minetest.register_abm({
nodenames = {"group:flammable"},
neighbors = {"group:igniter"},
interval = 7,
chance = 32,
action = function(p0, node, _, _)
-- If there is water or stuff like that around flame, don't ignite
if fire.flame_should_extinguish(p0) then
return
end
local p = fire.find_pos_for_flame_around(p0)
if p then
minetest.set_node(p, {name = "fire:basic_flame"})
end
end,
})
-- Rarely ignite things from far
--[[ Currently disabled to reduce the chance of uncontrollable spreading
fires that disrupt servers. Also for less lua processing load.
minetest.register_abm({
nodenames = {"group:igniter"},
neighbors = {"air"},
interval = 5,
chance = 10,
action = function(p0, node, _, _)
local reg = minetest.registered_nodes[node.name]
if not reg or not reg.groups.igniter or reg.groups.igniter < 2 then
return
end
local d = reg.groups.igniter
local p = minetest.find_node_near(p0, d, {"group:flammable"})
if p then
-- If there is water or stuff like that around flame, don't ignite
if fire.flame_should_extinguish(p) then
return
end
local p2 = fire.find_pos_for_flame_around(p)
if p2 then
minetest.set_node(p2, {name = "fire:basic_flame"})
end
end
end,
})
--]]
-- Remove flammable nodes and flame
minetest.register_abm({
nodenames = {"fire:basic_flame"},
interval = 5,
chance = 16,
action = function(p0, node, _, _)
-- If there is water or stuff like that around flame, remove flame
if fire.flame_should_extinguish(p0) then
minetest.remove_node(p0)
return
end
-- Make the following things rarer
if math.random(1, 3) == 1 then
return
end
-- If there are no flammable nodes around flame, remove flame
if not minetest.find_node_near(p0, 1, {"group:flammable"}) then
minetest.remove_node(p0)
return
end
if math.random(1, 4) == 1 then
-- remove a flammable node around flame
local p = minetest.find_node_near(p0, 1, {"group:flammable"})
if p then
-- If there is water or stuff like that around flame, don't remove
if fire.flame_should_extinguish(p0) then
return
end
minetest.remove_node(p)
nodeupdate(p)
end
else
-- remove flame
minetest.remove_node(p0)
end
end,
})
|
Fire: Slow down fire spread and reduce lua load
|
Fire: Slow down fire spread and reduce lua load
Increase chance value of ABMs
Disable ignition from a distance
Only detect neighbouring extinguishing nodes
Fix code style issues and add comments
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
99a9b49f81b52268899e4911893e5693c855ae89
|
lib/utils/parallel.lua
|
lib/utils/parallel.lua
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local Parallel = {
gpus = {0},
_pool = nil,
count = 1,
gradBuffer = torch.Tensor()
}
-- Synchronizes the current stream on dst device with src device. This is only
-- necessary if we are not on the default stream
local function waitForDevice(dst, src)
local stream = cutorch.getStream()
if stream ~= 0 then
cutorch.streamWaitForMultiDevice(dst, stream, { [src] = {stream} })
end
end
function Parallel.init(args)
if utils.Cuda.activated then
Parallel.count = args.nparallel
Parallel.gpus = utils.Cuda.getGPUs(args.nparallel)
Parallel.gradBuffer = utils.Cuda.convert(Parallel.gradBuffer)
if Parallel.count > 1 then
print('Using ' .. Parallel.count .. ' threads on ' .. #Parallel.gpus .. ' GPUs')
local threads = require 'threads'
threads.Threads.serialization('threads.sharedserialize')
local thegpus = Parallel.gpus
Parallel._pool = threads.Threads(
Parallel.count,
function(threadid)
require 'cunn'
require 'nngraph'
require('lib.utils.init')
require('lib.train.init')
require('lib.onmt.init')
require('lib.data')
utils.Cuda.init(args, thegpus[threadid])
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
if Parallel.count > 1 and not(args.no_nccl) then
-- check if we have nccl installed
local ret
ret, Parallel.usenccl = pcall(require, 'nccl')
if not ret then
print("WARNING: for improved efficiency in nparallel mode - do install nccl")
elseif os.getenv('CUDA_LAUNCH_BLOCKING') == '1' then
print("WARNING: CUDA_LAUNCH_BLOCKING set - cannot use nccl")
end
Parallel.usenccl = nil
end
end
end
function Parallel.getGPU(i)
if utils.Cuda.activated and Parallel.gpus[i] ~= 0 then
return Parallel.gpus[i]
end
return 0
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(label, closure, endcallback)
endcallback = endcallback or function() end
if label ~= nil then
print("START",label)
end
for j = 1, Parallel.count do
if Parallel._pool == nil then
endcallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endcallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
if label ~= nil then
print("DONE",label)
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(grad_params, batches)
if Parallel.count > 1 then
for h = 1, #grad_params[1] do
local inputs = { grad_params[1][h] }
for j = 2, #batches do
if not Parallel.usenccl then
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- Synchronize before and after copy to ensure that it doesn't overlap
-- with this add or previous adds
waitForDevice(Parallel.gpus[j], Parallel.gpus[1])
local remoteGrads = utils.Tensor.reuseTensor(Parallel.gradBuffer, grad_params[j][h]:size())
remoteGrads:copy(grad_params[j][h])
waitForDevice(Parallel.gpus[1], Parallel.gpus[j])
grad_params[1][h]:add(remoteGrads)
else
table.insert(inputs, grad_params[j][h])
end
end
if Parallel.usenccl then
Parallel.usenccl.reduce(inputs, nil, true)
end
end
end
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
if Parallel.count > 1 then
if not Parallel.usenccl then
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
waitForDevice(Parallel.gpus[j], Parallel.gpus[1])
end
else
for h = 1, #params[1] do
local inputs = { params[1][h] }
for j = 2, Parallel.count do
table.insert(inputs, params[j][h])
end
Parallel.usenccl.bcast(inputs, true, 1)
end
end
end
end
return Parallel
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local Parallel = {
gpus = {0},
_pool = nil,
count = 1,
gradBuffer = torch.Tensor()
}
-- Synchronizes the current stream on dst device with src device. This is only
-- necessary if we are not on the default stream
local function waitForDevice(dst, src)
local stream = cutorch.getStream()
if stream ~= 0 then
cutorch.streamWaitForMultiDevice(dst, stream, { [src] = {stream} })
end
end
function Parallel.init(args)
if utils.Cuda.activated then
Parallel.count = args.nparallel
Parallel.gpus = utils.Cuda.getGPUs(args.nparallel)
Parallel.gradBuffer = utils.Cuda.convert(Parallel.gradBuffer)
if Parallel.count > 1 then
print('Using ' .. Parallel.count .. ' threads on ' .. #Parallel.gpus .. ' GPUs')
local threads = require 'threads'
threads.Threads.serialization('threads.sharedserialize')
local thegpus = Parallel.gpus
Parallel._pool = threads.Threads(
Parallel.count,
function(threadid)
require 'cunn'
require 'nngraph'
require('lib.utils.init')
require('lib.train.init')
require('lib.onmt.init')
require('lib.data')
utils.Cuda.init(args, thegpus[threadid])
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
if Parallel.count > 1 and not(args.no_nccl) then
-- check if we have nccl installed
local ret
ret, Parallel.usenccl = pcall(require, 'nccl')
if not ret then
print("WARNING: for improved efficiency in nparallel mode - do install nccl")
Parallel.usenccl = nil
elseif os.getenv('CUDA_LAUNCH_BLOCKING') == '1' then
print("WARNING: CUDA_LAUNCH_BLOCKING set - cannot use nccl")
Parallel.usenccl = nil
end
end
end
end
function Parallel.getGPU(i)
if utils.Cuda.activated and Parallel.gpus[i] ~= 0 then
return Parallel.gpus[i]
end
return 0
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(label, closure, endcallback)
endcallback = endcallback or function() end
if label ~= nil then
print("START",label)
end
for j = 1, Parallel.count do
if Parallel._pool == nil then
endcallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endcallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
if label ~= nil then
print("DONE",label)
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(grad_params, batches)
if Parallel.count > 1 then
for h = 1, #grad_params[1] do
local inputs = { grad_params[1][h] }
for j = 2, #batches do
if not Parallel.usenccl then
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- Synchronize before and after copy to ensure that it doesn't overlap
-- with this add or previous adds
waitForDevice(Parallel.gpus[j], Parallel.gpus[1])
local remoteGrads = utils.Tensor.reuseTensor(Parallel.gradBuffer, grad_params[j][h]:size())
remoteGrads:copy(grad_params[j][h])
waitForDevice(Parallel.gpus[1], Parallel.gpus[j])
grad_params[1][h]:add(remoteGrads)
else
table.insert(inputs, grad_params[j][h])
end
end
if Parallel.usenccl then
Parallel.usenccl.reduce(inputs, nil, true)
end
end
end
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
if Parallel.count > 1 then
if not Parallel.usenccl then
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
waitForDevice(Parallel.gpus[j], Parallel.gpus[1])
end
else
for h = 1, #params[1] do
local inputs = { params[1][h] }
for j = 2, Parallel.count do
table.insert(inputs, params[j][h])
end
Parallel.usenccl.bcast(inputs, true, 1)
end
end
end
end
return Parallel
|
fix nccl that was always disabled
|
fix nccl that was always disabled
|
Lua
|
mit
|
monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,srush/OpenNMT,da03/OpenNMT,cservan/OpenNMT_scores_0.2.0,monsieurzhang/OpenNMT
|
5808b647c3ae9faf0b9c1dfcf0edbc7dff1e0874
|
lib/utils/parallel.lua
|
lib/utils/parallel.lua
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local cuda = require 'lib.utils.cuda'
local Parallel = {
gpus = {0},
_pool = nil,
count = 1
}
function Parallel.init(args)
if cuda.activated then
Parallel.count = args.nparallel
Parallel.gpus = cuda.getGPUs(args.nparallel)
if Parallel.count > 1 then
local threads = require 'threads'
threads.Threads.serialization('threads.sharedserialize')
local thegpus = Parallel.gpus
Parallel._pool = threads.Threads(
Parallel.count,
function(threadid)
require 'cunn'
require 'nngraph'
require('lib.utils.init')
require('lib.train.init')
require('lib.onmt.init')
Data = require('lib.data')
print('STARTING THREAD ', threadid, 'on GPU ' .. thegpus[threadid])
utils.Cuda.init(args, thegpus[threadid])
local refprint = print
print=function(...) refprint('[THREAD'..threadid..']',...) end
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
else
Parallel._G = {}
Parallel._G.Decoder = require 's2sa.decoder'
Parallel._G.Encoder = require 's2sa.encoder'
Parallel._G.Generator = require 's2sa.generator'
end
end
end
function Parallel.getGPU(i)
if cuda.activated and Parallel.gpus[i] ~= 0 then
return Parallel.gpus[i]
end
return 0
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(label, closure, endcallback)
endcallback = endcallback or function() end
if label ~= nil then
print("START",label)
end
for j = 1, Parallel.count do
if Parallel._pool == nil then
local _G = Parallel._G
endcallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endcallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
if label ~= nil then
print("DONE",label)
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(grad_params)
-- local freeMemory = cutorch.cutorch.getMemoryUsage(cutorch.getDevice())
for h = 1, #grad_params[1] do
for j = 2, Parallel.count do
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- also it is possible to optmize using nccl
local remote_grad_params=grad_params[j][h]:clone()
grad_params[1][h]:add(remote_grad_params)
end
end
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
end
end
return Parallel
|
--[[
This file provides generic parallel class - allowing to run functions
in different threads and on different GPU
]]--
local cuda = require 'lib.utils.cuda'
local Parallel = {
gpus = {0},
_pool = nil,
count = 1
}
function Parallel.init(args)
if cuda.activated then
Parallel.count = args.nparallel
Parallel.gpus = cuda.getGPUs(args.nparallel)
if Parallel.count > 1 then
local threads = require 'threads'
threads.Threads.serialization('threads.sharedserialize')
local thegpus = Parallel.gpus
Parallel._pool = threads.Threads(
Parallel.count,
function(threadid)
require 'cunn'
require 'nngraph'
require('lib.utils.init')
require('lib.train.init')
require('lib.onmt.init')
Data = require('lib.data')
print('STARTING THREAD ', threadid, 'on GPU ' .. thegpus[threadid])
utils.Cuda.init(args, thegpus[threadid])
local refprint = print
print=function(...) refprint('[THREAD'..threadid..']',...) end
end
) -- dedicate threads to GPUs
Parallel._pool:specific(true)
end
end
end
function Parallel.getGPU(i)
if cuda.activated and Parallel.gpus[i] ~= 0 then
return Parallel.gpus[i]
end
return 0
end
--[[ Launch function in parallel on different threads. ]]
function Parallel.launch(label, closure, endcallback)
endcallback = endcallback or function() end
if label ~= nil then
print("START",label)
end
for j = 1, Parallel.count do
if Parallel._pool == nil then
local _G = Parallel._G
endcallback(closure(j))
else
Parallel._pool:addjob(j, function() return closure(j) end, endcallback)
end
end
if Parallel._pool then
Parallel._pool:synchronize()
end
if label ~= nil then
print("DONE",label)
end
end
--[[ Accumulate the gradient parameters from the different parallel threads. ]]
function Parallel.accGradParams(grad_params)
-- local freeMemory = cutorch.cutorch.getMemoryUsage(cutorch.getDevice())
for h = 1, #grad_params[1] do
for j = 2, Parallel.count do
-- TODO - this is memory costly since we need to clone full parameters from one GPU to another
-- to avoid out-of-memory, we can copy/add by batch
-- also it is possible to optmize using nccl
local remote_grad_params=grad_params[j][h]:clone()
grad_params[1][h]:add(remote_grad_params)
end
end
end
--[[ Sync parameters from main model to different parallel threads. ]]
function Parallel.syncParams(params)
for j = 2, Parallel.count do
for h = 1, #params[1] do
params[j][h]:copy(params[1][h])
end
end
end
return Parallel
|
fix single-thread training
|
fix single-thread training
|
Lua
|
mit
|
monsieurzhang/OpenNMT,da03/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,cservan/OpenNMT_scores_0.2.0,srush/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT
|
9d8f7086e1f469a24b032307b43dc801fe10fd92
|
packages/rules.lua
|
packages/rules.lua
|
SILE.baseClass:loadPackage("raiselower")
SILE.baseClass:loadPackage("rebox")
SILE.registerCommand("hrule", function (options, _)
local width = SU.cast("length", options.width)
local height = SU.cast("length", options.height)
local depth = SU.cast("length", options.depth)
SILE.typesetter:pushHbox({
width = width:absolute(),
height = height:absolute(),
depth = depth:absolute(),
value = options.src,
outputYourself= function (self, typesetter, line)
local outputWidth = SU.rationWidth(self.width, self.width, line.ratio)
typesetter.frame:advancePageDirection(-self.height)
local oldx = typesetter.frame.state.cursorX
local oldy = typesetter.frame.state.cursorY
typesetter.frame:advanceWritingDirection(outputWidth)
typesetter.frame:advancePageDirection(self.height + self.depth)
local newx = typesetter.frame.state.cursorX
local newy = typesetter.frame.state.cursorY
SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy)
end
})
end, "Creates a line of width <width> and height <height>")
SILE.registerCommand("fullrule", function (options, _)
SILE.call("raise", { height = options.raise or "0.5em" }, function ()
SILE.call("hrule", {
height = options.height or "0.2pt",
width = options.width or "100%lw"
})
end)
end, "Draw a full width hrule centered on the current line")
SILE.registerCommand("underline", function (_, content)
local ot = SILE.require("core/opentype-parser")
local fontoptions = SILE.font.loadDefaults({})
local face = SILE.font.cache(fontoptions, SILE.shaper.getFace)
local font = ot.parseFont(face)
local upem = font.head.unitsPerEm
local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size
local underlineThickness = font.post.underlineThickness / upem * fontoptions.size
local hbox = SILE.call("hbox", {}, content)
table.remove(SILE.typesetter.state.nodes) -- steal it back...
-- Re-wrap the hbox in another hbox responsible for boxing it at output
-- time, when we will know the line contribution and can compute the scaled width
-- of the box, taking into account possible stretching and shrinking.
SILE.typesetter:pushHbox({
inner = hbox,
width = hbox.width,
height = hbox.height,
depth = hbox.depth,
outputYourself = function(self, typesetter, line)
local oldX = typesetter.frame.state.cursorX
local Y = typesetter.frame.state.cursorY
-- Build the original hbox.
-- Cursor will be moved by the actual definitive size.
self.inner:outputYourself(SILE.typesetter, line)
local newX = typesetter.frame.state.cursorX
-- Output a line.
-- NOTE: According to the OpenType specs, underlinePosition is "the suggested distance of
-- the top of the underline from the baseline" so it seems implied that the thickness
-- should expand downwards
SILE.outputter:drawRule(oldX, Y + underlinePosition, newX - oldX, underlineThickness)
end
})
end, "Underlines some content")
SILE.registerCommand("boxaround", function (_, content)
local hbox = SILE.call("hbox", {}, content)
local gl = SILE.length() - hbox.width
SILE.call("rebox", {width = 0}, function()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("raise", {height = hbox.height}, function ()
SILE.call("hrule", {width = gl.length-1, height = "0.5pt"})
end)
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
SILE.typesetter:pushGlue({width = hbox.width})
SILE.call("hrule", { height = hbox.height, width = "0.5pt"})
end, "Draws a box around some content")
return { documentation = [[\begin{document}
The \code{rules} package draws lines. It provides three commands.
The first command is \code{\\hrule},
which draws a line of a given length and thickness, although it calls these
\code{width} and \code{height}. (A box is just a square line.)
Lines are treated just like other text to be output, and so can appear in the
middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one
was generated with \code{\\hrule[width=20pt, height=0.5pt]}.)
Like images, rules are placed along the baseline of a line of text.
The second command provided by \code{rules} is \code{\\underline}, which
underlines its contents.
\note{
Underlining is horrible typographic practice, and
you should \underline{never} do it.}
(That was produced with \code{\\underline\{never\}}.)
Finally, \code{fullrule} draws a thin line across the width of the current frame.
\end{document}]] }
|
SILE.baseClass:loadPackage("raiselower")
SILE.baseClass:loadPackage("rebox")
SILE.registerCommand("hrule", function (options, _)
local width = SU.cast("length", options.width)
local height = SU.cast("length", options.height)
local depth = SU.cast("length", options.depth)
SILE.typesetter:pushHbox({
width = width:absolute(),
height = height:absolute(),
depth = depth:absolute(),
value = options.src,
outputYourself= function (self, typesetter, line)
local outputWidth = SU.rationWidth(self.width, self.width, line.ratio)
typesetter.frame:advancePageDirection(-self.height)
local oldx = typesetter.frame.state.cursorX
local oldy = typesetter.frame.state.cursorY
typesetter.frame:advanceWritingDirection(outputWidth)
typesetter.frame:advancePageDirection(self.height + self.depth)
local newx = typesetter.frame.state.cursorX
local newy = typesetter.frame.state.cursorY
SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy)
end
})
end, "Creates a line of width <width> and height <height>")
SILE.registerCommand("fullrule", function (options, _)
SILE.call("raise", { height = options.raise or "0.5em" }, function ()
SILE.call("hrule", {
height = options.height or "0.2pt",
width = options.width or "100%lw"
})
end)
end, "Draw a full width hrule centered on the current line")
SILE.registerCommand("underline", function (_, content)
local ot = SILE.require("core/opentype-parser")
local fontoptions = SILE.font.loadDefaults({})
local face = SILE.font.cache(fontoptions, SILE.shaper.getFace)
local font = ot.parseFont(face)
local upem = font.head.unitsPerEm
local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size
local underlineThickness = font.post.underlineThickness / upem * fontoptions.size
local hbox = SILE.call("hbox", {}, content)
table.remove(SILE.typesetter.state.nodes) -- steal it back...
-- Re-wrap the hbox in another hbox responsible for boxing it at output
-- time, when we will know the line contribution and can compute the scaled width
-- of the box, taking into account possible stretching and shrinking.
SILE.typesetter:pushHbox({
inner = hbox,
width = hbox.width,
height = hbox.height,
depth = hbox.depth,
outputYourself = function(self, typesetter, line)
local oldX = typesetter.frame.state.cursorX
local Y = typesetter.frame.state.cursorY
-- Build the original hbox.
-- Cursor will be moved by the actual definitive size.
self.inner:outputYourself(SILE.typesetter, line)
local newX = typesetter.frame.state.cursorX
-- Output a line.
-- NOTE: According to the OpenType specs, underlinePosition is "the suggested distance of
-- the top of the underline from the baseline" so it seems implied that the thickness
-- should expand downwards
SILE.outputter:drawRule(oldX, Y + underlinePosition, newX - oldX, underlineThickness)
end
})
end, "Underlines some content")
SILE.registerCommand("boxaround", function (_, content)
local hbox = SILE.call("hbox", {}, content)
table.remove(SILE.typesetter.state.nodes) -- steal it back...
-- Re-wrap the hbox in another hbox responsible for boxing it at output
-- time, when we will know the line contribution and can compute the scaled width
-- of the box, taking into account possible stretching and shrinking.
SILE.typesetter:pushHbox({
inner = hbox,
width = hbox.width,
height = hbox.height,
depth = hbox.depth,
outputYourself = function(self, typesetter, line)
local oldX = typesetter.frame.state.cursorX
local Y = typesetter.frame.state.cursorY
-- Build the original hbox.
-- Cursor will be moved by the actual definitive size.
self.inner:outputYourself(SILE.typesetter, line)
local newX = typesetter.frame.state.cursorX
-- Output a border
-- NOTE: Drawn inside the hbox, so borders overlap with inner content.
local w = newX - oldX
local h = self.height:tonumber()
local d = self.depth:tonumber()
local thickness = 0.5
SILE.outputter:drawRule(oldX, Y + d - thickness, w, thickness)
SILE.outputter:drawRule(oldX, Y - h, w, thickness)
SILE.outputter:drawRule(oldX, Y - h, thickness, h + d)
SILE.outputter:drawRule(oldX + w - thickness, Y - h, thickness, h + d)
end
})
end, "Draws a box around some content")
return { documentation = [[\begin{document}
The \code{rules} package draws lines. It provides three commands.
The first command is \code{\\hrule},
which draws a line of a given length and thickness, although it calls these
\code{width} and \code{height}. (A box is just a square line.)
Lines are treated just like other text to be output, and so can appear in the
middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one
was generated with \code{\\hrule[width=20pt, height=0.5pt]}.)
Like images, rules are placed along the baseline of a line of text.
The second command provided by \code{rules} is \code{\\underline}, which
underlines its contents.
\note{
Underlining is horrible typographic practice, and
you should \underline{never} do it.}
(That was produced with \code{\\underline\{never\}}.)
Finally, \code{fullrule} draws a thin line across the width of the current frame.
\end{document}]] }
|
fix(packages): Make boxaround respect shrink/strech (rules package)
|
fix(packages): Make boxaround respect shrink/strech (rules package)
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.