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
3ec5522d0666095da61915b29b0661aa8ea705e8
mods/broomstick/init.lua
mods/broomstick/init.lua
local broomstick_time = 120 -- Seconds (for default 2 minutes) local broomstick_mana = 210 local broomstick_actual_users = {} local had_fly_privilege = {} local privs = {} -- Register broomstick minetest.register_craftitem("broomstick:broomstick", { description = "Broomstick", inventory_image = "broomstick.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) local playername = user:get_player_name() if mana.get(playername) >= broomstick_mana then local has_already_a_broomstick = false for _, i in ipairs(broomstick_actual_users) do if i.name == playername then has_already_a_broomstick = true end end if not has_already_a_broomstick then privs = minetest.get_player_privs(playername) -- Set player privs... if not privs.fly == true then privs.fly = true minetest.set_player_privs(playername, privs) else minetest.chat_send_player(playername, "You known you " .. "can fly by yourself, don't you?") return end -- Send a message... minetest.chat_send_player(playername, "You can now fly during " .. tostring(broomstick_time) .. " seconds.") minetest.log("action", "Player " .. playername .." has use a broomstick.") -- Subtract mana... mana.subtract(playername, broomstick_mana) -- And insert player in the list. table.insert(broomstick_actual_users, { name = playername, time = 0, is_warning_said = false }) -- Remove broomstick... return ItemStack("") else minetest.chat_send_player(playername, "You already have a " .. "broomstick ! Please wait until the end of your actual " .. "broomstick.") end else minetest.chat_send_player(playername, "You must have " .. tostring(broomstick_mana) .. " of mana to use a broomstick !") end end, }) -- Broomstick timer minetest.register_globalstep(function(dtime) for index, i in ipairs(broomstick_actual_users) do i.time = i.time + dtime -- Just a little warning message if i.time >= broomstick_time - 10 and not i.is_warning_said then minetest.chat_send_player(i.name, "WARNING ! You'll fall in 10 seconds !") i.is_warning_said = true elseif i.time >= broomstick_time then -- Send a message... minetest.chat_send_player(i.name, "End of broomstick. " .. "I hope you're not falling down...") -- Set player privs... privs = minetest.get_player_privs(i.name) privs["fly"] = nil minetest.set_player_privs(i.name, privs) -- And remove the player in the list. table.remove(broomstick_actual_users, index) end end end) -- Craft minetest.register_craft({ output = "broomstick:broomstick", recipe = {{"default:stick","default:stick","farming:wheat",}}, }) minetest.log("action", "[OK] broomstick")
local broomstick_time = 120 -- Seconds (for default 2 minutes) local broomstick_mana = 210 local broomstick_actual_users = {} local had_fly_privilege = {} local privs = {} -- Register broomstick minetest.register_craftitem("broomstick:broomstick", { description = "Broomstick", inventory_image = "broomstick.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) local playername = user:get_player_name() if mana.get(playername) >= broomstick_mana then local has_already_a_broomstick = false for _, i in ipairs(broomstick_actual_users) do if i.name == playername then has_already_a_broomstick = true end end if not has_already_a_broomstick then privs = minetest.get_player_privs(playername) -- Set player privs... if not privs.fly == true then privs.fly = true minetest.set_player_privs(playername, privs) else minetest.chat_send_player(playername, "You known you " .. "can fly by yourself, don't you?") return end -- Send a message... minetest.chat_send_player(playername, "You can now fly during " .. tostring(broomstick_time) .. " seconds.") minetest.log("action", "Player " .. playername .." has use a broomstick.") -- Subtract mana... mana.subtract(playername, broomstick_mana) -- And insert player in the list. table.insert(broomstick_actual_users, { name = playername, time = 0, is_warning_said = false }) -- Remove broomstick... local item_count = user:get_wielded_item():get_count() return ItemStack("broomstick:broomstick ".. tostring(item_count-1)) else minetest.chat_send_player(playername, "You already have a " .. "broomstick ! Please wait until the end of your actual " .. "broomstick.") end else minetest.chat_send_player(playername, "You must have " .. tostring(broomstick_mana) .. " of mana to use a broomstick !") end end, }) -- Broomstick timer minetest.register_globalstep(function(dtime) for index, i in ipairs(broomstick_actual_users) do i.time = i.time + dtime -- Just a little warning message if i.time >= broomstick_time - 10 and not i.is_warning_said then minetest.chat_send_player(i.name, "WARNING ! You'll fall in 10 seconds !") i.is_warning_said = true elseif i.time >= broomstick_time then -- Send a message... minetest.chat_send_player(i.name, "End of broomstick. " .. "I hope you're not falling down...") -- Set player privs... privs = minetest.get_player_privs(i.name) privs["fly"] = nil minetest.set_player_privs(i.name, privs) -- And remove the player in the list. table.remove(broomstick_actual_users, index) end end end) -- Craft minetest.register_craft({ output = "broomstick:broomstick", recipe = {{"default:stick","default:stick","farming:wheat",}}, }) minetest.log("action", "[OK] broomstick")
fixed itemstack remove broomstick
fixed itemstack remove broomstick
Lua
unlicense
Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
999d49c95d9a8b7d96068a68c11432899ce2f9c8
net/adns.lua
net/adns.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local server = require "net.server"; local dns = require "net.dns"; local log = require "util.logger".init("adns"); local t_insert, t_remove = table.insert, table.remove; local coroutine, tostring, pcall = coroutine, tostring, pcall; local function dummy_send(sock, data, i, j) return (j-i)+1; end module "adns" function lookup(handler, qname, qtype, qclass) return coroutine.wrap(function (peek) if peek then log("debug", "Records for %s already cached, using those...", qname); handler(peek); return; end log("debug", "Records for %s not in cache, sending query (%s)...", qname, tostring(coroutine.running())); local ok, err = dns.query(qname, qtype, qclass); if ok then coroutine.yield({ qclass or "IN", qtype or "A", qname, coroutine.running()}); -- Wait for reply log("debug", "Reply for %s (%s)", qname, tostring(coroutine.running())); end if ok then ok, err = pcall(handler, dns.peek(qname, qtype, qclass)); else log("error", "Error sending DNS query: %s", err); ok, err = pcall(handler, nil, err); end if not ok then log("error", "Error in DNS response handler: %s", tostring(err)); end end)(dns.peek(qname, qtype, qclass)); end function cancel(handle, call_handler, reason) log("warn", "Cancelling DNS lookup for %s", tostring(handle[3])); dns.cancel(handle[1], handle[2], handle[3], handle[4], call_handler); end function new_async_socket(sock, resolver) local peername = "<unknown>"; local listener = {}; local handler = {}; function listener.onincoming(conn, data) if data then dns.feed(handler, data); end end function listener.ondisconnect(conn, err) if err then log("warn", "DNS socket for %s disconnected: %s", peername, err); local servers = resolver.server; if resolver.socketset[conn] == resolver.best_server and resolver.best_server == #servers then log("error", "Exhausted all %d configured DNS servers, next lookup will try %s again", #servers, servers[1]); end resolver:servfail(conn); -- Let the magic commence end end handler = server.wrapclient(sock, "dns", 53, listener); if not handler then log("warn", "handler is nil"); end handler.settimeout = function () end handler.setsockname = function (_, ...) return sock:setsockname(...); end handler.setpeername = function (_, ...) peername = (...); local ret = sock:setpeername(...); _:set_send(dummy_send); return ret; end handler.connect = function (_, ...) return sock:connect(...) end --handler.send = function (_, data) _:write(data); return _.sendbuffer and _.sendbuffer(); end handler.send = function (_, data) log("debug", "Sending DNS query to %s", sock:getpeername()); return sock:send(data); end return handler; end dns.socket_wrapper_set(new_async_socket); return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local server = require "net.server"; local dns = require "net.dns"; local log = require "util.logger".init("adns"); local t_insert, t_remove = table.insert, table.remove; local coroutine, tostring, pcall = coroutine, tostring, pcall; local function dummy_send(sock, data, i, j) return (j-i)+1; end module "adns" function lookup(handler, qname, qtype, qclass) return coroutine.wrap(function (peek) if peek then log("debug", "Records for %s already cached, using those...", qname); handler(peek); return; end log("debug", "Records for %s not in cache, sending query (%s)...", qname, tostring(coroutine.running())); local ok, err = dns.query(qname, qtype, qclass); if ok then coroutine.yield({ qclass or "IN", qtype or "A", qname, coroutine.running()}); -- Wait for reply log("debug", "Reply for %s (%s)", qname, tostring(coroutine.running())); end if ok then ok, err = pcall(handler, dns.peek(qname, qtype, qclass)); else log("error", "Error sending DNS query: %s", err); ok, err = pcall(handler, nil, err); end if not ok then log("error", "Error in DNS response handler: %s", tostring(err)); end end)(dns.peek(qname, qtype, qclass)); end function cancel(handle, call_handler, reason) log("warn", "Cancelling DNS lookup for %s", tostring(handle[3])); dns.cancel(handle[1], handle[2], handle[3], handle[4], call_handler); end function new_async_socket(sock, resolver) local peername = "<unknown>"; local listener = {}; local handler = {}; function listener.onincoming(conn, data) if data then dns.feed(handler, data); end end function listener.ondisconnect(conn, err) if err then log("warn", "DNS socket for %s disconnected: %s", peername, err); local servers = resolver.server; if resolver.socketset[conn] == resolver.best_server and resolver.best_server == #servers then log("error", "Exhausted all %d configured DNS servers, next lookup will try %s again", #servers, servers[1]); end resolver:servfail(conn); -- Let the magic commence end end handler = server.wrapclient(sock, "dns", 53, listener); if not handler then log("warn", "handler is nil"); end handler.settimeout = function () end handler.setsockname = function (_, ...) return sock:setsockname(...); end handler.setpeername = function (_, ...) peername = (...); local ret = sock:setpeername(...); _:set_send(dummy_send); return ret; end handler.connect = function (_, ...) return sock:connect(...) end --handler.send = function (_, data) _:write(data); return _.sendbuffer and _.sendbuffer(); end handler.send = function (_, data) local getpeername = sock.getpeername; log("debug", "Sending DNS query to %s", (getpeername and getpeername(sock)) or "<unconnected>"); return sock:send(data); end return handler; end dns.socket_wrapper_set(new_async_socket); return _M;
net.adns: Fix logging to handle unconnected UDP sockets
net.adns: Fix logging to handle unconnected UDP sockets
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
7cf95dd2bb4f27f9ab674df89d5983a03a3aa481
core/frame.lua
core/frame.lua
local cassowary = require("cassowary") SILE.frames = {} local solver = cassowary.SimplexSolver(); solverNeedsReloading = true local parseFrameDef = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser return SILE._frameParser:match(d); end SILE.framePrototype = std.object { next= nil, id= nil, previous= nil, balanced= false, direction = nil, state = {}, enterHooks = {}, leaveHooks = {}, constrain = function (self, method, value) self.constraints[method] = value self:invalidate() end, invalidate = function() solverNeedsReloading = true end, relax = function(self, method) self.constraints[method] = nil end, reifyConstraint = function(self, solver, method, stay) if not self.constraints[method] then return end local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} local c = parseFrameDef(self.constraints[method], dims[method]) --print("Adding constraint "..self.id.."("..method..") = "..self.constraints[method]) local eq = cassowary.Equation(self.variables[method],c) solver:addConstraint(eq) if stay then solver:addStay(eq) end end, addWidthHeightDefinitions = function(self, solver) solver:addConstraint(cassowary.Equation(self.variables.width, cassowary.minus(self.variables.right, self.variables.left))) solver:addConstraint(cassowary.Equation(self.variables.height, cassowary.minus(self.variables.bottom, self.variables.top))) end, -- This is hideously inefficient, -- but it's the easiest way to allow users to reconfigure frames at runtime. solve = function(self) if not solverNeedsReloading then return end --print("Solving") solver = cassowary.SimplexSolver(); if SILE.frames.page then for k,c in pairs(SILE.frames.page.constraints) do SILE.frames.page:reifyConstraint(solver, k, true) end SILE.frames.page:addWidthHeightDefinitions(solver) end for id,f in pairs(SILE.frames) do if not (id == "page") then for k,c in pairs(f.constraints) do f:reifyConstraint(solver, k) end f:addWidthHeightDefinitions(solver) end end solver:solve() solverNeedsReloading = false --SILE.repl() end }; function SILE.framePrototype:toString() local f = "<Frame: "..self.id..": " f = f .." next="..self.next.." " for k,v in pairs(self.constraints) do f = f .. k.."="..v.."; " end f = f.. ">" return f end function SILE.framePrototype:moveX(amount) if self.direction == "RTL" then self.state.cursorX = self.state.cursorX - amount else self.state.cursorX = self.state.cursorX + amount end self:normalize() end function SILE.framePrototype:moveY(amount) self.state.cursorY = self.state.cursorY + amount self:normalize() end function SILE.framePrototype:newLine() self.state.cursorX = self.direction == "RTL" and self:right() or self:left() end function SILE.framePrototype:init() self.state = { cursorY = self:top(), totals = { height= 0, pastTop = false } } self:enter() self:newLine() end function SILE.framePrototype:enter() for i = 1,#SILE.framePrototype.enterHooks do SILE.framePrototype.enterHooks[i](self) end end function SILE.framePrototype:leave() for i = 1,#self.leaveHooks do self.leaveHooks[i](self) end end function SILE.framePrototype:normalize() if (type(self.state.cursorY)) == "table" then self.state.cursorY =self.state.cursorY.length end if (type(self.state.cursorX)) == "table" then self.state.cursorX =self.state.cursorX.length end end function SILE.framePrototype:isMainContentFrame() local c = SILE.documentState.thisPageTemplate.firstContentFrame while c do if c == self then return true end c = SILE.getFrame(c.next) end return false end SILE.newFrame = function(spec) SU.required(spec, "id", "frame declaration") local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} local frame if not SILE.frames[spec.id] then frame = SILE.framePrototype { constraints = {}, variables = {} } -- Copy everything in from spec SILE.frames[spec.id] = frame for method, dimension in pairs(dims) do frame.variables[method] = cassowary.Variable({ name = spec.id .. "_" .. method }); frame[method] = function (frame) frame:solve() return frame.variables[method].value end end else frame = SILE.frames[spec.id] end for key, value in pairs(spec) do if not dims[key] then frame[key] = spec[key] end end -- Fix up "balanced" if frame.balanced == "true" or frame.balanced == "1" then frame.balanced = true end frame.constraints = {} -- Add definitions of width and height for method, dimension in pairs(dims) do if spec[method] then frame:constrain(method, spec[method]) end end return frame end SILE.getFrame = function(id) if type(frame) == "table" then return frame end -- Shouldn't happen but... return SILE.frames[id] or SU.error("Couldn't get frame ID "..id, true) end SILE._frameParser = require("core/frameparser") SILE.parseComplexFrameDimension = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser local v = SILE._frameParser:match(d); if type(v) == "table" then local g = cassowary.Variable({ name = "t" }) local eq = cassowary.Equation(g,v) solverNeedsReloading = true solver:addConstraint(eq) SILE.frames.page:solve() solverNeedsReloading = true return g.value end return v end
local cassowary = require("cassowary") SILE.frames = {} local solver = cassowary.SimplexSolver(); solverNeedsReloading = true local parseFrameDef = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser return SILE._frameParser:match(d); end SILE.framePrototype = std.object { next= nil, id= nil, previous= nil, balanced= false, direction = nil, state = {}, enterHooks = {}, leaveHooks = {}, constrain = function (self, method, value) self.constraints[method] = value self:invalidate() end, invalidate = function() solverNeedsReloading = true end, relax = function(self, method) self.constraints[method] = nil end, reifyConstraint = function(self, solver, method, stay) if not self.constraints[method] then return end local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} local c = parseFrameDef(self.constraints[method], dims[method]) --print("Adding constraint "..self.id.."("..method..") = "..self.constraints[method]) local eq = cassowary.Equation(self.variables[method],c) solver:addConstraint(eq) if stay then solver:addStay(eq) end end, addWidthHeightDefinitions = function(self, solver) solver:addConstraint(cassowary.Equation(self.variables.width, cassowary.minus(self.variables.right, self.variables.left))) solver:addConstraint(cassowary.Equation(self.variables.height, cassowary.minus(self.variables.bottom, self.variables.top))) end, -- This is hideously inefficient, -- but it's the easiest way to allow users to reconfigure frames at runtime. solve = function(self) if not solverNeedsReloading then return end --print("Solving") solver = cassowary.SimplexSolver(); if SILE.frames.page then for k,c in pairs(SILE.frames.page.constraints) do SILE.frames.page:reifyConstraint(solver, k, true) end SILE.frames.page:addWidthHeightDefinitions(solver) end for id,f in pairs(SILE.frames) do if not (id == "page") then for k,c in pairs(f.constraints) do f:reifyConstraint(solver, k) end f:addWidthHeightDefinitions(solver) end end solver:solve() solverNeedsReloading = false --SILE.repl() end }; function SILE.framePrototype:toString() local f = "<Frame: "..self.id..": " f = f .." next="..self.next.." " for k,v in pairs(self.constraints) do f = f .. k.."="..v.."; " end f = f.. ">" return f end function SILE.framePrototype:moveX(amount) if self.direction == "RTL" then self.state.cursorX = self.state.cursorX - amount else self.state.cursorX = self.state.cursorX + amount end self:normalize() end function SILE.framePrototype:moveY(amount) self.state.cursorY = self.state.cursorY + amount self:normalize() end function SILE.framePrototype:newLine() self.state.cursorX = self.direction == "RTL" and self:right() or self:left() end function SILE.framePrototype:init() self.state = { cursorY = self:top(), totals = { height= 0, pastTop = false } } self:enter() self:newLine() end function SILE.framePrototype:enter() for i = 1,#SILE.framePrototype.enterHooks do SILE.framePrototype.enterHooks[i](self) end end function SILE.framePrototype:leave() for i = 1,#self.leaveHooks do self.leaveHooks[i](self) end end function SILE.framePrototype:normalize() if (type(self.state.cursorY)) == "table" then self.state.cursorY =self.state.cursorY.length end if (type(self.state.cursorX)) == "table" then self.state.cursorX =self.state.cursorX.length end end function SILE.framePrototype:isMainContentFrame() local c = SILE.documentState.thisPageTemplate.firstContentFrame while c do if c == self then return true end if c.next then c = SILE.getFrame(c.next) else return false end end return false end SILE.newFrame = function(spec) SU.required(spec, "id", "frame declaration") local dims = { top="h", bottom="h", height="h", left="w", right="w", width="w"} local frame if not SILE.frames[spec.id] then frame = SILE.framePrototype { constraints = {}, variables = {} } -- Copy everything in from spec SILE.frames[spec.id] = frame for method, dimension in pairs(dims) do frame.variables[method] = cassowary.Variable({ name = spec.id .. "_" .. method }); frame[method] = function (frame) frame:solve() return frame.variables[method].value end end else frame = SILE.frames[spec.id] end for key, value in pairs(spec) do if not dims[key] then frame[key] = spec[key] end end -- Fix up "balanced" if frame.balanced == "true" or frame.balanced == "1" then frame.balanced = true end frame.constraints = {} -- Add definitions of width and height for method, dimension in pairs(dims) do if spec[method] then frame:constrain(method, spec[method]) end end return frame end SILE.getFrame = function(id) if type(frame) == "table" then return frame end -- Shouldn't happen but... return SILE.frames[id] or SU.error("Couldn't get frame ID "..id, true) end SILE._frameParser = require("core/frameparser") SILE.parseComplexFrameDimension = function(d, width_or_height) SILE.documentState._dimension = width_or_height; -- ugly hack since you can't pass state to the parser local v = SILE._frameParser:match(d); if type(v) == "table" then local g = cassowary.Variable({ name = "t" }) local eq = cassowary.Equation(g,v) solverNeedsReloading = true solver:addConstraint(eq) SILE.frames.page:solve() solverNeedsReloading = true return g.value end return v end
Better fix for #34.
Better fix for #34.
Lua
mit
shirat74/sile,shirat74/sile,neofob/sile,neofob/sile,anthrotype/sile,WAKAMAZU/sile_fe,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,alerque/sile,alerque/sile,simoncozens/sile,Nathan22Miles/sile,simoncozens/sile,shirat74/sile,anthrotype/sile,Nathan22Miles/sile,simoncozens/sile,anthrotype/sile,shirat74/sile,Nathan22Miles/sile,anthrotype/sile,Nathan22Miles/sile,alerque/sile,WAKAMAZU/sile_fe,neofob/sile,neofob/sile
76781ff7b950c9f4a618daedf93a1ecc9eb8075b
ios-icons/icons.lua
ios-icons/icons.lua
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function isEntry(e) return (type(e) == 'table' and e.id) end local function flatten(tab) for _,v in pairs(tab) do if isEntry(v) then insert(result, v) else if type(v) == 'table' then flatten(v) end end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do local vt = type(v) if vt == 'folder' then icons.visit(v.icons, visitor) elseif vt == 'page' then icons.visit(v, visitor) elseif vt == 'icon' then visitor(v) end end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function flatten(tab) for _,v in pairs(tab) do local vt = type(v) if vt == 'icon' then insert(result, v) elseif vt == 'page' then flatten(v) elseif vt == 'folder' then flatten(v.icons) end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do local vt = type(v) if vt == 'folder' then icons.visit(v.icons, visitor) elseif vt == 'page' then icons.visit(v, visitor) elseif vt == 'icon' then visitor(v) end end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
fixed flatten function
fixed flatten function
Lua
mit
profburke/ios-icons,profburke/ios-icons,profburke/ios-icons
590c8d95ffc0a0362ef871dbac41911199428ba3
MMOCoreORB/bin/scripts/mobile/tatooine/wild_dune_boar.lua
MMOCoreORB/bin/scripts/mobile/tatooine/wild_dune_boar.lua
wild_dune_boar = Creature:new { objectName = "@mob/creature_names:wild_dune_boar", socialGroup = "boar", pvpFaction = "", faction = "", level = 50, chanceHit = 0.5, damageMin = 395, damageMax = 500, baseXp = 4916, baseHAM = 10000, baseHAMmax = 12000, armor = 1, resists = {110,140,110,5,5,5,5,-1,-1}, meatType = "meat_herbivore", meatAmount = 90, hideType = "hide_leathery", hideAmount = 80, boneType = "bone_mammal", boneAmount = 75, milk = 0, tamingChance = 0.15, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = 0, diet = CARNIVORE, templates = {"object/mobile/zucca_boar.iff"}, controlDeviceTemplate = "object/intangible/pet/zucca_boar_hue.iff", scale = 1.3, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"intimidationattack","intimidationChance=50"}, {"stunattack","stunChance=50"} } } CreatureTemplates:addCreatureTemplate(wild_dune_boar, "wild_dune_boar")
wild_dune_boar = Creature:new { objectName = "@mob/creature_names:wild_dune_boar", socialGroup = "boar", pvpFaction = "", faction = "", level = 50, chanceHit = 0.5, damageMin = 395, damageMax = 500, baseXp = 4916, baseHAM = 10000, baseHAMmax = 12000, armor = 1, resists = {110,140,110,5,5,5,5,-1,-1}, meatType = "meat_herbivore", meatAmount = 90, hideType = "hide_leathery", hideAmount = 80, boneType = "bone_mammal", boneAmount = 75, milk = 0, tamingChance = 0.15, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = 0, diet = CARNIVORE, templates = {"object/mobile/zucca_boar.iff"}, controlDeviceTemplate = "object/intangible/pet/pet_control.iff", -- zucca_boar_hue.iff bugged in client scale = 1.3, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"intimidationattack","intimidationChance=50"}, {"stunattack","stunChance=50"} } } CreatureTemplates:addCreatureTemplate(wild_dune_boar, "wild_dune_boar")
[fix] mantis# 5877, same fix that was appleid to the zucca boar
[fix] mantis# 5877, same fix that was appleid to the zucca boar Change-Id: Ib518db7153286e5cdf53b0f4fe2ddf7114e9bb6e
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
ea4bd2d02334db7c52af70f64f591bbd293330e3
test_scripts/Defects/4_5/1206_REQUEST_PTU_Trigger_PTU_failed_previous_IGN_ON.lua
test_scripts/Defects/4_5/1206_REQUEST_PTU_Trigger_PTU_failed_previous_IGN_ON.lua
---------------------------------------------------------------------------------------------------- -- Script verifies issue https://github.com/SmartDeviceLink/sdl_core/issues/1206 -- Flow: HTTP ---------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require("user_modules/script_runner") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local mobile_session = require("mobile_session") local common = require("test_scripts/Defects/4_5/commonDefects") local color = require("user_modules/consts").color --[[ General configuration parameters ]] runner.testSettings.restrictions.sdlBuildOptions = { { extendedPolicy = { "PROPRIETARY", "HTTP" } } } --[[ Local Functions ]] --[[ @registerApplicationAndWaitPTUStart: create mobile session, start RPC service, register mobile application --! and check that 'SDL.OnStatusUpdate' notification is sent to HMI with 'UPDATE_NEEDED' status --! @parameters: --! self - test object which will be provided automatically by runner module --! @return: none --]] local function registerApplicationAndWaitPTUStart(self) -- create mobile session self.mobileSession1 = mobile_session.MobileSession(self, self.mobileConnection) -- start RPC service self.mobileSession1:StartService(7) :Do(function() -- send 'RegisterAppInterface' RPC with default parameters for mobile application -- and return correlation identifier local corId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) -- register expectation of response for 'RegisterAppInterface' request with appropriate correlation id -- on Mobile connection -- it's expected that request is processed successfully self.mobileSession1:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) -- register expectation of 'BC.OnAppRegistered' notification on HMI connection -- it's expected that the value of 'application.appName' argument will be equal to default application name EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.registerAppInterfaceParams.appName } }) -- register expectation of 'SDL.OnStatusUpdate' notification on HMI connection -- it's expected that the value of 'status' argument will be 'UPDATE_NEEDED' EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) :Do(function() -- print information about received notification to console commonFunctions:userPrint(color.blue, "Received OnStatusUpdate: UPDATE_NEEDED") end) end) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile", common.start) runner.Step("SDL Configuration", common.printSDLConfig) runner.Title("Test") runner.Step("Application Registration and wait for UPDATE_NEEDED", registerApplicationAndWaitPTUStart) runner.Step("Ignition Off", common.ignitionOff) runner.Step("Start SDL, HMI, connect Mobile", common.start) runner.Step("Application Registration and wait for UPDATE_NEEDED", registerApplicationAndWaitPTUStart) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
---------------------------------------------------------------------------------------------------- -- Script verifies issue https://github.com/SmartDeviceLink/sdl_core/issues/1206 -- Flow: HTTP, PROPRIETARY ---------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require("user_modules/script_runner") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local mobile_session = require("mobile_session") local common = require("test_scripts/Defects/4_5/commonDefects") local color = require("user_modules/consts").color --[[ General configuration parameters ]] runner.testSettings.restrictions.sdlBuildOptions = { { extendedPolicy = { "PROPRIETARY", "HTTP" } } } --[[ Local Functions ]] --[[ @registerApplicationAndWaitPTUStart: create mobile session, start RPC service, register mobile application --! and check that 'SDL.OnStatusUpdate' notification is sent to HMI with 'UPDATE_NEEDED' status --! @parameters: --! self - test object which will be provided automatically by runner module --! @return: none --]] local function registerApplicationAndWaitPTUStart(self) -- create mobile session self.mobileSession1 = mobile_session.MobileSession(self, self.mobileConnection) -- register expectation of 'SDL.OnStatusUpdate' notification on HMI connection -- it's expected that the value of 'status' argument will be 'UPDATE_NEEDED' EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) :Do(function() -- print information about received notification to console commonFunctions:userPrint(color.blue, "Received OnStatusUpdate: UPDATE_NEEDED") end) -- start RPC service self.mobileSession1:StartService(7) :Do(function() -- send 'RegisterAppInterface' RPC with default parameters for mobile application -- and return correlation identifier local corId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) -- register expectation of response for 'RegisterAppInterface' request with appropriate correlation id -- on Mobile connection -- it's expected that request is processed successfully self.mobileSession1:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) -- register expectation of 'BC.OnAppRegistered' notification on HMI connection -- it's expected that the value of 'application.appName' argument will be equal to default application name EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.registerAppInterfaceParams.appName } }) end) end local function start(self) common.start(self) -- register expectation of 'SDL.OnStatusUpdate' notification on HMI connection -- it's expected that the value of 'status' argument will be 'UPDATE_NEEDED' EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) :Do(function() -- print information about received notification to console commonFunctions:userPrint(color.blue, "Received OnStatusUpdate: UPDATE_NEEDED") end) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile", common.start) runner.Step("SDL Configuration", common.printSDLConfig) runner.Title("Test") runner.Step("Application Registration and wait for UPDATE_NEEDED", registerApplicationAndWaitPTUStart) runner.Step("Ignition Off", common.ignitionOff) runner.Step("Start SDL, HMI, connect Mobile and wait for UPDATE_NEEDED", start) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
fixup! Update 1206 script
fixup! Update 1206 script
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
8a1b16429de76b9efd47f9a203dd07621819abc6
otouto/plugins/imdb.lua
otouto/plugins/imdb.lua
local imdb = {} imdb.command = 'imdb <query>' function imdb:init(config) imdb.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('imdb', true).table imdb.inline_triggers = { "^imdb (.+)" } imdb.doc = [[* ]]..config.cmd_pat..[[imdb* _<Film>_ Sucht _Film_ bei IMDb]] end local BASE_URL = 'https://www.omdbapi.com' function imdb:get_imdb_info(id) local url = BASE_URL..'/?i='..id local res, code = https.request(url) if code ~= 200 then return end local movie_info = json.decode(res) return movie_info end function imdb:inline_callback(inline_query, config, matches) local query = matches[1] local url = BASE_URL..'/?s='..URL.escape(query) local res, code = https.request(url) if code ~= 200 then utilities.answer_inline_query(self, inline_query) return end local data = json.decode(res) if data.Response ~= "True" then utilities.answer_inline_query(self, inline_query) return end local results = '[' for num in pairs(data.Search) do if num > 5 then break; end local imdb_id = data.Search[num].imdbID local movie_info = imdb:get_imdb_info(imdb_id) local title = movie_info.Title local year = movie_info.Year local text = '<b>'..movie_info.Title.. ' ('..movie_info.Year..')</b> von '..movie_info.Director..'\\n'..string.gsub(movie_info.imdbRating, '%.', ',')..'/10 | '..movie_info.Runtime..' | '.. movie_info.Genre if movie_info.Plot then text = text..'\\n<i>'..movie_info.Plot..'</i>' description = movie_info.Plot else description = 'Keine Beschreibung verfügbar' end local text = text:gsub('"', '\\"') local text = text:gsub("'", "\'") if movie_info.Poster == "N/A" then img_url = 'https://anditest.perseus.uberspace.de/inlineQuerys/imdb/logo.jpg' else img_url = movie_info.Poster end results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","title":"'..title..' ('..year..')","description":"'..description..'","url":"http://imdb.com/title/'..imdb_id..'","hide_url":true,"thumb_url":"'..img_url..'","reply_markup":{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'..imdb_id..'"}]]},"input_message_content":{"message_text":"'..text..'","parse_mode":"HTML"}},' end local results = results:sub(0, -2) local results = results..']' utilities.answer_inline_query(self, inline_query, results, 10000) end function imdb:action(msg, config) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(self, msg.chat.id, imdb.doc, true, msg.message_id, true) return end end local url = BASE_URL..'/?t='..URL.escape(input) local jstr, res = https.request(url) if res ~= 200 then utilities.send_reply(self, msg, config.errors.connection) return end local jdat = json.decode(jstr) if jdat.Response ~= 'True' then utilities.send_reply(self, msg, config.errors.results) return end local output = '<b>'..jdat.Title.. ' ('..jdat.Year..')</b> von '..jdat.Director..'\n' output = output..string.gsub(jdat.imdbRating, '%.', ',')..'/10 | '..jdat.Runtime..' | '.. jdat.Genre..'\n' output = output..'<i>' .. jdat.Plot .. '</i>' utilities.send_reply(self, msg, output, 'HTML', '{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'.. jdat.imdbID..'"}]]}') if jdat.Poster ~= "N/A" then local file = download_to_file(jdat.Poster) utilities.send_photo(self, msg.chat.id, file) end end return imdb
local imdb = {} imdb.command = 'imdb <query>' function imdb:init(config) imdb.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('imdb', true).table imdb.inline_triggers = { "^imdb (.+)" } imdb.doc = [[* ]]..config.cmd_pat..[[imdb* _<Film>_ Sucht _Film_ bei IMDb]] end local BASE_URL = 'https://www.omdbapi.com' function imdb:get_imdb_info(id) local url = BASE_URL..'/?i='..id local res, code = https.request(url) if code ~= 200 then return end local movie_info = json.decode(res) return movie_info end function imdb:inline_callback(inline_query, config, matches) local query = matches[1] local url = BASE_URL..'/?s='..URL.escape(query) local res, code = https.request(url) if code ~= 200 then utilities.answer_inline_query(self, inline_query) return end local data = json.decode(res) if data.Response ~= "True" then utilities.answer_inline_query(self, inline_query) return end local results = '[' for num in pairs(data.Search) do if num > 5 then break; end local imdb_id = data.Search[num].imdbID local movie_info = imdb:get_imdb_info(imdb_id) local title = movie_info.Title local year = movie_info.Year local text = '<b>'..movie_info.Title.. ' ('..movie_info.Year..')</b> von '..movie_info.Director..'\\n'..string.gsub(movie_info.imdbRating, '%.', ',')..'/10 | '..movie_info.Runtime..' | '.. movie_info.Genre if movie_info.Plot then text = text..'\\n<i>'..movie_info.Plot..'</i>' description = movie_info.Plot else description = 'Keine Beschreibung verfügbar' end local text = text:gsub('"', '\\"') local text = text:gsub("'", "\'") local description = description:gsub('"', '\\"') local description = description:gsub("'", "\'") if movie_info.Poster == "N/A" then img_url = 'https://anditest.perseus.uberspace.de/inlineQuerys/imdb/logo.jpg' else img_url = movie_info.Poster end results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","title":"'..title..' ('..year..')","description":"'..description..'","url":"http://imdb.com/title/'..imdb_id..'","hide_url":true,"thumb_url":"'..img_url..'","reply_markup":{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'..imdb_id..'"}]]},"input_message_content":{"message_text":"'..text..'","parse_mode":"HTML"}},' end local results = results:sub(0, -2) local results = results..']' utilities.answer_inline_query(self, inline_query, results, 10000) end function imdb:action(msg, config) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(self, msg.chat.id, imdb.doc, true, msg.message_id, true) return end end local url = BASE_URL..'/?t='..URL.escape(input) local jstr, res = https.request(url) if res ~= 200 then utilities.send_reply(self, msg, config.errors.connection) return end local jdat = json.decode(jstr) if jdat.Response ~= 'True' then utilities.send_reply(self, msg, config.errors.results) return end local output = '<b>'..jdat.Title.. ' ('..jdat.Year..')</b> von '..jdat.Director..'\n' output = output..string.gsub(jdat.imdbRating, '%.', ',')..'/10 | '..jdat.Runtime..' | '.. jdat.Genre..'\n' output = output..'<i>' .. jdat.Plot .. '</i>' utilities.send_reply(self, msg, output, 'HTML', '{"inline_keyboard":[[{"text":"IMDb-Seite aufrufen","url":"http://imdb.com/title/'.. jdat.imdbID..'"}]]}') if jdat.Poster ~= "N/A" then local file = download_to_file(jdat.Poster) utilities.send_photo(self, msg.chat.id, file) end end return imdb
IMDB: Fix Inline für einige Filme
IMDB: Fix Inline für einige Filme
Lua
agpl-3.0
Brawl345/Brawlbot-v2
49eb5aee862ba21492ef6cd96c5e6d3f445a06e8
test_scripts/Polices/Validation_of_PolicyTables/Check_count_of_user_selections.lua
test_scripts/Polices/Validation_of_PolicyTables/Check_count_of_user_selections.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] "usage_and_error_counts" and "count_of_rejections_duplicate_name" update -- -- Description: -- In case application registers with the name already registered on SDL now, -- Policy Manager must increment "count_of_rejections_duplicate_name" section value -- of Local Policy Table for the corresponding application. -- a. SDL and HMI are started -- b. app_1 with <abc> name successfully registers and running on SDL -- Steps: -- 1. app_2 -> SDL; RegisterAppInterface (appName: <abc>) -- 2. SDL -> app_2: RegisterAppInterface (DUPLICATE_NAME) -- Expected: -- 3. PoliciesMananger increments "count_of_rejections_duplicate_name" filed at PolicyTable --------------------------------------------------------------------------------------------- --[[ 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 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') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') local mobile_session = require('mobile_session') require('cardinalities') require('user_modules/AppTypes') --[[ Local variables ]] local HMIAppID local basic_ptu_file = "files/ptu.json" local ptu_first_app_registered = "files/ptu1app.json" local application2 = { registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Test Application", -- the same name in config.application1 isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = { "NAVIGATION" }, appID = "0000003", --ID different deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } } -- 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", "Location-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 --[[Preconditions]] commonFunctions:newTestCasesGroup("Preconditions") function Test.Precondition_StopSDL() StopSDL() end function Test.Precondition_DeleteLogsAndPolicyTable() commonSteps:DeleteLogsFiles() commonSteps:DeletePolicyTable() 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_first_app_registered) end function Test:Precondition_RegisterFirstApp() 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.Precondition_PreparePTData() PrepareJsonPTU1(config.application1.registerAppInterfaceParams.appID, ptu_first_app_registered) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_RegisterSecondApp_DuplicateData() self.mobileSession1 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession1:StartService(7) :Do(function (_,_) local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", application2.registerAppInterfaceParams) self.mobileSession1:ExpectResponse(correlationId, { success = false, resultCode = "DUPLICATE_NAME" }) end) end function Test:TestStep2_ActivateAppInSpecificLevel() commonSteps:ActivateAppInSpecificLevel(self,HMIAppID,"FULL") end function Test:TestStep3_InitiatePTUForGetSnapshot() testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_first_app_registered, config.application1.registerAppInterfaceParams.appName, self.mobileSession) end function Test:TestStep2_Check_count_of_rejections_duplicate_name_incremented_in_PT() local appID = "0000003" local file = io.open("/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json", "r") local json_data = file:read("*all") -- may be abbreviated to "*a"; file:close() local data = json.decode(json_data) local CountOfRejectionsDuplicateName = data.policy_table.usage_and_error_counts.app_level[appID].count_of_rejections_duplicate_name if CountOfRejectionsDuplicateName == 1 then return true else self:FailTestCase("Wrong count_of_run_attempts_while_revoked. Expected: " .. 1 .. ", Actual: " .. CountOfRejectionsDuplicateName) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_RemovePTUfiles() os.remove(ptu_first_app_registered) end function Test.Postcondition_Stop_SDL() StopSDL() end
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] "usage_and_error_counts" and "count_of_rejections_duplicate_name" update -- -- Description: -- In case application registers with the name already registered on SDL now, -- Policy Manager must increment "count_of_rejections_duplicate_name" section value -- of Local Policy Table for the corresponding application. -- a. SDL and HMI are started -- b. app_1 with <abc> name successfully registers and running on SDL -- Steps: -- 1. app_2 -> SDL; RegisterAppInterface (appName: <abc>) -- 2. SDL -> app_2: RegisterAppInterface (DUPLICATE_NAME) -- Expected: -- 3. PoliciesMananger increments "count_of_rejections_duplicate_name" filed at PolicyTable --------------------------------------------------------------------------------------------- --[[ 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 commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local json = require('json') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') local mobile_session = require('mobile_session') require('cardinalities') require('user_modules/AppTypes') --[[ Local variables ]] local HMIAppID local application1 = { registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Test Application", -- the same name in config.application1 isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = { "NAVIGATION" }, appID = "0000001", --ID different deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } } local application2 = { registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Test Application", -- the same name in application1 isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = { "NAVIGATION" }, appID = "0000003", --ID different deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } } --[[Preconditions]] commonFunctions:newTestCasesGroup("Preconditions") function Test.Precondition_StopSDL() StopSDL() end function Test.Precondition_DeleteLogsAndPolicyTable() commonSteps:DeleteLogsFiles() commonSteps:DeletePolicyTable() 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) self.mobileSession:StartService(7) end function Test:Precondition_RegisterApp() local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface", application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_,data) HMIAppID = data.params.application.appID EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"}) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_RegisterSecondApp_DuplicateData() self.mobileSession1 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession1:StartService(7) :Do(function (_,_) local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", application2.registerAppInterfaceParams) self.mobileSession1:ExpectResponse(correlationId, { success = false, resultCode = "DUPLICATE_NAME" }) end) end function Test.TestStep2_ActivateAppInSpecificLevel() commonSteps:ActivateAppInSpecificLevel(Test,HMIAppID) os.execute("sleep 3") end function Test:TestStep2_Check_count_of_rejections_duplicate_name_incremented_in_PT() local json_data local appID = "0000003" local file = io.open("/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json", "r") if file then json_data = file:read("*all") -- may be abbreviated to "*a"; file:close() local data = json.decode(json_data) local CountOfRejectionsDuplicateName = data.policy_table.usage_and_error_counts.app_level[appID].count_of_rejections_duplicate_name if CountOfRejectionsDuplicateName == 1 then return true else self:FailTestCase("Wrong count_of_run_attempts_while_revoked. Expected: " .. 1 .. ", Actual: " .. CountOfRejectionsDuplicateName) end else self:FailTestCase("PT snapshot was not found") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
Fixed test script
Fixed test script
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
8e7bad47a5605a348ca7c599fad8f95b69ea8b85
src/lounge/lua/mplayer.lua
src/lounge/lua/mplayer.lua
#!/lounge/bin/janosh -f local RUN_DIR="/var/run/mplayer" local CMD_FIFO=RUN_DIR .. "/cmdfifo" Janosh:exec({ "mkdir -p " .. RUN_DIR, "rm -rf " .. CMD_FIFO, "mkfifo " .. CMD_FIFO }) Janosh:setenv("DISPLAY",":0") Janosh:setenv("http_proxy","http://localhost:1234/") local PID, STDIN, STDOUT, STDERR = Janosh:popen("/usr/bin/mplayer","-idle", "-input", "file=\"/dev/stdin\"") Janosh:setenv("http_proxy","") local MplayerClass = {} -- the table representing the class, which will double as the metatable for the instances MplayerClass.__index = MplayerClass -- failed table lookups on the instances should fallback to the class table, to get methods function MplayerClass.new() return setmetatable({}, MplayerClass) end function MplayerClass.jump(self, idx) obj = Janosh:get("/playlist/items/.") if tonumber(idx) > #obj then idx = #obj - 1 end file = obj[tonumber(idx)].url self:cmd("pause") Janosh:trigger("/player/active", "true") self:cmd("loadfile " .. file) end function MplayerClass.previous(self) self:jump(tonumber(Janosh:get("/playlist/index").playlist.index) - 1) end function MplayerClass.next(self) self:jump(tonumber(Janosh:get("/playlist/index").playlist.index) + 1) end function MplayerClass.enqueue(self, videoUrl, title, srcUrl) if title == "" then title = "(no title)" end size = Janosh:size("/playlist/items/.") Janosh:mkobj("/playlist/items/#" .. size .. "/.") Janosh:set("/playlist/items/#" .. size .. "/url", videoUrl) Janosh:set("/playlist/items/#" .. size .. "/title", title) Janosh:set("/playlist/items/#" .. size .. "/source", srcUrl) end function MplayerClass.add(self, videoUrl, title, srcUrl) self:enqueue(videoUrl, title, srcUrl) Janosh:trigger("/notify/message", "Playing " .. title) if Janosh:get("/player/active").player.active == "false" then self:jump(10000000) -- jump to the ned of the playlist end end function MplayerClass.run(self) SOTRACK="DEMUXER: ==> Found" EOTRACK="GLOBAL: EOF code: 1" PATH_CHANGED="GLOBAL: ANS_path=" CACHEEMPTY="Cache empty" while true do line="" logf = io.open("/var/log/mplayer.log", "w") while true do line = Janosh:preadLine(STDOUT) if line == nil then break end logf:write(line .. "\n") logf:flush() if string.find(line, EOTRACK) then self:eotrack() elseif string.find(line, SOTRACK) then self:sotrack() elseif string.find(line, CACHEEMPTY) then self:cache_empty() end end Janosh:sleep(1000) end end function MplayerClass.cmd(self, cmdstring) Janosh:lock("MplayerClass.cmd") Janosh:pwrite(STDIN, cmdstring .. "\n") Janosh:unlock("MplayerClass.cmd") end function MplayerClass.setVolume(self, vol) self:cmd("volume " .. vol .. " 1") end function MplayerClass.setMute(self, mute) if mute == true then self:cmd("mute 1") else self:cmd("mute 0") end end function MplayerClass.forward(self) self:cmd("seek +10") end function MplayerClass.forwardMore(self) self:cmd("seek +300") end function MplayerClass.rewind(self) self:cmd("seek -10") end function MplayerClass.rewindMore(self) self:cmd("seek -300") end function MplayerClass.pause(self) self:cmd("pause") end function MplayerClass.stop(self) self:cmd("pause") self:cmd("stop") Janosh:trigger("/player/active","false") end function MplayerClass.osd(self) self:cmd("osd") end function MplayerClass.subtitle(self) self:cmd("sub_visibility") end function MplayerClass.sotrack(self) end function MplayerClass.cache_empty(self) Janosh:trigger("/notify/message", "Network Problem!") end function MplayerClass.eotrack(self) obj = Janosh:get("/playlist/.") idx = tonumber(obj.index) len = #obj.items if idx < len then self:jump(idx + 1) else self:stop() end end return MplayerClass:new()
#!/lounge/bin/janosh -f local RUN_DIR="/var/run/mplayer" local CMD_FIFO=RUN_DIR .. "/cmdfifo" Janosh:exec({ "mkdir -p " .. RUN_DIR, "rm -rf " .. CMD_FIFO, "mkfifo " .. CMD_FIFO }) Janosh:setenv("DISPLAY",":0") Janosh:setenv("http_proxy","http://localhost:1234/") local PID, STDIN, STDOUT, STDERR = Janosh:popen("/usr/bin/mplayer","-idle", "-input", "file=\"/dev/stdin\"") Janosh:setenv("http_proxy","") local MplayerClass = {} -- the table representing the class, which will double as the metatable for the instances MplayerClass.__index = MplayerClass -- failed table lookups on the instances should fallback to the class table, to get methods function MplayerClass.new() return setmetatable({}, MplayerClass) end function MplayerClass.jump(self, idx) obj = Janosh:get("/playlist/items/.") if tonumber(idx) > #obj then idx = #obj - 1 end file = obj[tonumber(idx)].url self:cmd("pause") Janosh:trigger("/player/active", "true") self:cmd("loadfile " .. file) Janosh:set("/playlist/index", idx) end function MplayerClass.previous(self) self:jump(tonumber(Janosh:get("/playlist/index").playlist.index) - 1) end function MplayerClass.next(self) self:jump(tonumber(Janosh:get("/playlist/index").playlist.index) + 1) end function MplayerClass.enqueue(self, videoUrl, title, srcUrl) if title == "" then title = "(no title)" end size = Janosh:size("/playlist/items/.") Janosh:mkobj("/playlist/items/#" .. size .. "/.") Janosh:set("/playlist/items/#" .. size .. "/url", videoUrl) Janosh:set("/playlist/items/#" .. size .. "/title", title) Janosh:set("/playlist/items/#" .. size .. "/source", srcUrl) end function MplayerClass.add(self, videoUrl, title, srcUrl) self:enqueue(videoUrl, title, srcUrl) Janosh:trigger("/notify/message", "Playing " .. title) if Janosh:get("/player/active").player.active == "false" then self:jump(10000000) -- jump to the ned of the playlist end end function MplayerClass.run(self) SOTRACK="DEMUXER: ==> Found" EOTRACK="GLOBAL: EOF code: 1" PATH_CHANGED="GLOBAL: ANS_path=" CACHEEMPTY="Cache empty" while true do line="" logf = io.open("/var/log/mplayer.log", "w") while true do line = Janosh:preadLine(STDOUT) if line == nil then break end logf:write(line .. "\n") logf:flush() if string.find(line, EOTRACK) then self:eotrack() elseif string.find(line, SOTRACK) then self:sotrack() elseif string.find(line, CACHEEMPTY) then self:cache_empty() end end Janosh:sleep(1000) end end function MplayerClass.cmd(self, cmdstring) Janosh:lock("MplayerClass.cmd") Janosh:pwrite(STDIN, cmdstring .. "\n") Janosh:unlock("MplayerClass.cmd") end function MplayerClass.setVolume(self, vol) self:cmd("volume " .. vol .. " 1") end function MplayerClass.setMute(self, mute) if mute == true then self:cmd("mute 1") else self:cmd("mute 0") end end function MplayerClass.forward(self) self:cmd("seek +10") end function MplayerClass.forwardMore(self) self:cmd("seek +300") end function MplayerClass.rewind(self) self:cmd("seek -10") end function MplayerClass.rewindMore(self) self:cmd("seek -300") end function MplayerClass.pause(self) self:cmd("pause") end function MplayerClass.stop(self) self:cmd("pause") self:cmd("stop") Janosh:trigger("/player/active","false") end function MplayerClass.osd(self) self:cmd("osd") end function MplayerClass.subtitle(self) self:cmd("sub_visibility") end function MplayerClass.sotrack(self) end function MplayerClass.cache_empty(self) Janosh:trigger("/notify/message", "Network Problem!") end function MplayerClass.eotrack(self) obj = Janosh:get("/playlist/.") idx = tonumber(obj.index) len = #obj.items if idx < len - 1 then self:jump(tostring(idx)) else self:stop() end end return MplayerClass:new()
fixed eotrack in mplayer
fixed eotrack in mplayer
Lua
agpl-3.0
screeninvader/ScreenInvader,screeninvader/ScreenInvader
2560730123b73f8c3e52345dc238c96b9b8c7e0f
src/lua/main.lua
src/lua/main.lua
-- © 2008 David Given. -- WordGrinder is licensed under the MIT open source license. See the COPYING -- file in this distribution for the full text. local int = math.floor local Write = wg.write local SetNormal = wg.setnormal local SetBold = wg.setbold local SetUnderline = wg.setunderline local SetReverse = wg.setreverse local GetStringWidth = wg.getstringwidth local redrawpending = true -- Determine the user's home directory. HOME = os.getenv("HOME") or os.getenv("USERPROFILE") function QueueRedraw() redrawpending = true if not Document.wrapwidth then ResizeScreen() end end function ResetDocumentSet() DocumentSet = CreateDocumentSet() DocumentSet.menu = CreateMenu() DocumentSet:addDocument(CreateDocument(), "main") DocumentSet:setCurrent("main") RebuildParagraphStylesMenu(DocumentSet.styles) RebuildDocumentsMenu(DocumentSet.documents) DocumentSet:purge() DocumentSet:clean() FireEvent(Event.DocumentCreated) FireEvent(Event.RegisterAddons) end -- This function contains the word processor proper, including the main event -- loop. function WordProcessor(filename) wg.initscreen() ResizeScreen() RedrawScreen() if filename then Cmd.LoadDocumentSet(filename) end --ModalMessage("Welcome!", "Welcome to WordGrinder! While editing, you may press ESC for the menu, or ESC, F, X to exit (or ALT+F, X if your terminal supports it).") local masterkeymap = { ["KEY_RESIZE"] = function() -- resize ResizeScreen() RedrawScreen() end, ["KEY_REDRAW"] = RedrawScreen, [" "] = Cmd.SplitCurrentWord, ["KEY_RETURN"] = Cmd.SplitCurrentParagraph, ["KEY_ESCAPE"] = Cmd.ActivateMenu, } local function eventloop() local nl = string.char(13) while true do if DocumentSet.justchanged then FireEvent(Event.Changed) DocumentSet.justchanged = false end FireEvent(Event.WaitingForUser) local c = "KEY_TIMEOUT" while (c == "KEY_TIMEOUT") do if redrawpending then RedrawScreen() redrawpending = false end c = wg.getchar(DocumentSet.idletime) if (c == "KEY_TIMEOUT") then FireEvent(Event.Idle) end end ResetNonmodalMessages() -- Anything in masterkeymap overrides everything else. local f = masterkeymap[c] if f then f() else -- It's not in masterkeymap. If it's printable, insert it; if it's -- not, look it up in the menu hierarchy. if not c:match("^KEY_") then Cmd.InsertStringIntoWord(c) else f = DocumentSet.menu:lookupAccelerator(c) if f then if (type(f) == "function") then f() else Cmd.ActivateMenu(f) end else NonmodalMessage(c:gsub("^KEY_", "").." is not bound --- try ESCAPE for a menu") end end end end end while true do local f, e = xpcall(eventloop, Traceback) if not f then ModalMessage("Internal error!", "Something went wrong inside WordGrinder! I'll try and ".. "continue but you should save your work immediately (under a ".. "different filename), exit, and send the following technical ".. "information to the author:\n\n" .. e) end end end -- Program entry point. Parses command line arguments and executes. function Main(...) -- Set up the initial document so that the command line options have -- access. ResetDocumentSet() local filename = nil do local stdout = io.stdout local stderr = io.stderr local function message(...) stderr:write("wordgrinder: ", ...) stderr:write("\n") end local function usererror(...) message(...) os.exit(1) end local function do_help(opt) stdout:write("WordGrinder version ", VERSION, " © 2007-2008 David Given\n") if DEBUG then stdout:write("(This version has been compiled with debugging enabled.)\n") end stdout:write([[ Syntax: wordgrinder [<options...>] [<filename>] Options: -h --help Displays this message. --lua file.lua Loads and executes file.lua before startup -c --convert src dest Converts from one file format to another Only one filename may be specified, which is the name of a WordGrinder file to load on startup. If not given, you get a blank document instead. To convert documents, use --convert. The file type is autodetected from the extension. To specify a document name, use :name as a suffix. e.g.: wordgrinder --convert filename.wg:"Chapter 1" chapter1.odt ]]) if DEBUG then -- List debugging options here. end os.exit(0) end local function do_lua(opt) if not opt then usererror("--lua must have an argument") end local f, e = loadfile(opt) if e then usererror("user script compilation error: "..e) end f() return 1 end local function do_convert(opt1, opt2) if not opt1 or not opt2 then usererror("--convert must have two arguments") end CliConvert(opt1, opt2) end local function needarg(opt) if not opt then usererror("missing option parameter") end end local argmap = { ["h"] = do_help, ["help"] = do_help, ["lua"] = do_lua, ["c"] = do_convert, ["convert"] = do_convert, } if DEBUG then -- argmap["p"] = do_profile -- argmap["profile"] = do_profile end -- Called on an unrecognised option. local function unrecognisedarg(arg) usererror("unrecognised option '", arg, "' --- try --help for help") end -- Do the actual argument parsing. local arg = {...} for i = 2, #arg do local o = arg[i] local op if (o:byte(1) == 45) then -- This is an option. if (o:byte(2) == 45) then -- ...with a -- prefix. o = o:sub(3) local fn = argmap[o] if not fn then unrecognisedarg("--"..o) end i = i + fn(arg[i+1], arg[i+2]) else -- ...without a -- prefix. local od = o:sub(2, 2) local fn = argmap[od] if not fn then unrecognisedarg("-"..od) end op = o:sub(3) if (op == "") then i = i + fn(arg[i+1], arg[i+2]) else fn(op) end end else if filename then usererror("you may only specify one filename") end filename = o end end end if filename and not filename:find("^/") and not filename:find("^[a-zA-Z]:[/\\]") then filename = lfs.currentdir() .. "/" .. filename end WordProcessor(filename) end
-- © 2008 David Given. -- WordGrinder is licensed under the MIT open source license. See the COPYING -- file in this distribution for the full text. local int = math.floor local Write = wg.write local SetNormal = wg.setnormal local SetBold = wg.setbold local SetUnderline = wg.setunderline local SetReverse = wg.setreverse local GetStringWidth = wg.getstringwidth local redrawpending = true -- Determine the user's home directory. HOME = os.getenv("HOME") or os.getenv("USERPROFILE") function QueueRedraw() redrawpending = true if not Document.wrapwidth then ResizeScreen() end end function ResetDocumentSet() DocumentSet = CreateDocumentSet() DocumentSet.menu = CreateMenu() DocumentSet:addDocument(CreateDocument(), "main") DocumentSet:setCurrent("main") RebuildParagraphStylesMenu(DocumentSet.styles) RebuildDocumentsMenu(DocumentSet.documents) DocumentSet:purge() DocumentSet:clean() FireEvent(Event.DocumentCreated) FireEvent(Event.RegisterAddons) end -- This function contains the word processor proper, including the main event -- loop. function WordProcessor(filename) wg.initscreen() ResizeScreen() RedrawScreen() if filename then Cmd.LoadDocumentSet(filename) end --ModalMessage("Welcome!", "Welcome to WordGrinder! While editing, you may press ESC for the menu, or ESC, F, X to exit (or ALT+F, X if your terminal supports it).") local masterkeymap = { ["KEY_RESIZE"] = function() -- resize ResizeScreen() RedrawScreen() end, ["KEY_REDRAW"] = RedrawScreen, [" "] = Cmd.SplitCurrentWord, ["KEY_RETURN"] = Cmd.SplitCurrentParagraph, ["KEY_ESCAPE"] = Cmd.ActivateMenu, } local function eventloop() local nl = string.char(13) while true do if DocumentSet.justchanged then FireEvent(Event.Changed) DocumentSet.justchanged = false end FireEvent(Event.WaitingForUser) local c = "KEY_TIMEOUT" while (c == "KEY_TIMEOUT") do if redrawpending then RedrawScreen() redrawpending = false end c = wg.getchar(DocumentSet.idletime) if (c == "KEY_TIMEOUT") then FireEvent(Event.Idle) end end ResetNonmodalMessages() -- Anything in masterkeymap overrides everything else. local f = masterkeymap[c] if f then f() else -- It's not in masterkeymap. If it's printable, insert it; if it's -- not, look it up in the menu hierarchy. if not c:match("^KEY_") then Cmd.InsertStringIntoWord(c) else f = DocumentSet.menu:lookupAccelerator(c) if f then if (type(f) == "function") then f() else Cmd.ActivateMenu(f) end else NonmodalMessage(c:gsub("^KEY_", "").." is not bound --- try ESCAPE for a menu") end end end end end while true do local f, e = xpcall(eventloop, Traceback) if not f then ModalMessage("Internal error!", "Something went wrong inside WordGrinder! I'll try and ".. "continue but you should save your work immediately (under a ".. "different filename), exit, and send the following technical ".. "information to the author:\n\n" .. e) end end end -- Program entry point. Parses command line arguments and executes. function Main(...) -- Set up the initial document so that the command line options have -- access. ResetDocumentSet() local filename = nil do local stdout = io.stdout local stderr = io.stderr local function message(...) stderr:write("wordgrinder: ", ...) stderr:write("\n") end local function usererror(...) message(...) os.exit(1) end local function do_help(opt) stdout:write("WordGrinder version ", VERSION, " © 2007-2008 David Given\n") if DEBUG then stdout:write("(This version has been compiled with debugging enabled.)\n") end stdout:write([[ Syntax: wordgrinder [<options...>] [<filename>] Options: -h --help Displays this message. --lua file.lua Loads and executes file.lua before startup -c --convert src dest Converts from one file format to another Only one filename may be specified, which is the name of a WordGrinder file to load on startup. If not given, you get a blank document instead. To convert documents, use --convert. The file type is autodetected from the extension. To specify a document name, use :name as a suffix. e.g.: wordgrinder --convert filename.wg:"Chapter 1" chapter1.odt ]]) if DEBUG then -- List debugging options here. end os.exit(0) end local function do_lua(opt) if not opt then usererror("--lua must have an argument") end local f, e = loadfile(opt) if e then usererror("user script compilation error: "..e) end f() return 1 end local function do_convert(opt1, opt2) if not opt1 or not opt2 then usererror("--convert must have two arguments") end CliConvert(opt1, opt2) end local function needarg(opt) if not opt then usererror("missing option parameter") end end local argmap = { ["h"] = do_help, ["help"] = do_help, ["lua"] = do_lua, ["c"] = do_convert, ["convert"] = do_convert, } if DEBUG then -- argmap["p"] = do_profile -- argmap["profile"] = do_profile end -- Called on an unrecognised option. local function unrecognisedarg(arg) usererror("unrecognised option '", arg, "' --- try --help for help") end -- Do the actual argument parsing. local arg = {...} local i = 2 while (i <= #arg) do local o = arg[i] local op if (o:byte(1) == 45) then -- This is an option. if (o:byte(2) == 45) then -- ...with a -- prefix. o = o:sub(3) local fn = argmap[o] if not fn then unrecognisedarg("--"..o) end i = i + fn(arg[i+1], arg[i+2]) else -- ...without a -- prefix. local od = o:sub(2, 2) local fn = argmap[od] if not fn then unrecognisedarg("-"..od) end op = o:sub(3) if (op == "") then i = i + fn(arg[i+1], arg[i+2]) else fn(op) end end else if filename then usererror("you may only specify one filename") end filename = o end i = i + 1 end end if filename and not filename:find("^/") and not filename:find("^[a-zA-Z]:[/\\]") then filename = lfs.currentdir() .. "/" .. filename end WordProcessor(filename) end
Fix command line parsing to consider more than just the first parameter.
Fix command line parsing to consider more than just the first parameter.
Lua
mit
rodoviario/wordgrinder,NRauh/wordgrinder,rodoviario/wordgrinder,NRauh/wordgrinder,Munchotaur/wordgrinder,Munchotaur/wordgrinder
e69dcf68a2da0c2dc74ce6932b195144330a6c1b
libs/httpd/luasrc/httpd/handler/luci.lua
libs/httpd/luasrc/httpd/handler/luci.lua
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") local ltn12 = require("luci.ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self, limit) luci.httpd.module.Handler.__init__(self) self.limit = limit or 5 self.running = {} setmetatable(self.running, {__mode = "v"}) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) if self.limit and #self.running >= self.limit then for k, v in ipairs(self.running) do if coroutine.status(v) == "dead" then collectgarbage() break end end if #self.running >= self.limit then return self:failure(503, "Overload") end end table.insert(self.running, coroutine.running()) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local active = true local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id or not active then return true elseif id == 5 then active = false while (coroutine.resume(x)) do end return nil elseif id == 4 then return data end if coroutine.status(x) == "dead" then return nil end end return Response(status, headers), iter end
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") local ltn12 = require("luci.ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self, limit) luci.httpd.module.Handler.__init__(self) self.limit = limit or 5 self.running = {} setmetatable(self.running, {__mode = "k"}) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local reaped = false local running = 0 for _, v in pairs(self.running) do if v then running = running + 1 end end if self.limit and running >= self.limit then for k, v in ipairs(self.running) do if coroutine.status(k) == "dead" then self.running[k] = nil running = running - 1 reaped = true end end if reaped then collectgarbage() end if running >= self.limit then return self:failure(503, "Overload %i/%i" % { running, self.limit } ) end end self.running[coroutine.running()] = true local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local active = true local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id or not active then return true elseif id == 5 then active = false while (coroutine.resume(x)) do end return nil elseif id == 4 then return data end if coroutine.status(x) == "dead" then return nil end end return Response(status, headers), iter end
* luci/libs/httpd: fix spurious Overload errors in luci-httpd
* luci/libs/httpd: fix spurious Overload errors in luci-httpd
Lua
apache-2.0
david-xiao/luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,schidler/ionic-luci,thesabbir/luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,maxrio/luci981213,Sakura-Winkey/LuCI,hnyman/luci,taiha/luci,RedSnake64/openwrt-luci-packages,981213/luci-1,mumuqz/luci,jorgifumi/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,nwf/openwrt-luci,obsy/luci,obsy/luci,ollie27/openwrt_luci,daofeng2015/luci,harveyhu2012/luci,jorgifumi/luci,nwf/openwrt-luci,taiha/luci,nmav/luci,teslamint/luci,bright-things/ionic-luci,remakeelectric/luci,forward619/luci,nmav/luci,slayerrensky/luci,mumuqz/luci,Hostle/luci,LuttyYang/luci,daofeng2015/luci,openwrt-es/openwrt-luci,Sakura-Winkey/LuCI,joaofvieira/luci,aa65535/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,teslamint/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,lbthomsen/openwrt-luci,artynet/luci,chris5560/openwrt-luci,taiha/luci,bittorf/luci,Noltari/luci,david-xiao/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,mumuqz/luci,ff94315/luci-1,david-xiao/luci,artynet/luci,lbthomsen/openwrt-luci,hnyman/luci,slayerrensky/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,keyidadi/luci,florian-shellfire/luci,cappiewu/luci,MinFu/luci,maxrio/luci981213,Hostle/luci,dismantl/luci-0.12,artynet/luci,LuttyYang/luci,tobiaswaldvogel/luci,sujeet14108/luci,Noltari/luci,jorgifumi/luci,MinFu/luci,NeoRaider/luci,tcatm/luci,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,opentechinstitute/luci,obsy/luci,NeoRaider/luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,joaofvieira/luci,thesabbir/luci,Noltari/luci,wongsyrone/luci-1,Wedmer/luci,openwrt/luci,florian-shellfire/luci,jlopenwrtluci/luci,marcel-sch/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,palmettos/cnLuCI,deepak78/new-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,ollie27/openwrt_luci,NeoRaider/luci,tobiaswaldvogel/luci,thesabbir/luci,lcf258/openwrtcn,nmav/luci,sujeet14108/luci,jchuang1977/luci-1,mumuqz/luci,bittorf/luci,taiha/luci,openwrt-es/openwrt-luci,palmettos/test,Sakura-Winkey/LuCI,hnyman/luci,daofeng2015/luci,obsy/luci,chris5560/openwrt-luci,kuoruan/luci,Wedmer/luci,nwf/openwrt-luci,MinFu/luci,chris5560/openwrt-luci,wongsyrone/luci-1,wongsyrone/luci-1,forward619/luci,thess/OpenWrt-luci,nmav/luci,Kyklas/luci-proto-hso,deepak78/new-luci,forward619/luci,dismantl/luci-0.12,RuiChen1113/luci,remakeelectric/luci,cshore/luci,zhaoxx063/luci,ff94315/luci-1,tcatm/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,dwmw2/luci,lcf258/openwrtcn,kuoruan/lede-luci,forward619/luci,cshore-firmware/openwrt-luci,keyidadi/luci,lcf258/openwrtcn,tcatm/luci,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,kuoruan/lede-luci,Noltari/luci,marcel-sch/luci,marcel-sch/luci,openwrt/luci,obsy/luci,hnyman/luci,maxrio/luci981213,oneru/luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,jchuang1977/luci-1,artynet/luci,tobiaswaldvogel/luci,forward619/luci,Noltari/luci,cshore-firmware/openwrt-luci,oneru/luci,openwrt-es/openwrt-luci,kuoruan/luci,openwrt/luci,dwmw2/luci,jchuang1977/luci-1,florian-shellfire/luci,maxrio/luci981213,maxrio/luci981213,chris5560/openwrt-luci,slayerrensky/luci,Noltari/luci,rogerpueyo/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,artynet/luci,RuiChen1113/luci,lbthomsen/openwrt-luci,Hostle/luci,tcatm/luci,kuoruan/lede-luci,kuoruan/luci,maxrio/luci981213,dwmw2/luci,male-puppies/luci,shangjiyu/luci-with-extra,bittorf/luci,wongsyrone/luci-1,oneru/luci,schidler/ionic-luci,thesabbir/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,oneru/luci,sujeet14108/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,schidler/ionic-luci,obsy/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,dismantl/luci-0.12,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,LuttyYang/luci,harveyhu2012/luci,male-puppies/luci,openwrt/luci,MinFu/luci,Sakura-Winkey/LuCI,ff94315/luci-1,openwrt-es/openwrt-luci,nwf/openwrt-luci,fkooman/luci,cshore-firmware/openwrt-luci,urueedi/luci,oyido/luci,cappiewu/luci,lcf258/openwrtcn,male-puppies/luci,joaofvieira/luci,fkooman/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,hnyman/luci,palmettos/test,nmav/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,nmav/luci,cshore/luci,daofeng2015/luci,ff94315/luci-1,openwrt/luci,mumuqz/luci,cshore/luci,openwrt/luci,nmav/luci,shangjiyu/luci-with-extra,fkooman/luci,taiha/luci,cappiewu/luci,NeoRaider/luci,Wedmer/luci,cshore/luci,remakeelectric/luci,RuiChen1113/luci,palmettos/test,aa65535/luci,Hostle/luci,dwmw2/luci,LuttyYang/luci,tcatm/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,kuoruan/luci,remakeelectric/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,kuoruan/lede-luci,cappiewu/luci,dismantl/luci-0.12,remakeelectric/luci,cappiewu/luci,cshore/luci,bittorf/luci,lcf258/openwrtcn,aa65535/luci,Wedmer/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,schidler/ionic-luci,deepak78/new-luci,NeoRaider/luci,kuoruan/lede-luci,male-puppies/luci,harveyhu2012/luci,981213/luci-1,opentechinstitute/luci,joaofvieira/luci,jchuang1977/luci-1,marcel-sch/luci,florian-shellfire/luci,zhaoxx063/luci,hnyman/luci,ollie27/openwrt_luci,joaofvieira/luci,wongsyrone/luci-1,opentechinstitute/luci,oyido/luci,obsy/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,jorgifumi/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,kuoruan/luci,jlopenwrtluci/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,keyidadi/luci,palmettos/test,nwf/openwrt-luci,Wedmer/luci,keyidadi/luci,lcf258/openwrtcn,Hostle/luci,jchuang1977/luci-1,lcf258/openwrtcn,sujeet14108/luci,joaofvieira/luci,Wedmer/luci,aa65535/luci,aa65535/luci,harveyhu2012/luci,kuoruan/lede-luci,rogerpueyo/luci,urueedi/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,openwrt/luci,hnyman/luci,sujeet14108/luci,sujeet14108/luci,tcatm/luci,urueedi/luci,urueedi/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,Hostle/openwrt-luci-multi-user,urueedi/luci,mumuqz/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,Noltari/luci,dwmw2/luci,chris5560/openwrt-luci,ollie27/openwrt_luci,thesabbir/luci,schidler/ionic-luci,palmettos/cnLuCI,bittorf/luci,teslamint/luci,thess/OpenWrt-luci,ff94315/luci-1,kuoruan/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,harveyhu2012/luci,slayerrensky/luci,Kyklas/luci-proto-hso,deepak78/new-luci,bright-things/ionic-luci,aa65535/luci,RuiChen1113/luci,bittorf/luci,teslamint/luci,MinFu/luci,harveyhu2012/luci,thesabbir/luci,jorgifumi/luci,fkooman/luci,teslamint/luci,bright-things/ionic-luci,palmettos/test,Sakura-Winkey/LuCI,kuoruan/lede-luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,remakeelectric/luci,fkooman/luci,palmettos/cnLuCI,slayerrensky/luci,oyido/luci,deepak78/new-luci,RuiChen1113/luci,ollie27/openwrt_luci,aa65535/luci,MinFu/luci,zhaoxx063/luci,teslamint/luci,kuoruan/lede-luci,florian-shellfire/luci,taiha/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,dismantl/luci-0.12,deepak78/new-luci,fkooman/luci,oyido/luci,zhaoxx063/luci,palmettos/test,lcf258/openwrtcn,ff94315/luci-1,Noltari/luci,tobiaswaldvogel/luci,forward619/luci,oyido/luci,palmettos/cnLuCI,981213/luci-1,RedSnake64/openwrt-luci-packages,zhaoxx063/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,david-xiao/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,cappiewu/luci,openwrt-es/openwrt-luci,MinFu/luci,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,daofeng2015/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,981213/luci-1,nwf/openwrt-luci,joaofvieira/luci,oyido/luci,mumuqz/luci,florian-shellfire/luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,bright-things/ionic-luci,ollie27/openwrt_luci,zhaoxx063/luci,Noltari/luci,LuttyYang/luci,marcel-sch/luci,opentechinstitute/luci,RuiChen1113/luci,palmettos/cnLuCI,remakeelectric/luci,florian-shellfire/luci,rogerpueyo/luci,taiha/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,jchuang1977/luci-1,Hostle/luci,cshore-firmware/openwrt-luci,urueedi/luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,male-puppies/luci,urueedi/luci,artynet/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,981213/luci-1,MinFu/luci,remakeelectric/luci,zhaoxx063/luci,florian-shellfire/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,chris5560/openwrt-luci,Wedmer/luci,rogerpueyo/luci,keyidadi/luci,981213/luci-1,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,artynet/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,oyido/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,jorgifumi/luci,wongsyrone/luci-1,artynet/luci,dismantl/luci-0.12,maxrio/luci981213,harveyhu2012/luci,palmettos/test,slayerrensky/luci,ff94315/luci-1,NeoRaider/luci,Hostle/luci,lbthomsen/openwrt-luci,slayerrensky/luci,thess/OpenWrt-luci,teslamint/luci,keyidadi/luci,cappiewu/luci,fkooman/luci,sujeet14108/luci,wongsyrone/luci-1,tcatm/luci,bright-things/ionic-luci,david-xiao/luci,teslamint/luci,Sakura-Winkey/LuCI,thesabbir/luci,ff94315/luci-1,wongsyrone/luci-1,opentechinstitute/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,981213/luci-1,schidler/ionic-luci,fkooman/luci,bright-things/ionic-luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,nmav/luci,shangjiyu/luci-with-extra,cshore/luci,cshore/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,bittorf/luci,nwf/openwrt-luci,lcf258/openwrtcn,LuttyYang/luci,openwrt/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,Wedmer/luci,david-xiao/luci,palmettos/cnLuCI,slayerrensky/luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,obsy/luci,Sakura-Winkey/LuCI,daofeng2015/luci,jlopenwrtluci/luci,urueedi/luci,palmettos/test,Hostle/openwrt-luci-multi-user,hnyman/luci,nmav/luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci
40e7b6b8ee82c2aea18e43327fc6807a608c5c7e
core/base-shaper.lua
core/base-shaper.lua
if not SILE.shapers then SILE.shapers = { } end SILE.tokenizers.default = function(text) return SU.gtoke(text, SILE.settings.get("shaper.spacepattern")) end SILE.settings.declare({ name = "shaper.spacepattern", type = "string", default = "%s+", help = "The Lua pattern used for splitting words on spaces" }) SILE.shapers.base = std.object { -- Return the length of a space character -- with a particular set of font options, -- giving preference to document.spaceskip -- Caching this has no significant speedup measureSpace = function(self, options) local ss = SILE.settings.get("document.spaceskip") if ss then return ss end local i,w = self:shapeToken(" ", options) local spacewidth if w then spacewidth = w.length else if not i[1] then return SILE.length.new() end spacewidth = i[1].width end return SILE.length.new({ length = spacewidth * 1.2, shrink = spacewidth/3, stretch = spacewidth /2 }) -- XXX all rather arbitrary end, measureDim = function (self, char) local options = SILE.font.loadDefaults({}) local i = self:shapeToken(char, options) if char == "x" then return i[1].height else return i[1].width end end, -- Given a text and some font options, return a bunch of boxes shapeToken = function(self, text, options) SU.error("Abstract function shapeToken called", true) end, -- Given font options, select a font. We will handle -- caching here. Returns an arbitrary, implementation-specific -- object (ie a PAL for Pango, font number for libtexpdf, ...) getFace = function(options) SU.error("Abstract function getFace called", true) end, itemize = function(self, nodelist, text) local state = SILE.font.loadDefaults({}) local gluewidth = self:measureSpace(state) -- First tokenize on spaces for token in self:tokenize(text,state) do if (token.separator) then table.insert(nodelist, SILE.nodefactory.newGlue({ width = gluewidth })) elseif (token.node) then table.insert(nodelist, token.node) else local nodes = self:subItemize(token.string, state) for i= 1,#nodes do nodelist[#nodelist+1] = nodes[i] end end end end, subItemize = function(self,text,options) -- We have a character string; sort it out. local nodelist = {} for token in SU.gtoke(text, "-") do local t2= token.separator and token.separator or token.string nodelist[#(nodelist)+1] = SILE.nodefactory.newUnshaped({ text = t2, options = options }):shape() if token.separator then nodelist[#(nodelist)+1] = SILE.nodefactory.newPenalty({ value = SILE.settings.get("linebreak.hyphenPenalty") }) end end return nodelist end, tokenize = function(self, text, options) -- Do language-specific tokenization pcall(function () SILE.require("languages/"..options.language) end) local tokenizer = SILE.tokenizers[options.language] if not tokenizer then tokenizer = SILE.tokenizers.default end return tokenizer(text) end, shape = function(self, text, options) if not options then options = {} end options = SILE.font.loadDefaults(options) return self:subItemize(text, options) end, addShapedGlyphToNnodeValue = function (self, nnodevalue, shapedglyph) SU.error("Abstract function addShapedGlyphToNnodeValue called", true) end, preAddNodes = function(self, items, nnodeValue) end, createNnodes = function (self, token, options) local items, width = self:shapeToken(token, options) local nnodeContents = {} local glyphs = {} local totalWidth = 0 local depth = 0 local height = 0 local glyphNames = {} local nnodeValue = { text = token, options = options, glyphString = {} } self:preAddNodes(items, nnodeValue) for i = 1,#items do local glyph = items[i] if glyph.depth > depth then depth = glyph.depth end if glyph.height > height then height = glyph.height end totalWidth = totalWidth + glyph.width self:addShapedGlyphToNnodeValue(nnodeValue, glyph) end table.insert(nnodeContents, SILE.nodefactory.newHbox({ depth = depth, height= height, width = width or SILE.length.new({ length = totalWidth }), value = nnodeValue })) -- Why does the nnode contain only one hbox? return { SILE.nodefactory.newNnode({ nodes = nnodeContents, text = token, options = options, language = options.language }) } end }
if not SILE.shapers then SILE.shapers = { } end SILE.tokenizers.default = function(text) return SU.gtoke(text, SILE.settings.get("shaper.spacepattern")) end SILE.settings.declare({ name = "shaper.spacepattern", type = "string", default = "%s+", help = "The Lua pattern used for splitting words on spaces" }) SILE.shapers.base = std.object { -- Return the length of a space character -- with a particular set of font options, -- giving preference to document.spaceskip -- Caching this has no significant speedup measureSpace = function(self, options) local ss = SILE.settings.get("document.spaceskip") if ss then return ss end local i,w = self:shapeToken(" ", options) local spacewidth if w then spacewidth = w.length else if not i[1] then return SILE.length.new() end spacewidth = i[1].width end return SILE.length.new({ length = spacewidth * 1.2, shrink = spacewidth/3, stretch = spacewidth /2 }) -- XXX all rather arbitrary end, measureDim = function (self, char) local options = SILE.font.loadDefaults({}) local i = self:shapeToken(char, options) if char == "x" then return i[1].height else return i[1].width end end, -- Given a text and some font options, return a bunch of boxes shapeToken = function(self, text, options) SU.error("Abstract function shapeToken called", true) end, -- Given font options, select a font. We will handle -- caching here. Returns an arbitrary, implementation-specific -- object (ie a PAL for Pango, font number for libtexpdf, ...) getFace = function(options) SU.error("Abstract function getFace called", true) end, itemize = function(self, nodelist, text) local state = SILE.font.loadDefaults({}) local gluewidth = self:measureSpace(state) -- First tokenize on spaces for token in self:tokenize(text,state) do if (token.separator) then table.insert(nodelist, SILE.nodefactory.newGlue({ width = gluewidth })) elseif (token.node) then table.insert(nodelist, token.node) else local nodes = self:subItemize(token.string, state) for i= 1,#nodes do nodelist[#nodelist+1] = nodes[i] end end end end, subItemize = function(self,text,options) -- We have a character string; sort it out. local nodelist = {} for token in SU.gtoke(text, "-") do local t2= token.separator and token.separator or token.string nodelist[#(nodelist)+1] = SILE.nodefactory.newUnshaped({ text = t2, options = options }) if token.separator then nodelist[#(nodelist)+1] = SILE.nodefactory.newPenalty({ value = SILE.settings.get("linebreak.hyphenPenalty") }) end end return nodelist end, tokenize = function(self, text, options) -- Do language-specific tokenization pcall(function () SILE.require("languages/"..options.language) end) local tokenizer = SILE.tokenizers[options.language] if not tokenizer then tokenizer = SILE.tokenizers.default end return tokenizer(text) end, addShapedGlyphToNnodeValue = function (self, nnodevalue, shapedglyph) SU.error("Abstract function addShapedGlyphToNnodeValue called", true) end, preAddNodes = function(self, items, nnodeValue) end, createNnodes = function (self, token, options) local items, width = self:shapeToken(token, options) local nnodeContents = {} local glyphs = {} local totalWidth = 0 local depth = 0 local height = 0 local glyphNames = {} local nnodeValue = { text = token, options = options, glyphString = {} } self:preAddNodes(items, nnodeValue) for i = 1,#items do local glyph = items[i] if glyph.depth > depth then depth = glyph.depth end if glyph.height > height then height = glyph.height end totalWidth = totalWidth + glyph.width self:addShapedGlyphToNnodeValue(nnodeValue, glyph) end table.insert(nnodeContents, SILE.nodefactory.newHbox({ depth = depth, height= height, width = width or SILE.length.new({ length = totalWidth }), value = nnodeValue })) -- Why does the nnode contain only one hbox? return { SILE.nodefactory.newNnode({ nodes = nnodeContents, text = token, options = options, language = options.language }) } end }
Remove the autoshaping of unshaped nodes. This should get us closer to a fix of #76
Remove the autoshaping of unshaped nodes. This should get us closer to a fix of #76
Lua
mit
neofob/sile,anthrotype/sile,anthrotype/sile,alerque/sile,anthrotype/sile,shirat74/sile,WAKAMAZU/sile_fe,neofob/sile,alerque/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,shirat74/sile,shirat74/sile,simoncozens/sile,simoncozens/sile,neofob/sile,simoncozens/sile,alerque/sile,WAKAMAZU/sile_fe,shirat74/sile,simoncozens/sile,neofob/sile,WAKAMAZU/sile_fe
3ec1064010cab2cfc40f0d41ca42d6e5049b649e
LibCoroutine-1.0.lua
LibCoroutine-1.0.lua
-- A library to make usage of coroutines in wow easier. local MAJOR_VERSION = "LibCoroutine-1.0" local MINOR_VERSION = tonumber(("$Revision: 1023 $"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local AT = LibStub("AceTimer-3.0") local AE = LibStub("AceEvent-3.0") local function running_co_checked() local co = coroutine.running() assert(co, "Sleep should be called inside a coroutine not the main thread") return co end function lib:Create(fn) return coroutine.create(fn) end function lib:Yield(...) return self:Sleep(0, ...) end local function runner(args) local ok, err = coroutine.resume(args[1], unpack(args, 2)) if not ok then error(err) end end function lib:Sleep(t, ...) local co = running_co_checked() AT:ScheduleTimer(runner, t, {co, ...}) return coroutine.yield(co) end local tsubset local function deepequal(a, b) if type(a) == "table" and type(b) == "table" then return tsubset(a, b) and tsubset(b, a) else return a == b end end local function tsubset(t1, t2) for k,v in pairs(t2) do if not deepequal(t1[k], v) then return false end end return true end local function event_checker(event, args, ...) local co = args[1] if deepequal({unpack(args, 3)}, {...}) then -- This will not work before -- http://www.wowace.com/addons/callbackhandler/tickets/5-allow-coroutines-to-be-set-as-self-when-registering/ -- is fixed. AE.UnregisterEvent(co, event) runner(args) else return coroutine.yield(co) end end function lib:WaitForEvent(event, ...) local co = running_co_checked() -- This will not work before -- http://www.wowace.com/addons/callbackhandler/tickets/5-allow-coroutines-to-be-set-as-self-when-registering/ -- is fixed. AE.RegisterEvent(co, event, event_checker, {co, event, ...}) end function lib:RunAsync(fn, ...) local co = self:Create(fn) AT:ScheduleTimer(runner, 0, {co, ...}) end
-- A library to make usage of coroutines in wow easier. local MAJOR_VERSION = "LibCoroutine-1.0" local MINOR_VERSION = tonumber(("$Revision: 1023 $"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local AT = LibStub("AceTimer-3.0") local AE = LibStub("AceEvent-3.0") local function running_co_checked() local co = coroutine.running() assert(co, "Should not be called from the main thread") return co end local function runner(co, ...) local ok, err = coroutine.resume(co, ...) if not ok then error(err) end end function lib:Create(fn) return coroutine.create(fn) end function lib:Yield() return self:Sleep(0) end function lib:Sleep(t) local co = running_co_checked() AT:ScheduleTimer(runner, t, co) return coroutine.yield(co) end local function event_runner(co, event, ...) AE.UnregisterEvent(co, event) runner(co, ...) end function lib:WaitForEvent(event) local co = running_co_checked() AE.RegisterEvent(co, event, event_runner, co) return coroutine.yield(co) end local function message_runner(co, message, ...) AE.UnregisterMessage(co, message) runner(co, ...) end function lib:WaitForMessage(message) local co = running_co_checked() AE.RegisterMessage(co, message, message_runner, co) return coroutine.yield(co) end function lib:RunAsync(fn, ...) local co = self:Create(fn) AT:ScheduleTimer(function(args) runner(args[1], unpack(args, 2)) end, 0, {co, ...}) end -- /run LibStub("LibCoroutine-1.0"):UnitTest() function lib:UnitTest() function RunTests(i) print("running tests async. expecting 1 as arg. got ", i) print("waiting for foo message") lib:WaitForMessage("foo") print("done") print("waiting for foo message with 1 as arg") n = lib:WaitForMessage("foo") print("done. got: ", n) print("sleeping for 1 sec") lib:Sleep(1) print("done") end lib:RunAsync(RunTests, 1) AT:ScheduleTimer(function() AE:SendMessage("foo") end, 1) AT:ScheduleTimer(function() AE:SendMessage("foo", 1) end, 2) end
Add unittest to LibCoroutine. Multiple fixes.
Add unittest to LibCoroutine. Multiple fixes.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp
b1af70d03a346b4e83cb1d71409f8fd03357a23f
test/test-c3.lua
test/test-c3.lua
require "busted.runner" () local assert = require "luassert" describe ("the c3 module", function () it ("can be required", function () assert.has.no.error (function () local C3 = require "c3" end) end) it ("can be instantiated", function () assert.has.no.error (function () local C3 = require "c3" c3 = C3.new { superclass = function (x) return x end, } end) end) it ("runs on the Wikipedia example", function () local o = {} local a = { o, } local b = { o, } local c = { o, } local d = { o, } local e = { o, } local k1 = { c, b, a, } local k2 = { e, b, d, } local k3 = { d, a, } local z = { k3, k2, k1, } local C3 = require "c3" c3 = C3.new { superclass = function (x) return x end, } assert.are.same (c3 (o ), { o, }) assert.are.same (c3 (a ), { o, a, }) assert.are.same (c3 (b ), { o, b, }) assert.are.same (c3 (c ), { o, c, }) assert.are.same (c3 (d ), { o, d, }) assert.are.same (c3 (e ), { o, e, }) assert.are.same (c3 (k1), { o, c, b, a, k1, }) assert.are.same (c3 (k2), { o, e, b, d, k2, }) assert.are.same (c3 (k3), { o, a, d, k3, }) assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, }) end) it ("handles cycles", function () assert.has.no.error (function () local C3 = require "c3" c3 = C3.new { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a assert.are.same (c3 (a), { b, a, }) assert.are.same (c3 (b), { a, b, }) end) end) it ("reports an error in case of conflicting orders", function () assert.has.no.error (function () local C3 = require "c3" c3 = C3.new { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a local c = { a, b, } local assert = require "luassert" local ok, err = pcall (c3, c) assert.is_falsy (ok) assert.is_truthy (err:match "linearization failed") end) end) it ("allows to clear the cache", function () assert.has.no.error (function () local C3 = require "c3" c3 = C3.new { superclass = function (x) return x end, } c3:clear () end) end) end)
require "busted.runner" () local assert = require "luassert" describe ("the c3 module", function () it ("can be required", function () assert.has.no.error (function () require "c3" end) end) it ("can be instantiated", function () assert.has.no.error (function () local C3 = require "c3" C3.new { superclass = function (x) return x end, } end) end) it ("runs on the Wikipedia example", function () local o = {} local a = { o, } local b = { o, } local c = { o, } local d = { o, } local e = { o, } local k1 = { c, b, a, } local k2 = { e, b, d, } local k3 = { d, a, } local z = { k3, k2, k1, } local C3 = require "c3" local c3 = C3.new { superclass = function (x) return x end, } assert.are.same (c3 (o ), { o, }) assert.are.same (c3 (a ), { o, a, }) assert.are.same (c3 (b ), { o, b, }) assert.are.same (c3 (c ), { o, c, }) assert.are.same (c3 (d ), { o, d, }) assert.are.same (c3 (e ), { o, e, }) assert.are.same (c3 (k1), { o, c, b, a, k1, }) assert.are.same (c3 (k2), { o, e, b, d, k2, }) assert.are.same (c3 (k3), { o, a, d, k3, }) assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, }) end) it ("handles cycles", function () assert.has.no.error (function () local C3 = require "c3" local c3 = C3.new { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a assert.are.same (c3 (a), { b, a, }) assert.are.same (c3 (b), { a, b, }) end) end) it ("reports an error in case of conflicting orders", function () assert.has.no.error (function () local C3 = require "c3" local c3 = C3.new { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a local c = { a, b, } local ok, err = pcall (c3, c) assert.is_falsy (ok) assert.is_truthy (err:match "linearization failed") end) end) it ("allows to clear the cache", function () assert.has.no.error (function () local C3 = require "c3" local c3 = C3.new { superclass = function (x) return x end, } c3:clear () end) end) end)
Fix warnings.
Fix warnings.
Lua
mit
saucisson/lua-c3
c12fa6d01b44dfea387120763315b3181f5bb2ad
src/cqueues.lua
src/cqueues.lua
local loader = function(loader, ...) local core = require"_cqueues" local errno = require"_cqueues.errno" local yield = coroutine.yield local resume = coroutine.resume local monotime = core.monotime local running = core.running local strerror = errno.strerror local _POLL = {} function core.poll(...) local _, immediate = running() if immediate then return yield(...) else return yield(_POLL, ...) end end -- core.poll function core.sleep(timeout) core.poll(timeout) end -- core.sleep -- -- Provide coroutine wrappers for inline I/O polling of -- coroutine-wrapped code. The code checks for a special value -- returned by our poll routine (above), and will propogate a yield -- on I/O. Everything else should behave as usual. -- local function _iresume(co, ok, arg1, ...) if ok and arg1 == _POLL then return core.iresume(co, yield(_POLL, ...)) else return ok, arg1, ... end end -- _iresume function core.iresume(co, ...) return _iresume(co, resume(co, ...)) end -- core.iresume local function _iwrap(co, ok, ...) if ok then return ... else error((...), 0) end end -- _iwrap function core.iwrap(f) local co = coroutine.create(f) return function(...) return _iwrap(co, _iresume(co, resume(co, ...))) end end -- core.iwrap local function findwhy(x, ...) if x then if type(x) == "number" then return strerror(x) or x else return tostring(x) end elseif select("#", ...) > 0 then return findwhy(...) else return end end function core.assert(x, ...) if x then return x, ... end return error(findwhy(...), 2) end -- core.assert local step; step = core.interpose("step", function (self, timeout) if core.running() then core.poll(self, timeout) return step(self, 0.0) else return step(self, timeout) end end) -- core:step core.interpose("loop", function (self, timeout) local ok, why if timeout then local curtime = monotime() local deadline = curtime + timeout repeat ok, why = self:step(deadline - curtime) curtime = monotime() until not ok or deadline <= curtime or self:empty() else repeat ok, why = self:step() until not ok or self:empty() end return ok, why end) -- core:loop core.interpose("errors", function (self, timeout) if timeout then local deadline = monotime() + timeout return function () local curtime = monotime() if curtime < deadline then local ok, why = self:loop(deadline - curtime) if not ok then return why end end return --> nothing, to end for loop end else return function () local ok, why = self:loop() if not ok then return why end return --> nothing, to end for loop end end end) -- core:errors core.loader = loader return core end -- loader return loader(loader, ...)
local loader = function(loader, ...) local core = require"_cqueues" local errno = require"_cqueues.errno" local yield = coroutine.yield local resume = coroutine.resume local monotime = core.monotime local running = core.running local strerror = errno.strerror local _POLL = {} function core.poll(...) local _, immediate = running() if immediate then return yield(...) else return yield(_POLL, ...) end end -- core.poll function core.sleep(timeout) core.poll(timeout) end -- core.sleep -- -- Provide coroutine wrappers for multilevel coroutine management to -- allow I/O polling of coroutine-wrapped code. The code checks for -- a special value returned by our poll routine (above), and will -- propogate a yield on I/O. Everything else should behave as usual. -- local function _resume(co, ok, arg1, ...) if ok and arg1 == _POLL then return core.resume(co, yield(_POLL, ...)) else return ok, arg1, ... end end -- _resume function core.resume(co, ...) return _resume(co, resume(co, ...)) end -- core.resume local function _wrap(co, ok, ...) if ok then return ... else error((...), 0) end end -- _wrap function core.wrap(f) local co = coroutine.create(f) return function(...) return _wrap(co, _resume(co, resume(co, ...))) end end -- core.wrap -- -- Many routines return only an integer error number, as errors like -- EAGAIN are very common, and constantly pushing a new string on -- the stack would be inefficient. Also, the failure mode for some -- routines will return multiple false/nil falses which precede the -- error number. This assert routine handles these cases. -- local function findwhy(x, ...) if x then if type(x) == "number" then return strerror(x) or x else return tostring(x) end elseif select("#", ...) > 0 then return findwhy(...) else return end end function core.assert(x, ...) if x then return x, ... end return error(findwhy(...), 2) end -- core.assert -- -- Wrappers for the low-level :step interface to make managing event -- loops slightly easier. -- local step; step = core.interpose("step", function (self, timeout) if core.running() then core.poll(self, timeout) return step(self, 0.0) else return step(self, timeout) end end) -- core:step core.interpose("loop", function (self, timeout) local ok, why if timeout then local curtime = monotime() local deadline = curtime + timeout repeat ok, why = self:step(deadline - curtime) curtime = monotime() until not ok or deadline <= curtime or self:empty() else repeat ok, why = self:step() until not ok or self:empty() end return ok, why end) -- core:loop core.interpose("errors", function (self, timeout) if timeout then local deadline = monotime() + timeout return function () local curtime = monotime() if curtime < deadline then local ok, why = self:loop(deadline - curtime) if not ok then return why end end return --> nothing, to end for loop end else return function () local ok, why = self:loop() if not ok then return why end return --> nothing, to end for loop end end end) -- core:errors core.loader = loader return core end -- loader return loader(loader, ...)
remove the prefix on iresume and iwrap and just call it resume and wrap
remove the prefix on iresume and iwrap and just call it resume and wrap
Lua
mit
bigcrush/cqueues,daurnimator/cqueues,wahern/cqueues,bigcrush/cqueues,wahern/cqueues,daurnimator/cqueues
a836857aa5512a1c8596e629fb7bb468deabc986
state/demo.lua
state/demo.lua
--[[-- DEMO STATE ---- Developer playground. --]]-- local st = GameState.new() local math_max, math_min, math_random, string_char = math.max, math.min, math.random, string.char local RandomBag = require 'lib.pud.randombag' local RingBuffer = require 'lib.hump.ringbuffer' -- set up background music track buffer local _bgm local _bgmbuffer = RingBuffer() local _bgmchar local _bgmvolume = 1.0 -- set up sound bag local _sounds = { 'door', 'hit', 'mdeath', 'miss', 'mouch', 'pdeath', 'pouch', 'quaff', 'stairs', 'trap', 'use', } local _sbag = RandomBag(1,#_sounds) local _sound for i=97,96+NUM_MUSIC do _bgmbuffer:append(i) end for i=1,math_random(NUM_MUSIC) do _bgmbuffer:next() end local function _selectBGM(direction) local i = case(direction) { [-1] = function() return _bgmbuffer:prev() end, [1] = function() return _bgmbuffer:next() end, default = function() return _bgmbuffer:get() end, } _bgmchar = string_char(i) end local function _adjustBGMVolume(amt) _bgmvolume = math_max(0, math_min(1, _bgmvolume + amt)) _bgm:setVolume(_bgmvolume) end local function _playMusic() _bgm = love.audio.play('music/'.._bgmchar..'.ogg', 'stream', true) end local function _playRandomSound() local sound = _sounds[_sbag:next()] _sound = love.audio.play(Sound[sound]) _sound:setVolume(_bgmvolume) end function st:init() _selectBGM(0) _playMusic() _bgm:setVolume(_bgmvolume) end function st:draw() love.graphics.setFont(GameFont.small) love.graphics.setColor(0.6, 0.6, 0.6) love.graphics.print('fps: '..tostring(love.timer.getFPS()), 8, 8) love.graphics.setColor(0.9, 0.8, 0.6) love.graphics.print('[n]ext [p]rev [s]top [g]o', 210, 42) love.graphics.print('[+][-] volume', 210, 84) love.graphics.print('[d]emo a sound', 210, 126) love.graphics.setFont(GameFont.big) love.graphics.setColor(1, 1, 1) love.graphics.print(_bgmchar, 8, 40) love.graphics.print(_bgmvolume, 8, 80) if _sound and not _sound:isStopped() then love.graphics.print(_sounds[_sbag:getLast()], 8, 120) end end function st:keypressed(key, unicode) case(key) { escape = function() love.event.push('q') end, s = function() love.audio.stop(_bgm) end, g = function() love.audio.play(_bgm) end, n = function() love.audio.stop(_bgm) _selectBGM(1) _playMusic() _bgm:setVolume(_bgmvolume) end, p = function() love.audio.stop(_bgm) _selectBGM(-1) _playMusic() _bgm:setVolume(_bgmvolume) end, d = function() _playRandomSound() end, ['-'] = function() _adjustBGMVolume(-0.05) end, ['kp-'] = function() _adjustBGMVolume(-0.05) end, ['+'] = function() _adjustBGMVolume(0.05) end, ['kp+'] = function() _adjustBGMVolume(0.05) end, } end return st
--[[-- DEMO STATE ---- Developer playground. --]]-- local st = GameState.new() local math_max, math_min, math_random, string_char = math.max, math.min, math.random, string.char local RandomBag = require 'lib.pud.randombag' local RingBuffer = require 'lib.hump.ringbuffer' -- set up background music track buffer local _bgm local _bgmbuffer = RingBuffer() local _bgmchar local _bgmvolume = 1.0 -- set up sound bag local _sounds = { 'door', 'hit', 'mdeath', 'miss', 'mouch', 'pdeath', 'pouch', 'quaff', 'stairs', 'trap', 'use', } local _sbag = RandomBag(1,#_sounds) local _sound for i=97,96+NUM_MUSIC do _bgmbuffer:append(i) end for i=1,math_random(NUM_MUSIC) do _bgmbuffer:next() end local function _selectBGM(direction) local i = case(direction) { [-1] = function() return _bgmbuffer:prev() end, [1] = function() return _bgmbuffer:next() end, default = function() return _bgmbuffer:get() end, } _bgmchar = string_char(i) end local function _adjustBGMVolume(amt) _bgmvolume = math_max(0, math_min(1, _bgmvolume + amt)) _bgm:setVolume(_bgmvolume) end local function _playMusic() if _bgm and not _bgm:isStopped() then return end _bgm = love.audio.play('music/'.._bgmchar..'.ogg', 'stream', true) _bgm:setVolume(_bgmvolume) end local function _playRandomSound() local sound = _sounds[_sbag:next()] _sound = love.audio.play(Sound[sound]) _sound:setVolume(_bgmvolume) end function st:enter() _selectBGM(0) end function st:draw() love.graphics.setFont(GameFont.small) love.graphics.setColor(0.3, 0.3, 0.3) love.graphics.print('fps: '..tostring(love.timer.getFPS()), 8, 8) love.graphics.setColor(0.9, 0.8, 0.6) love.graphics.print('[n]ext [p]rev [s]top [g]o', 210, 46) love.graphics.print('[+][-] volume', 210, 88) love.graphics.print('[d]emo a sound', 210, 130) love.graphics.setFont(GameFont.big) local clr = {.1, .8, .1} if not _bgm or _bgm:isStopped() then clr = {.8, .1, .1} end love.graphics.setColor(clr) love.graphics.print(_bgmchar, 8, 44) love.graphics.setColor(1, 1, 1) love.graphics.print(_bgmvolume, 8, 84) if _sound and not _sound:isStopped() then love.graphics.print(_sounds[_sbag:getLast()], 8, 124) end end function st:keypressed(key, unicode) case(key) { escape = function() love.event.push('q') end, s = function() love.audio.stop(_bgm) end, g = function() _playMusic() end, n = function() love.audio.stop(_bgm) _selectBGM(1) _playMusic() end, p = function() love.audio.stop(_bgm) _selectBGM(-1) _playMusic() end, d = function() _playRandomSound() end, ['-'] = function() _adjustBGMVolume(-0.05) end, ['kp-'] = function() _adjustBGMVolume(-0.05) end, ['+'] = function() _adjustBGMVolume(0.05) end, ['kp+'] = function() _adjustBGMVolume(0.05) end, } end return st
fix demo
fix demo
Lua
mit
scottcs/wyx
6866d5331fa14cde62fa31edeb9a97bda02984fb
lua/histogram.lua
lua/histogram.lua
--- Histogram, typically used for latencies local histogram = {} histogram.__index = histogram local serpent = require "Serpent" local log = require "log" function histogram:create() local histo = setmetatable({}, histogram) histo.histo = {} histo.dirty = true return histo end histogram.new = histogram.create setmetatable(histogram, { __call = histogram.create }) function histogram:update(k) if not k then return end self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, { k = k, v = v }) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples local stdDevSum = 0 for k, v in pairs(self.histo) do stdDevSum = stdDevSum + v * (k - self.avg)^2 end self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5 table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) local maxCell = self.sortedHisto[#self.sortedHisto] self.maximum = maxCell.k local minCell = self.sortedHisto[1] self.minimum = minCell.k -- TODO: this is obviously not entirely correct for numbers not divisible by 4 -- however, it doesn't really matter for the number of samples we usually use local quartSamples = self.numSamples / 4 self.quarts = {} local idx = 0 for _, p in ipairs(self.sortedHisto) do -- TODO: inefficient for _ = 1, p.v do if not self.quarts[1] and idx >= quartSamples then self.quarts[1] = p.k elseif not self.quarts[2] and idx >= quartSamples * 2 then self.quarts[2] = p.k elseif not self.quarts[3] and idx >= quartSamples * 3 then self.quarts[3] = p.k break end idx = idx + 1 end end for i = 1, 3 do if not self.quarts[i] then self.quarts[i] = 0/0 end end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:avg() if self.dirty then self:calc() end return self.avg end function histogram:min() if self.dirty then self:calc() end return self.minimum end function histogram:max() if self.dirty then self:calc() end return self.maximum end function histogram:standardDeviation() if self.dirty then self:calc() end return self.stdDev end function histogram:quartiles() if self.dirty then self:calc() end return unpack(self.quarts) end function histogram:median() if self.dirty then self:calc() end return self.quarts[2] end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end -- FIXME: add support for different formats function histogram:print(prefix) if self.dirty then self:calc() end printf("%sSamples: %d, Average: %.1f ns, StdDev: %.1f ns, Quartiles: %.1f/%.1f/%.1f ns", prefix and ("[" .. prefix .. "] ") or "", self.numSamples, self.avg, self.stdDev, unpack(self.quarts)) end function histogram:save(file) if self.dirty then self:calc() end local close = false if type(file) ~= "userdata" then log:info("Saving histogram to '%s'", file) file = io.open(file, "w+") close = true end for i, v in ipairs(self.sortedHisto) do file:write(("%s,%s\n"):format(v.k, v.v)) end if close then file:close() end end function histogram:__serialize() return "require 'histogram'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('histogram')"), true end return histogram
--- Histogram, typically used for latencies local histogram = {} histogram.__index = histogram local serpent = require "Serpent" local log = require "log" function histogram:create() local histo = setmetatable({}, histogram) histo.histo = {} histo.dirty = true return histo end histogram.new = histogram.create setmetatable(histogram, { __call = histogram.create }) function histogram:update(k) if not k then return end self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, { k = k, v = v }) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples local stdDevSum = 0 for k, v in pairs(self.histo) do stdDevSum = stdDevSum + v * (k - self.avg)^2 end self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5 table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) if #self.sortedHisto > 0 then local maxCell = self.sortedHisto[#self.sortedHisto] self.maximum = maxCell.k local minCell = self.sortedHisto[1] self.minimum = minCell.k -- TODO: this is obviously not entirely correct for numbers not divisible by 4 -- however, it doesn't really matter for the number of samples we usually use local quartSamples = self.numSamples / 4 self.quarts = {} local idx = 0 for _, p in ipairs(self.sortedHisto) do -- TODO: inefficient for _ = 1, p.v do if not self.quarts[1] and idx >= quartSamples then self.quarts[1] = p.k elseif not self.quarts[2] and idx >= quartSamples * 2 then self.quarts[2] = p.k elseif not self.quarts[3] and idx >= quartSamples * 3 then self.quarts[3] = p.k break end idx = idx + 1 end end for i = 1, 3 do if not self.quarts[i] then self.quarts[i] = 0/0 end end else self.quarts = {0/0, 0/0, 0/0} -- NaN end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:avg() if self.dirty then self:calc() end return self.avg end function histogram:min() if self.dirty then self:calc() end return self.minimum end function histogram:max() if self.dirty then self:calc() end return self.maximum end function histogram:standardDeviation() if self.dirty then self:calc() end return self.stdDev end function histogram:quartiles() if self.dirty then self:calc() end return unpack(self.quarts) end function histogram:median() if self.dirty then self:calc() end return self.quarts[2] end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end -- FIXME: add support for different formats function histogram:print(prefix) if self.dirty then self:calc() end printf("%sSamples: %d, Average: %.1f ns, StdDev: %.1f ns, Quartiles: %.1f/%.1f/%.1f ns", prefix and ("[" .. prefix .. "] ") or "", self.numSamples, self.avg, self.stdDev, unpack(self.quarts)) end function histogram:save(file) if self.dirty then self:calc() end local close = false if type(file) ~= "userdata" then log:info("Saving histogram to '%s'", file) file = io.open(file, "w+") close = true end for i, v in ipairs(self.sortedHisto) do file:write(("%s,%s\n"):format(v.k, v.v)) end if close then file:close() end end function histogram:__serialize() return "require 'histogram'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('histogram')"), true end return histogram
fix error when printing empty histograms
fix error when printing empty histograms
Lua
mit
libmoon/libmoon,libmoon/libmoon,emmericp/libmoon,scholzd/libmoon,scholzd/libmoon,emmericp/libmoon,emmericp/libmoon,libmoon/libmoon,scholzd/libmoon
b2d63e5f4fbf00ad9a2c2bf1fc4678f1a7204557
TripletCriterion.lua
TripletCriterion.lua
-- Look for shared object local libpath = package.searchpath('libtriplet', package.cpath) if not libpath then return end local ffi = require 'ffi' local C = ffi.load(libpath) ffi.cdef[[ void updateOutput( THCState* state, THCudaTensor* input, THCudaTensor* label, float norm, float alpha, int samples, int nb_blocks, THCudaTensor* dist, THCudaTensor* emb, THCudaTensor* loss ); void updateGradInput( THCState* state, THCudaTensor* input, THCudaTensor* emb, THCudaTensor* loss, THCudaTensor* gradInput ); ]] local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion') function TripletCriterion:__init(samples, blocks, norm, margin) parent.__init(self) self.norm = norm or 2 self.alpha = margin or 0.2 self.samples = samples or 1 -- use all anchor-positive pairs for (>1) self.blocks = blocks or 0 if self.samples > 1 then assert(self.blocks ~= 0) end self.dist = torch.Tensor() self.embeddings = torch.Tensor() self.loss = torch.Tensor() end function TripletCriterion:updateOutput(input, target) assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)') assert(input:size(1) >= self.samples*self.blocks) if input:type() == 'torch.CudaTensor' then -- kernel call C.updateOutput( cutorch.getState(), input:cdata(), target:cdata(), self.norm, self.alpha, self.samples, self.blocks, self.dist:cdata(), self.embeddings:cdata(), self.loss:cdata() ) else local nb_batch = input:size(1) local length = input:size(2) -------------------------------------------------------------------------- -- BUG allert -------------------------------------------------------------------------- local nb_blocks = math.floor(nb_batch/self.samples) -------------------------------------------------------------------------- -- should be simply nb_batch = self.blocks -- Otherwise we enter the trash area! -------------------------------------------------------------------------- -- calculate distance matrix self.dist:resize(nb_batch, nb_batch) for i = 1, nb_batch do for j = i, nb_batch do if j == i then self.dist[i][j] = 0 else self.dist[i][j] = torch.dist(input[i], input[j], self.norm) self.dist[j][i] = self.dist[i][j] end end end -- find pos/neg embeddings indices -- (i) hard anchor-positive pair if self.samples == 1 then self.embeddings:resize(nb_batch, 3) for i = 1, nb_batch do local ipos = i local vpos = 0 local ineg = i local vneg = math.huge for j = 1, nb_batch do if (target[j] == target[i]) and (vpos < self.dist[i][j]) then ipos = j vpos = self.dist[i][j] end end for j = 1, nb_batch do if (target[j] ~= target[i]) and (vpos < self.dist[i][j]) and (vneg > self.dist[i][j]) then ineg = j vneg = self.dist[i][j] end end self.embeddings[i][1] = i self.embeddings[i][2] = ipos self.embeddings[i][3] = ineg end -- (ii) all anchor-positive pairs elseif self.samples > 1 then -- calculate nb of all pairs self.embeddings:resize(nb_batch*(self.samples-1), 3):zero() -- repeat batch (samples-1) times for i = 0, self.samples-2 do for j = 0, nb_blocks-1 do for k = 0, self.samples-1 do -- pick an element in distance matrix local row = j*self.samples + k + 1 local col = j*self.samples + i + 1 col = col < row and col or col + 1 -- find positive embedding local ipos = col local vpos = self.dist[row][col] -- find negative embedding local ineg = row local vneg = math.huge for l = self.samples*self.blocks+1, nb_batch do if target[l] ~= target[row] and self.dist[row][l] > vpos and self.dist[row][l] < vneg then ineg = l vneg = self.dist[row][l] end end self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg end end end end -- compute loss self.loss:resize(self.embeddings:size(1)) for i = 1, self.embeddings:size(1) do -- do not penalize if negative is not found if self.embeddings[i][1] == self.embeddings[i][3] then self.loss[i] = 0 else local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2) local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2) self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an) end end end if self.samples > 1 then self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1)) else self.output = self.loss:sum()/input:size(1) end return self.output end function TripletCriterion:updateGradInput(input, target) --self:updateOutput(input, target) local length = input:size(2) local nb_pairs = self.loss:size(1) self.gradInput:resize(nb_pairs, length) if input:type() == 'torch.CudaTensor' then -- Kernel call C.updateGradInput( cutorch.getState(), input:cdata(), self.embeddings:cdata(), self.loss:cdata(), self.gradInput ) --input.THNN.TripletCriterion_updateGradInput(self, input, target) else for i = 1, nb_pairs do if self.loss[i] > 0 then self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs else self.gradInput[i] = 0 end end end local nb_backwards = math.max(1, self.samples-1) local nb_batch = input:size(1) self.gradInput = self.gradInput:view(nb_backwards, nb_batch, length):sum(1):squeeze() return self.gradInput end
-- Look for shared object local libpath = package.searchpath('libtriplet', package.cpath) if not libpath then return end local ffi = require 'ffi' local C = ffi.load(libpath) ffi.cdef[[ void updateOutput( THCState* state, THCudaTensor* input, THCudaTensor* label, float norm, float alpha, int samples, int nb_blocks, THCudaTensor* dist, THCudaTensor* emb, THCudaTensor* loss ); void updateGradInput( THCState* state, THCudaTensor* input, THCudaTensor* emb, THCudaTensor* loss, THCudaTensor* gradInput ); ]] local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion') function TripletCriterion:__init(samples, blocks, norm, margin) parent.__init(self) self.norm = norm or 2 self.alpha = margin or 0.2 self.samples = samples or 1 -- use all anchor-positive pairs for (>1) self.blocks = blocks or 0 if self.samples > 1 then assert(self.blocks ~= 0) end self.dist = torch.Tensor() self.embeddings = torch.Tensor() self.loss = torch.Tensor() end function TripletCriterion:updateOutput(input, target) assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)') assert(input:size(1) >= self.samples*self.blocks) if input:type() == 'torch.CudaTensor' then -- kernel call C.updateOutput( cutorch.getState(), input:cdata(), target:cdata(), self.norm, self.alpha, self.samples, self.blocks, self.dist:cdata(), self.embeddings:cdata(), self.loss:cdata() ) else local nb_batch = input:size(1) local length = input:size(2) -- calculate distance matrix self.dist:resize(nb_batch, nb_batch) for i = 1, nb_batch do for j = i, nb_batch do if j == i then self.dist[i][j] = 0 else self.dist[i][j] = torch.dist(input[i], input[j], self.norm) self.dist[j][i] = self.dist[i][j] end end end -- find pos/neg embeddings indices -- (i) hard anchor-positive pair if self.samples == 1 then self.embeddings:resize(nb_batch, 3) for i = 1, nb_batch do local ipos = i local vpos = 0 local ineg = i local vneg = math.huge for j = 1, nb_batch do if (target[j] == target[i]) and (vpos < self.dist[i][j]) then ipos = j vpos = self.dist[i][j] end end for j = 1, nb_batch do if (target[j] ~= target[i]) and (vpos < self.dist[i][j]) and (vneg > self.dist[i][j]) then ineg = j vneg = self.dist[i][j] end end self.embeddings[i][1] = i self.embeddings[i][2] = ipos self.embeddings[i][3] = ineg end -- (ii) all anchor-positive pairs elseif self.samples > 1 then -- calculate nb of all pairs self.embeddings:resize(nb_batch*(self.samples-1), 3):fill(1) -- repeat batch (samples-1) times for i = 0, self.samples-2 do for j = 0, self.blocks-1 do for k = 0, self.samples-1 do -- pick an element in distance matrix local row = j*self.samples + k + 1 local col = j*self.samples + i + 1 col = col < row and col or col + 1 -- find positive embedding local ipos = col local vpos = self.dist[row][col] -- find negative embedding local ineg = row local vneg = math.huge for l = self.samples*self.blocks+1, nb_batch do if target[l] ~= target[row] and self.dist[row][l] > vpos and self.dist[row][l] < vneg then ineg = l vneg = self.dist[row][l] end end self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg end end end end -- compute loss self.loss:resize(self.embeddings:size(1)) for i = 1, self.embeddings:size(1) do -- do not penalize if negative is not found if self.embeddings[i][1] == self.embeddings[i][3] then self.loss[i] = 0 else local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2) local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2) self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an) end end end if self.samples > 1 then self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1)) else self.output = self.loss:sum()/input:size(1) end return self.output end function TripletCriterion:updateGradInput(input, target) --self:updateOutput(input, target) local length = input:size(2) local nb_pairs = self.loss:size(1) self.gradInput:resize(nb_pairs, length) if input:type() == 'torch.CudaTensor' then -- Kernel call C.updateGradInput( cutorch.getState(), input:cdata(), self.embeddings:cdata(), self.loss:cdata(), self.gradInput ) --input.THNN.TripletCriterion_updateGradInput(self, input, target) else for i = 1, nb_pairs do if self.loss[i] > 0 then self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs else self.gradInput[i] = 0 end end end local nb_backwards = math.max(1, self.samples-1) local nb_batch = input:size(1) self.gradInput = self.gradInput:view(nb_backwards, nb_batch, length):sum(1):squeeze() return self.gradInput end
Bug fix: avoid invasion of trash area
Bug fix: avoid invasion of trash area
Lua
mit
jhjin/triplet-criterion
c2d68da910a1b993b78742504fde40b5681c3f8d
eqn/adm1d_v2.lua
eqn/adm1d_v2.lua
--[[ Based on the Alcubierre 1997 "The appearance of coorindate shocks in hyperbolic formalisms of General Relativity". This is also a 1D version of the 3D formalism in the Alcubierre 2008 book "Introduction to 3+1 Numerical Relativity" on the chapter on hyperbolic formalisms. a_x,t + (alpha f K_xx / gamma_xx),x = 0 d_xxx,t + (alpha K_xx),x = 0 K_xx,t + (alpha a_x),x = (alpha / gamma_xx) (a_x d_xxx - K_xx^2) for d_xxx = 1/2 gamma_xx,x expanded: a_x,t + alpha,x f K_xx / gamma_xx + alpha f,x K_xx / gamma_xx + alpha f K_xx,x / gamma_xx - alpha f K_xx / gamma_xx^2 gamma_xx,x = 0 a_x,t + alpha f / gamma_xx K_xx,x = alpha K_xx / gamma_xx (f (2 d_xxx / gamma_xx - a_x) - alpha a_x f') d_xxx,t + alpha,x K_xx + alpha K_xx,x = 0 d_xxx,t + alpha K_xx,x = -alpha a_x K_xx K_xx,t + alpha,x a_x + alpha a_x,x = alpha / gamma_xx (a_x d_xxx - K_xx^2) K_xx,t + alpha a_x,x = alpha ((a_x d_xxx - K_xx^2) / gamma_xx - a_x^2) [ a_x ] [ 0, 0, alpha f / gamma_xx ] [ a_x ] [ alpha K_xx / gamma_xx (f (2 d_xxx / gamma_xx - a_x) - alpha a_x f') ] [d_xxx] + [ 0, 0, alpha ] [d_xxx] = [ -alpha a_x K_xx ] [ K_xx],t [ alpha, 0, 0 ] [ K_xx],x [ alpha ((a_x d_xxx - K_xx^2) / gamma_xx - a_x^2) ] ... has eigenvalues ... Lambda = {-alpha sqrt(f/gamma_xx), 0, alpha sqrt(f/gamma_xx)} ... and eigenvectors ... [ sqrt(f/gamma_xx), 0, sqrt(f/gamma_xx) ] Q = [ sqrt(gamma_xx/f), 1, sqrt(gamma_xx/f) ] [ -1, 0, 1 ] [ sqrt(gamma_xx/f)/2, 0, -1/2 ] Q^-1 = [ -gamma_xx/f, 1, 0 ] [ sqrt(gamma_xx/f)/2, 0, 1/2 ] corresponding eigenfields: ( should be a_x - f d_xxx / gamma_xx, sqrt(f) K_xx / gamma_xx \pm a_x / sqrt(gamma_xx) ) eigenfields: [ sqrt(gamma_xx/f)/2, 0, -1/2 ] [ a_x,a ] [ -gamma_xx/f, 1, 0 ] [d_xxx,a] [ sqrt(gamma_xx/f)/2, 0, 1/2 ] [ K_xx,a] 1/2 (sqrt(gamma_xx / f) a_x,a - K_xx,a) ... * -2 * sqrt(f) / gamma_xx -gamma_xx / f a_x,a + d_xxx,a ... * -f / gamma_xx 1/2 (sqrt(gamma_xx / f) a_x,a + K_xx,a) ... * 2 * sqrt(f) / gamma_xx sqrt(f) / gamma_xx K_xx,a - 1 / sqrt(gamma_xx) a_x,a <- check a_x,a - f / gamma_xx * d_xxx,a <- check sqrt(f) / gamma_xx K_xx,a + 1 / sqrt(gamma_xx) a_x,a <- check same system, favoring flux terms, incorporating alpha and gamma to do just that ... (I'm trying to figure out why adding in the extra source terms that come from linearizing wrt the primitive variables messes the equation up, but removing them works fine) [ alpha ] [ 0, 0, 0, 0, 0 ] [ alpha ] [ -alpha^2 f K ] [gamma_xx] [ 0, 0, 0, 0, 0 ] [gamma_xx] [ -2 alpha K_xx ] [ a_x ] + [ alpha^2 K_xx / gamma_xx (f + alpha f'), -alpha K_xx f / gamma_xx^2, 0, 0, alpha f / gamma_xx ] [ a_x ] = [ 0 ] [ d_xxx ] [ alpha^2 K_xx, 0, 0, 0, alpha ] [ d_xxx ] [ 0 ] [ K_xx ],t [ alpha^2 a_x, 0, alpha, 0, 0 ] [ K_xx ],x [ alpha / gamma_xx (a_x d_xxx - K_xx^2) ] ...and voila, our source term now matches up with what the paper says. the catch? finding the eigenvectors is difficult, since the eigenvalues are +-alpha sqrt(f/gamma_xx) and 0 x3 for this reason I use the eigenfields, and it reconstructs the above matrix all except the alpha and gamma columns ... so why can't those terms go into the source? why do I have to use a matrix that reconstructs without them? --]] local class = require 'ext.class' local table = require 'ext.table' local file = require 'ext.file' local template = require 'template' local Equation = require 'eqn.eqn' local ADM_BonaMasso_1D_Alcubierre1997 = class(Equation) ADM_BonaMasso_1D_Alcubierre1997.name = 'ADM_BonaMasso_1D_Alcubierre1997' ADM_BonaMasso_1D_Alcubierre1997.numStates = 5 ADM_BonaMasso_1D_Alcubierre1997.numWaves = 3 ADM_BonaMasso_1D_Alcubierre1997.consVars = {'alpha', 'gamma_xx', 'a_x', 'd_xxx', 'K_xx'} ADM_BonaMasso_1D_Alcubierre1997.mirrorVars = {{'gamma_xx', 'a_x', 'd_xxx', 'K_xx'}} ADM_BonaMasso_1D_Alcubierre1997.hasEigenCode = true ADM_BonaMasso_1D_Alcubierre1997.useSourceTerm = true ADM_BonaMasso_1D_Alcubierre1997.initStates = require 'init.adm' function ADM_BonaMasso_1D_Alcubierre1997:getCodePrefix() local initState = self.initStates[self.solver.initStatePtr[0]+1] local alphaVar = require 'symmath'.var'alpha' local fGuiVar = self.guiVarsForName.f local fCode = fGuiVar.options[fGuiVar.value[0]+1] local fExpr = assert(loadstring('local alpha = ... return '..fCode))(alphaVar) self.codes = initState.init(self.solver, { f = fExpr, alphaVar = alphaVar, }) return table.map(self.codes, function(code,name,t) return 'real calc_'..name..code, #t+1 end):concat'\n' end ADM_BonaMasso_1D_Alcubierre1997.guiVars = { require 'guivar.combo'{ name = 'f', options = {'1', '1.69', '.49', '1 + 1/alpha^2'}, } } function ADM_BonaMasso_1D_Alcubierre1997:getInitStateCode() return template([[ kernel void initState( global <?=eqn.cons_t?>* UBuf ) { SETBOUNDS(0,0); real3 x = cell_x(i); global <?=eqn.cons_t?>* U = UBuf + index; U->alpha = calc_alpha(x.x, x.y, x.z); U->gamma_xx = calc_gamma_xx(x.x, x.y, x.z); U->a_x = calc_a_x(x.x, x.y, x.z); U->d_xxx = calc_d_xxx(x.x, x.y, x.z); U->K_xx = calc_K_xx(x.x, x.y, x.z); } ]], { eqn = self, }) end function ADM_BonaMasso_1D_Alcubierre1997:getSolverCode() return template(file['eqn/adm1d_v2.cl'], {eqn=self, solver=self.solver}) end function ADM_BonaMasso_1D_Alcubierre1997:getDisplayVars() return { -- source-only: {alpha = 'value = U->alpha;'}, {gamma_xx = 'value = U->gamma_xx;'}, -- both 1998 and 2008 cons vars: {a_x = 'value = U->a_x;'}, -- 1998-only cons vars: {d_xxx = 'value = U->d_xxx;'}, {K_xx = 'value = U->K_xx;'}, -- 2008-only cons vars: {D_g = 'value = 2. * U->d_xxx / U->gamma_xx;'}, {KTilde_xx = 'value = U->K_xx * sqrt(U->gamma_xx);'}, -- aux: {dx_alpha = 'value = U->alpha * U->a_x;'}, {dx_gamma_xx = 'value = 2. * U->d_xxx;'}, {volume = 'value = U->alpha * sqrt(U->gamma_xx);'}, } end local eigenVars = {'alpha', 'sqrt_f_over_gamma_xx'} function ADM_BonaMasso_1D_Alcubierre1997:getEigenTypeCode() return require 'eqn.makestruct'(self.eigen_t, eigenVars) end function ADM_BonaMasso_1D_Alcubierre1997:getEigenDisplayVars() return table.map(eigenVars, function(var) return {[var] = 'value = eigen->'..var..';'} end) end return ADM_BonaMasso_1D_Alcubierre1997
--[[ Based on the Alcubierre 1997 "The appearance of coorindate shocks in hyperbolic formalisms of General Relativity". This is also a 1D version of the 3D formalism in the Alcubierre 2008 book "Introduction to 3+1 Numerical Relativity" on the chapter on hyperbolic formalisms. a_x,t + (alpha f K_xx / gamma_xx),x = 0 d_xxx,t + (alpha K_xx),x = 0 K_xx,t + (alpha a_x),x = (alpha / gamma_xx) (a_x d_xxx - K_xx^2) for d_xxx = 1/2 gamma_xx,x expanded: a_x,t + alpha,x f K_xx / gamma_xx + alpha f,x K_xx / gamma_xx + alpha f K_xx,x / gamma_xx - alpha f K_xx / gamma_xx^2 gamma_xx,x = 0 a_x,t + alpha f / gamma_xx K_xx,x = alpha K_xx / gamma_xx (f (2 d_xxx / gamma_xx - a_x) - alpha a_x f') d_xxx,t + alpha,x K_xx + alpha K_xx,x = 0 d_xxx,t + alpha K_xx,x = -alpha a_x K_xx K_xx,t + alpha,x a_x + alpha a_x,x = alpha / gamma_xx (a_x d_xxx - K_xx^2) K_xx,t + alpha a_x,x = alpha ((a_x d_xxx - K_xx^2) / gamma_xx - a_x^2) [ a_x ] [ 0, 0, alpha f / gamma_xx ] [ a_x ] [ alpha K_xx / gamma_xx (f (2 d_xxx / gamma_xx - a_x) - alpha a_x f') ] [d_xxx] + [ 0, 0, alpha ] [d_xxx] = [ -alpha a_x K_xx ] [ K_xx],t [ alpha, 0, 0 ] [ K_xx],x [ alpha ((a_x d_xxx - K_xx^2) / gamma_xx - a_x^2) ] ... has eigenvalues ... Lambda = {-alpha sqrt(f/gamma_xx), 0, alpha sqrt(f/gamma_xx)} ... and eigenvectors ... [ sqrt(f/gamma_xx), 0, sqrt(f/gamma_xx) ] Q = [ sqrt(gamma_xx/f), 1, sqrt(gamma_xx/f) ] [ -1, 0, 1 ] [ sqrt(gamma_xx/f)/2, 0, -1/2 ] Q^-1 = [ -gamma_xx/f, 1, 0 ] [ sqrt(gamma_xx/f)/2, 0, 1/2 ] corresponding eigenfields: ( should be a_x - f d_xxx / gamma_xx, sqrt(f) K_xx / gamma_xx \pm a_x / sqrt(gamma_xx) ) eigenfields: [ sqrt(gamma_xx/f)/2, 0, -1/2 ] [ a_x,a ] [ -gamma_xx/f, 1, 0 ] [d_xxx,a] [ sqrt(gamma_xx/f)/2, 0, 1/2 ] [ K_xx,a] 1/2 (sqrt(gamma_xx / f) a_x,a - K_xx,a) ... * -2 * sqrt(f) / gamma_xx -gamma_xx / f a_x,a + d_xxx,a ... * -f / gamma_xx 1/2 (sqrt(gamma_xx / f) a_x,a + K_xx,a) ... * 2 * sqrt(f) / gamma_xx sqrt(f) / gamma_xx K_xx,a - 1 / sqrt(gamma_xx) a_x,a <- check a_x,a - f / gamma_xx * d_xxx,a <- check sqrt(f) / gamma_xx K_xx,a + 1 / sqrt(gamma_xx) a_x,a <- check same system, favoring flux terms, incorporating alpha and gamma to do just that ... (I'm trying to figure out why adding in the extra source terms that come from linearizing wrt the primitive variables messes the equation up, but removing them works fine) [ alpha ] [ 0, 0, 0, 0, 0 ] [ alpha ] [ -alpha^2 f K ] [gamma_xx] [ 0, 0, 0, 0, 0 ] [gamma_xx] [ -2 alpha K_xx ] [ a_x ] + [ alpha^2 K_xx / gamma_xx (f + alpha f'), -alpha K_xx f / gamma_xx^2, 0, 0, alpha f / gamma_xx ] [ a_x ] = [ 0 ] [ d_xxx ] [ alpha^2 K_xx, 0, 0, 0, alpha ] [ d_xxx ] [ 0 ] [ K_xx ],t [ alpha^2 a_x, 0, alpha, 0, 0 ] [ K_xx ],x [ alpha / gamma_xx (a_x d_xxx - K_xx^2) ] ...and voila, our source term now matches up with what the paper says. the catch? finding the eigenvectors is difficult, since the eigenvalues are +-alpha sqrt(f/gamma_xx) and 0 x3 for this reason I use the eigenfields, and it reconstructs the above matrix all except the alpha and gamma columns ... so why can't those terms go into the source? why do I have to use a matrix that reconstructs without them? --]] local class = require 'ext.class' local table = require 'ext.table' local file = require 'ext.file' local template = require 'template' local Equation = require 'eqn.eqn' local ADM_BonaMasso_1D_Alcubierre1997 = class(Equation) ADM_BonaMasso_1D_Alcubierre1997.name = 'ADM_BonaMasso_1D_Alcubierre1997' ADM_BonaMasso_1D_Alcubierre1997.numStates = 5 ADM_BonaMasso_1D_Alcubierre1997.numWaves = 3 ADM_BonaMasso_1D_Alcubierre1997.consVars = {'alpha', 'gamma_xx', 'a_x', 'd_xxx', 'K_xx'} ADM_BonaMasso_1D_Alcubierre1997.mirrorVars = {{'gamma_xx', 'a_x', 'd_xxx', 'K_xx'}} ADM_BonaMasso_1D_Alcubierre1997.hasEigenCode = true ADM_BonaMasso_1D_Alcubierre1997.useSourceTerm = true ADM_BonaMasso_1D_Alcubierre1997.initStates = require 'init.adm' function ADM_BonaMasso_1D_Alcubierre1997:getCodePrefix() local initState = self.initStates[self.solver.initStatePtr[0]+1] local alphaVar = require 'symmath'.var'alpha' local fGuiVar = self.guiVarsForName.f local fCode = fGuiVar.options[fGuiVar.value[0]+1] local fExpr = assert(loadstring('local alpha = ... return '..fCode))(alphaVar) self.codes = initState.init(self.solver, { f = fExpr, alphaVar = alphaVar, }) return table.map(self.codes, function(code,name,t) return 'real calc_'..name..code, #t+1 end):concat'\n' end ADM_BonaMasso_1D_Alcubierre1997.guiVars = { require 'guivar.combo'{ name = 'f', options = {'1', '1.69', '.49', '1 + 1/alpha^2'}, } } function ADM_BonaMasso_1D_Alcubierre1997:getInitStateCode() return template([[ kernel void initState( global <?=eqn.cons_t?>* UBuf ) { SETBOUNDS(0,0); real3 x = cell_x(i); global <?=eqn.cons_t?>* U = UBuf + index; U->alpha = calc_alpha(x.x, x.y, x.z); U->gamma_xx = calc_gamma_xx(x.x, x.y, x.z); U->a_x = calc_a_x(x.x, x.y, x.z); U->d_xxx = calc_d_xxx(x.x, x.y, x.z); U->K_xx = calc_K_xx(x.x, x.y, x.z); } ]], { eqn = self, }) end function ADM_BonaMasso_1D_Alcubierre1997:getSolverCode() return template(file['eqn/adm1d_v2.cl'], {eqn=self, solver=self.solver}) end function ADM_BonaMasso_1D_Alcubierre1997:getDisplayVars() return { -- source-only: {alpha = 'value = U->alpha;'}, {gamma_xx = 'value = U->gamma_xx;'}, -- both 1998 and 2008 cons vars: {a_x = 'value = U->a_x;'}, -- 1998-only cons vars: {d_xxx = 'value = U->d_xxx;'}, {K_xx = 'value = U->K_xx;'}, -- 2008-only cons vars: {D_g = 'value = 2. * U->d_xxx / U->gamma_xx;'}, {KTilde = 'value = U->K_xx / sqrt(U->gamma_xx);'}, -- aux: {dx_alpha = 'value = U->alpha * U->a_x;'}, {dx_gamma_xx = 'value = 2. * U->d_xxx;'}, {volume = 'value = U->alpha * sqrt(U->gamma_xx);'}, {f = 'value = calc_f(U->alpha);'}, {['df/dalpha'] = 'value = calc_dalpha_f(U->alpha);'}, } end local eigenVars = {'alpha', 'sqrt_f_over_gamma_xx'} function ADM_BonaMasso_1D_Alcubierre1997:getEigenTypeCode() return require 'eqn.makestruct'(self.eigen_t, eigenVars) end function ADM_BonaMasso_1D_Alcubierre1997:getEigenDisplayVars() return table.map(eigenVars, function(var) return {[var] = 'value = eigen->'..var..';'} end) end return ADM_BonaMasso_1D_Alcubierre1997
fixed the v2 display vars
fixed the v2 display vars
Lua
mit
thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua
87f9b7970c81d30f971f9256866f3d7092b03dac
hammerspoon/do-not-disturb.lua
hammerspoon/do-not-disturb.lua
-------------------------------------------------------------------------------- --- Function --- Determine whether "Do Not Disturb" is enabled. --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether "Do Not Disturb" is enabled. -------------------------------------------------------------------------------- function isDoNotDisturbEnabled() local command = 'defaults -currentHost read com.apple.notificationcenterui doNotDisturb' mode, _, _, _ = hs.execute(command) return tonumber(mode) == 1 end -------------------------------------------------------------------------------- --- Function --- Toggle "Do Not Disturb". --- --- Parameters: --- * None --- --- Returns: --- * Nothing -------------------------------------------------------------------------------- function toggleDoNotDisturb() local applescript = [[ tell application "System Events" to tell process "SystemUIServer" key down option click menu bar item 1 of menu bar 1 key up option end tell ]] hs.osascript.applescript(applescript) end -------------------------------------------------------------------------------- -- Bind URL for toggling the macOS "Do Not Disturb" setting: -- -- hammerspoon://toggle-do-not-disturb -------------------------------------------------------------------------------- hs.urlevent.bind("toggle-do-not-disturb", toggleDoNotDisturb) -------------------------------------------------------------------------------- --- Function --- Set "Do Not Disturb" state. --- --- Parameters: --- * state - A boolean value. True to enable "Do Not Disturb"; False to --- disable it --- --- Returns: --- * Nothing -------------------------------------------------------------------------------- function setDoNotDisturb(state) if state ~= isDoNotDisturbEnabled() then toggleDoNotDisturb() end end
-------------------------------------------------------------------------------- --- Function --- Determine whether "Do Not Disturb" is enabled. --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether "Do Not Disturb" is enabled. -------------------------------------------------------------------------------- function isDoNotDisturbEnabled() local command = 'defaults -currentHost read com.apple.notificationcenterui doNotDisturb' mode, _, _, _ = hs.execute(command) return tonumber(mode) == 1 end -------------------------------------------------------------------------------- --- Function --- Toggle "Do Not Disturb". --- --- Depends on https://github.com/sindresorhus/do-not-disturb-cli being --- installed on the system. --- --- Parameters: --- * None --- --- Returns: --- * Nothing -------------------------------------------------------------------------------- function toggleDoNotDisturb() local _, status, exit, code = hs.execute('/usr/local/bin/do-not-disturb toggle', true) if (not (status == true and exit == 'exit' and code == 0)) then hs.alert("Whoops! Toggling 'Do Not Disturb' failed.") local alertDurationInSeconds = 4 hs.alert( "Make sure you have sindresorhus/do-not-disturb-cli installed and try again.", hs.alert.defaultStyle, hs.screen.mainScreen(), alertDurationInSeconds ) end end -------------------------------------------------------------------------------- -- Bind URL for toggling the macOS "Do Not Disturb" setting: -- -- hammerspoon://toggle-do-not-disturb -------------------------------------------------------------------------------- hs.urlevent.bind("toggle-do-not-disturb", toggleDoNotDisturb) -------------------------------------------------------------------------------- --- Function --- Set "Do Not Disturb" state. --- --- Parameters: --- * state - A boolean value. True to enable "Do Not Disturb"; False to --- disable it --- --- Returns: --- * Nothing -------------------------------------------------------------------------------- function setDoNotDisturb(state) if state ~= isDoNotDisturbEnabled() then toggleDoNotDisturb() end end
Use sindresorhus/do-not-disturb-cli to toggle "Do Not Disturb"
Use sindresorhus/do-not-disturb-cli to toggle "Do Not Disturb" Ever since upgrading to macOS Mojave, using AppleScript to toggle "Do Not Disturb" has been fairly buggy for me. I suspect it's related to the updated permission rules in Mojave. sindresorhus/do-not-disturb-cli seems to do the trick though, so let's use it!
Lua
mit
jasonrudolph/dotfiles,jasonrudolph/dotfiles,jasonrudolph/dotfiles,jasonrudolph/dotfiles
d1d330ecfcfe2feb540da9797d484609f53ac592
esp8266/sta_mode.lua
esp8266/sta_mode.lua
function writeSerialCommand(command) for i, byte in pairs(command) do uart.write(0, string.char(byte)) end uart.write(0, string.char(10)) end uart.setup(0, 9600, 8, 0, 1, 0) conn=net.createConnection(net.TCP, 0) conn:connect(1337, "tdc2.turningdigital.com") conn:on("connection", function(conn) conn:send(u..":"..p) end) tmr.alarm(1, 300000, 1, function() conn:send(u..":heartbeat") tmr.alarm(2, 15000, 1, function() node.restart() end) end) conn:on("receive", function(conn, data) params = {} for param in string.gmatch(data, "(%w+)") do table.insert(params, param) end if params[1] ~= nill then if params[1] == "ACK" then tmr.stop(2) else if params[1] == "showcolor" then writeSerialCommand({ 0xF0, params[2], params[3], params[4] }) elseif params[1] == "setbrightness" then writeSerialCommand({ 0xF1, params[2] }) elseif params[1] == "alternatecolors" then writeSerialCommand({ 0xF2, params[2], params[3], params[4], params[5], params[6], params[7], params[8] }) elseif params[1] == "twocolor" then writeSerialCommand({ 0xF3, params[2], params[3], params[4], params[5], params[6], params[7] }) elseif params[1] == "flashcolor" then writeSerialCommand({ 0xF4, params[2], params[3], params[4], params[5] }) elseif params[1] == "showrainbow" then writeSerialCommand({ 0xF5, params[2] }) elseif params[1] == "fade" then writeSerialCommand({ 0xF6, params[2], params[3], params[4], params[5] }) end end end end)
function writeSerialCommand(command) for i, byte in pairs(command) do uart.write(0, string.char(byte)) end uart.write(0, string.char(10)) end uart.setup(0, 9600, 8, 0, 1, 0) conn=net.createConnection(net.TCP, 0) conn:connect(1337, "tdc2.turningdigital.com") conn:on("connection", function(conn) conn:send(u..":"..p) end) tmr.alarm(1, 300000, 1, function() conn:send(u..":heartbeat") tmr.alarm(2, 15000, 1, function() node.restart() end) end) conn:on("receive", function(conn, data) params = {} for param in string.gmatch(data, "(%w+)") do table.insert(params, param) end if params[1] ~= nill then if params[1] == "ACK" then tmr.stop(2) else if params[1] == "showcolor" then writeSerialCommand({ 0xF0, params[2], params[3], params[4] }) elseif params[1] == "setbrightness" then writeSerialCommand({ 0xF1, params[2] }) elseif params[1] == "alternatecolors" then writeSerialCommand({ 0xF2, params[2], params[3], params[4], params[5], params[6], params[7], params[8] }) elseif params[1] == "twocolor" then writeSerialCommand({ 0xF3, params[2], params[3], params[4], params[5], params[6], params[7] }) elseif params[1] == "flashcolor" then writeSerialCommand({ 0xF4, params[2] }) elseif params[1] == "showrainbow" then writeSerialCommand({ 0xF5, params[2] }) elseif params[1] == "fade" then writeSerialCommand({ 0xF6, params[2] }) end end end end)
Fix ups
Fix ups
Lua
mit
ttosi/moodbeam,ttosi/moodbeam,ttosi/moodbeam
e215d77087a81a619a241e24077b5066929a2aa2
xmake/core/main.lua
xmake/core/main.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- define module: main local main = main or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local option = require("base/option") local profiler = require("base/profiler") local deprecated = require("base/deprecated") local task = require("project/task") local history = require("project/history") -- init the option menu local menu = { -- title title = "XMake v" .. xmake._VERSION .. ", The Make-like Build Utility based on Lua" -- copyright , copyright = "Copyright (C) 2015-2016 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}" -- the tasks: xmake [task] , task.menu } -- done help function main._help() -- done help if option.get("help") then -- print menu option.show_menu(option.taskname()) -- ok return true -- done version elseif option.get("version") then -- print title if menu.title then utils.cprint(menu.title) end -- print copyright if menu.copyright then utils.cprint(menu.copyright) end -- ok return true end end -- the init function for main function main._init() -- init the project directory local projectdir = option.find(xmake._ARGV, "project", "P") or xmake._PROJECT_DIR if projectdir and not path.is_absolute(projectdir) then projectdir = path.absolute(projectdir) elseif projectdir then projectdir = path.translate(projectdir) end xmake._PROJECT_DIR = projectdir assert(projectdir) -- init the xmake.lua file path local projectfile = option.find(xmake._ARGV, "file", "F") or xmake._PROJECT_FILE if projectfile and not path.is_absolute(projectfile) then projectfile = path.absolute(projectfile, projectdir) end xmake._PROJECT_FILE = projectfile assert(projectfile) -- make all parent directories local dirs = {} local dir = path.directory(projectfile) while os.isdir(dir) do table.insert(dirs, 1, dir) local parentdir = path.directory(dir) if parentdir ~= dir then dir = parentdir else break end end -- find the first `xmake.lua` from it's parent directory for _, dir in ipairs(dirs) do local file = path.join(dir, "xmake.lua") if os.isfile(file) then -- switch to the project directory xmake._PROJECT_DIR = dir xmake._PROJECT_FILE = file os.cd(dir) break end end end -- check run command as root function main._check_root() -- TODO not check if xmake._HOST == "windows" then return true end -- check it local ok, code = os.iorun("id -u") if ok and code and code:trim() == '0' then return false, [[Running xmake as root is extremely dangerous and no longer supported. As xmake does not drop privileges on installation you would be giving all build scripts full access to your system.]] end -- not root return true end -- the main function function main.done() -- init main._init() -- init option local ok, errors = option.init(menu) if not ok then utils.error(errors) return -1 end -- check run command as root if not option.get("root") then local ok, errors = main._check_root() if not ok then utils.error(errors) return -1 end end -- start profiling if option.get("profile") then profiler:start() end -- run help? if main._help() then return 0 end -- save command lines to history history.save("cmdlines", option.cmdline()) -- run task ok, errors = task.run(option.taskname() or "build") if not ok then utils.error(errors) return -1 end -- dump deprecated entries deprecated.dump() -- stop profiling if option.get("profile") then profiler:stop() end -- ok return 0 end -- return module: main return main
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- define module: main local main = main or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local option = require("base/option") local profiler = require("base/profiler") local deprecated = require("base/deprecated") local task = require("project/task") local history = require("project/history") -- init the option menu local menu = { -- title title = "XMake v" .. xmake._VERSION .. ", The Make-like Build Utility based on Lua" -- copyright , copyright = "Copyright (C) 2015-2016 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}" -- the tasks: xmake [task] , task.menu } -- done help function main._help() -- done help if option.get("help") then -- print menu option.show_menu(option.taskname()) -- ok return true -- done version elseif option.get("version") then -- print title if menu.title then utils.cprint(menu.title) end -- print copyright if menu.copyright then utils.cprint(menu.copyright) end -- ok return true end end -- the init function for main function main._init() -- init the project directory local projectdir = option.find(xmake._ARGV, "project", "P") or xmake._PROJECT_DIR if projectdir and not path.is_absolute(projectdir) then projectdir = path.absolute(projectdir) elseif projectdir then projectdir = path.translate(projectdir) end xmake._PROJECT_DIR = projectdir assert(projectdir) -- init the xmake.lua file path local projectfile = option.find(xmake._ARGV, "file", "F") or xmake._PROJECT_FILE if projectfile and not path.is_absolute(projectfile) then projectfile = path.absolute(projectfile, projectdir) end xmake._PROJECT_FILE = projectfile assert(projectfile) -- make all parent directories local dirs = {} local dir = path.directory(projectfile) while os.isdir(dir) do table.insert(dirs, 1, dir) local parentdir = path.directory(dir) if parentdir and parentdir ~= dir and parentdir ~= '.' then dir = parentdir else break end end -- find the first `xmake.lua` from it's parent directory for _, dir in ipairs(dirs) do local file = path.join(dir, "xmake.lua") if os.isfile(file) then -- switch to the project directory xmake._PROJECT_DIR = dir xmake._PROJECT_FILE = file os.cd(dir) break end end end -- check run command as root function main._check_root() -- TODO not check if xmake._HOST == "windows" then return true end -- check it local ok, code = os.iorun("id -u") if ok and code and code:trim() == '0' then return false, [[Running xmake as root is extremely dangerous and no longer supported. As xmake does not drop privileges on installation you would be giving all build scripts full access to your system.]] end -- not root return true end -- the main function function main.done() -- init main._init() -- init option local ok, errors = option.init(menu) if not ok then utils.error(errors) return -1 end -- check run command as root if not option.get("root") then local ok, errors = main._check_root() if not ok then utils.error(errors) return -1 end end -- start profiling if option.get("profile") then profiler:start() end -- run help? if main._help() then return 0 end -- save command lines to history history.save("cmdlines", option.cmdline()) -- run task ok, errors = task.run(option.taskname() or "build") if not ok then utils.error(errors) return -1 end -- dump deprecated entries deprecated.dump() -- stop profiling if option.get("profile") then profiler:stop() end -- ok return 0 end -- return module: main return main
fix find xmake.lua path on windows
fix find xmake.lua path on windows
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
15a7a3e9e66d8a167cc3d4c0b84d1a66c79acd0c
lualib/json.lua
lualib/json.lua
local json = {} function json.decode(str) local j = string.gsub(str, '\"([^\"]-)\":','%1=') j = "local t =" .. j .."; return t" t = assert(load(j))() return t; end local encode_tbl, encode_array, encode_object local function table_type(tbl) assert(type(tbl) == "table") for k, v in pairs(tbl) do if type(k) ~= "number" then return "object" end end return "array" end function encode_array(arr) local first = true local sz = "[" for _, v in ipairs(arr) do local encode if (type(v) == "table") then encode = encode_tbl(v) else encode = '"' .. v .. '"' end if first then first = false else sz = sz .. ',' end sz = sz .. encode end return sz .. "]" end function encode_object(tbl) local sz = "" local first = true local encode sz = "{" for k, v in pairs(tbl) do if (type(v) == "table") then encode = encode_tbl(v) else encode = '"' .. k .. '"' .. ":" .. '"' .. v .. '"' end if first then first = false else sz = sz .. "," end sz = sz .. encode end sz = sz .. "}" return sz end function encode_tbl(tbl) local sz = "" local first = true local t; assert(type(tbl) == "table") t = table_type(tbl) if t == "object" then sz = sz .. encode_object(tbl) elseif t == "array" then sz = sz .. encode_array(tbl) end return sz end function json.encode(tbl) local sz = encode_tbl(tbl) return sz end return json
local json = {} function json.decode(str) local j = string.gsub(str, '\"([^\"]-)\":','%1=') j = "local t =" .. j .."; return t" t = assert(load(j))() return t; end local encode_tbl, encode_array, encode_object local function table_type(tbl) assert(type(tbl) == "table") for k, v in pairs(tbl) do if type(k) ~= "number" then return "object" end end return "array" end function encode_array(arr) local first = true local sz = "[" for _, v in ipairs(arr) do local encode if (type(v) == "table") then encode = encode_tbl(v) else encode = '"' .. v .. '"' end if first then first = false else sz = sz .. ',' end sz = sz .. encode end return sz .. "]" end function encode_object(tbl) local sz = "" local first = true local encode sz = "{" for k, v in pairs(tbl) do if (type(v) == "table") then encode = encode_tbl(v) else encode = '"' .. v .. '"' end encode = '"' .. k .. '"' .. ":" .. encode if first then first = false else sz = sz .. "," end sz = sz .. encode end sz = sz .. "}" return sz end function encode_tbl(tbl) local sz = "" local first = true local t; assert(type(tbl) == "table") t = table_type(tbl) if t == "object" then sz = sz .. encode_object(tbl) elseif t == "array" then sz = sz .. encode_array(tbl) end return sz end function json.encode(tbl) local sz = encode_tbl(tbl) return sz end return json
fix json encode bug
fix json encode bug
Lua
mit
findstr/silly
8c4f9f7a994238c97bc436b8fd7376833d1d042a
upcache/vary.lua
upcache/vary.lua
local common = require "upcache.common" local console = common.console local module = {} local varyHeader = "Vary" local function build_key(key, headers, list) local resVal local reqVal for reqName, map in pairs(list) do reqVal = headers[reqName] if reqVal ~= nil then resVal = map[reqVal] if resVal ~= nil then key = reqName .. '->' .. resVal .. ' ' .. key end end end return key end function module.get(key, vars, ngx) local list = common.get(common.variants, key, 'vary') if list == nil then return key end return build_key(key, ngx.req.get_headers(), list) end function module.set(key, vars, ngx) local resHeaders = ngx.header local varies = common.parseHeader(resHeaders[varyHeader]) if varies == nil then return key end local list = common.get(common.variants, key, 'vary') if list == nil then list = {} end local ok = false local reqHeaders = ngx.req.get_headers() local resName, resVal, reqName, reqVal for i, reqName in ipairs(varies) do if reqName == "Accept" then resName = "Content-Type" elseif reqName:sub(1, 7) == "Accept-" then resName = "Content-" .. reqName:sub(8) else resName = reqName end reqVal = reqHeaders[reqName] resVal = resHeaders[resName] if resVal ~= nil and reqVal ~= nil then local map = list[reqName] if map == nil then map = {} list[reqName] = map end map[reqVal] = resVal ok = true end end if ok == false then return key end common.set(common.variants, key, list, 'vary') return build_key(key, reqHeaders, list) end return module;
local common = require "upcache.common" local console = common.console local module = {} local varyHeader = "Vary" local function build_key(key, headers, list) local resVal local reqVal for reqName, map in pairs(list) do reqVal = headers[reqName] or "*" resVal = map[reqVal] if resVal ~= nil then key = reqName .. '->' .. resVal .. ' ' .. key end end return key end function module.get(key, vars, ngx) local list = common.get(common.variants, key, 'vary') if list == nil then return key end return build_key(key, ngx.req.get_headers(), list) end function module.set(key, vars, ngx) local resHeaders = ngx.header local varies = common.parseHeader(resHeaders[varyHeader]) if varies == nil then return key end local list = common.get(common.variants, key, 'vary') or {} local ok = false local reqHeaders = ngx.req.get_headers() local resName, resVal, reqName, reqVal for i, reqName in ipairs(varies) do if reqName == "Accept" then resName = "Content-Type" elseif reqName:sub(1, 7) == "Accept-" then resName = "Content-" .. reqName:sub(8) else resName = reqName end reqVal = reqHeaders[reqName] or "*" resVal = resHeaders[resName] or "*" local map = list[reqName] if map == nil then map = {} list[reqName] = map end map[reqVal] = resVal ok = true end if ok == false then return key end common.set(common.variants, key, list, 'vary') return build_key(key, reqHeaders, list) end return module;
vary: fix cache pollution by empty headers
vary: fix cache pollution by empty headers
Lua
mit
kapouer/cache-protocols,kapouer/upcache
e21782dd79cb50ede2756018ff9a24aa4ac9fc4b
mod_auth_ldap/mod_auth_ldap.lua
mod_auth_ldap/mod_auth_ldap.lua
local new_sasl = require "util.sasl".new; local log = require "util.logger".init("auth_ldap"); local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)"); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local lualdap = require "lualdap"; local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:format(ldap_filter_escape(username)); })(); end local provider = {}; function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.password ~= password then ld:modify(dn, { '=', userPassword = password }); end return true end function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end module:provides("auth", provider);
local new_sasl = require "util.sasl".new; local log = require "util.logger".init("auth_ldap"); local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=%s)"); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local lualdap = require "lualdap"; local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:format(ldap_filter_escape(username)); })(); end local provider = {}; function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end module:provides("auth", provider);
mod_auth_ldap: Fix set_password
mod_auth_ldap: Fix set_password
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
cc1cd5c293bc65e0cd4af5d4cee0f7cc83eefbdf
stable_pairs.lua
stable_pairs.lua
-- https://www.lua.org/manual/5.4/manual.html#pdf-next -- The order in which the indices are enumerated is not specified, even for numeric indices. local table_insert = table.insert local table_sort = table.sort local opairs = _G.pairs _G.pairs = function(t) local st = {} for k, v in opairs(t) do table_insert(st, {k = k, v = v}) end table_sort(st, function(a, b) -- Warning! This function is only guaranteed to work if all keys are strings or numbers. -- "number" < "string", so numbers will be sorted before strings. local type1, type2 = type(key1), type(key2) if type1 ~= type2 then return type1 < type2 else return key1 < key2 end end) local idx = 0 local function n(t) while idx <= #st do idx = idx + 1 local v = st[idx] if not v then return end if t[v.k] then return v.k, v.v end end return end return n, t, nil end --- do print("example 1 ---") local t = {[1001] = 1, [1003] = 3, ["abc"] = "string_abc" } for k, v in pairs(t) do print(k, v) end end do print("example 2 ---") local t = {[1001] = 1, [1003] = 3, ["abc"] = "string_abc" } for k, v in pairs(t) do if t["abc"] then t["abc"] = nil end print(k, v) end end
-- https://www.lua.org/manual/5.4/manual.html#pdf-next -- The order in which the indices are enumerated is not specified, even for numeric indices. local table_insert = table.insert local table_sort = table.sort local opairs = _G.pairs _G.pairs = function(t) local st = {} for k in opairs(t) do table_insert(st, k) end table_sort(st, function(key1, key2) -- Warning! This function is only guaranteed to work if all keys are strings or numbers. -- "number" < "string", so numbers will be sorted before strings. local type1, type2 = type(key1), type(key2) if type1 ~= type2 then return type1 < type2 else return key1 < key2 end end) local idx = 0 local function n(t) while idx <= #st do idx = idx + 1 local key = st[idx] if not key then return end if t[key] then return key, t[key] end end return end return n, t, nil end --- do print("example 1 ---") local t = {[1001] = 1, [1003] = 3, ["abc"] = "string_abc" } for k, v in pairs(t) do print(k, v) end end do print("example 2 ---") local t = {[1001] = 1, [1003] = 3, ["abc"] = "string_abc" } for k, v in pairs(t) do if t["abc"] then t["abc"] = nil end print(k, v) end end
fix bug
fix bug
Lua
mit
kinbei/lua-misc
ef0250259d6e6f21bf43461e3561d2509f230b0b
testserver/item/id_293_throwing_spear.lua
testserver/item/id_293_throwing_spear.lua
-- UPDATE common SET com_script='item.id_293_throwing_spear' WHERE com_itemid IN (293); require("base.lookat") module("item.id_293_throwing_spear", package.seeall) function LookAtItem(User, Item) local customText = base.lookat.GetItemDescription(User,Item,2,false,false); if Item.data > 2^30 then world:itemInform( User, Item, customText ); else world:itemInform( User, Item, User:getPlayerLanguage()==0 and world:getItemName(Item.id,0) or world:getItemName(Item.id,1) ); end end
-- UPDATE common SET com_script='item.id_293_throwing_spear' WHERE com_itemid IN (293); require("base.lookat") module("item.id_293_throwing_spear", package.seeall) function LookAtItem(User, Item) local customText = base.lookat.GetItemDescription(User,Item,base.lookat.WOOD,false,false); if Item:getData("spearData") > 2^30 then world:itemInform( User, Item, customText ); else world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.WOOD)); end end
fixed lookat and exchanged old data
fixed lookat and exchanged old data
Lua
agpl-3.0
KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
bac4b779b07a15be35b3dd3c7192a993e684c362
TripletCriterion.lua
TripletCriterion.lua
local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion') function TripletCriterion:__init(samples, blocks, norm, margin) parent.__init(self) self.norm = norm or 2 self.alpha = margin or 0.2 self.samples = samples or 1 -- use all anchor-positive pairs for (>1) self.blocks = blocks or 0 if self.samples > 1 then assert(self.blocks ~= 0) end self.dist = torch.Tensor() self.embeddings = torch.Tensor() self.loss = torch.Tensor() end function TripletCriterion:updateOutput(input, target) assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)') assert(input:size(1) >= self.samples*self.blocks) if input:type() == 'torch.CudaTensor' then -- kernel call input.nn.TripletCriterion_updateOutput(self, input, target) else local nb_batch = input:size(1) local length = input:size(2) local nb_blocks = math.floor(nb_batch/self.samples) -- calculate distance matrix self.dist:resize(nb_batch, nb_batch) for i = 1, nb_batch do for j = i, nb_batch do if j == i then self.dist[i][j] = 0 else self.dist[i][j] = torch.dist(input[i], input[j], self.norm) self.dist[j][i] = self.dist[i][j] end end end -- find pos/neg embeddings indices -- (i) hard anchor-positive pair if self.samples == 1 then self.embeddings:resize(nb_batch, 3) for i = 1, nb_batch do local ipos = i local vpos = 0 local ineg = i local vneg = math.huge for j = 1, nb_batch do if (target[j] == target[i]) and (vpos < self.dist[i][j]) then ipos = j vpos = self.dist[i][j] end end for j = 1, nb_batch do if (target[j] ~= target[i]) and (vpos < self.dist[i][j]) and (vneg > self.dist[i][j]) then ineg = j vneg = self.dist[i][j] end end self.embeddings[i][1] = i self.embeddings[i][2] = ipos self.embeddings[i][3] = ineg end -- (ii) all anchor-positive pairs elseif self.samples > 1 then -- calculate nb of all pairs self.embeddings:resize(nb_batch*(self.samples-1), 3):zero() -- repeat batch (samples-1) times for i = 0, self.samples-2 do for j = 0, nb_blocks-1 do for k = 0, self.samples-1 do -- pick an element in distance matrix local row = j*self.samples + k + 1 local col = j*self.samples + i + 1 col = col < row and col or col + 1 -- find positive embedding local ipos = col local vpos = self.dist[row][col] -- find negative embedding local ineg = row local vneg = math.huge for l = self.samples*self.blocks+1, nb_batch do if target[l] ~= target[row] and self.dist[row][l] > vpos and self.dist[row][l] < vneg then ineg = l vneg = self.dist[row][l] end end self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg end end end end -- compute loss self.loss:resize(self.embeddings:size(1)) for i = 1, self.embeddings:size(1) do -- do not penalize if negative is not found if self.embeddings[i][1] == self.embeddings[i][3] then self.loss[i] = 0 else local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2) local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2) self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an) end end end if self.samples > 1 then self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1)) else self.output = self.loss:sum()/input:size(1) end return self.output end function TripletCriterion:updateGradInput(input, target) self:updateOutput(input, target) if input:type() == 'torch.CudaTensor' then input.nn.TripletCriterion_updateGradInput(self, input, target) else local nb_pairs = self.loss:size(1) local length = input:size(2) self.gradInput:resize(nb_pairs, length) for i = 1, nb_pairs do if self.loss[i] > 0 then self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs else self.gradInput[i] = 0 end end end return self.gradInput end
local TripletCriterion, parent = torch.class('nn.TripletCriterion', 'nn.Criterion') function TripletCriterion:__init(samples, blocks, norm, margin) parent.__init(self) self.norm = norm or 2 self.alpha = margin or 0.2 self.samples = samples or 1 -- use all anchor-positive pairs for (>1) self.blocks = blocks or 0 if self.samples > 1 then assert(self.blocks ~= 0) end self.dist = torch.Tensor() self.embeddings = torch.Tensor() self.loss = torch.Tensor() end function TripletCriterion:updateOutput(input, target) assert(input:dim() == 2, 'input should have 2 dimensions of (batch x embedding)') assert(input:size(1) >= self.samples*self.blocks) if input:type() == 'torch.CudaTensor' then -- kernel call input.nn.TripletCriterion_updateOutput(self, input, target) else local nb_batch = input:size(1) local length = input:size(2) local nb_blocks = math.floor(nb_batch/self.samples) -- calculate distance matrix self.dist:resize(nb_batch, nb_batch) for i = 1, nb_batch do for j = i, nb_batch do if j == i then self.dist[i][j] = 0 else self.dist[i][j] = torch.dist(input[i], input[j], self.norm) self.dist[j][i] = self.dist[i][j] end end end -- find pos/neg embeddings indices -- (i) hard anchor-positive pair if self.samples == 1 then self.embeddings:resize(nb_batch, 3) for i = 1, nb_batch do local ipos = i local vpos = 0 local ineg = i local vneg = math.huge for j = 1, nb_batch do if (target[j] == target[i]) and (vpos < self.dist[i][j]) then ipos = j vpos = self.dist[i][j] end end for j = 1, nb_batch do if (target[j] ~= target[i]) and (vpos < self.dist[i][j]) and (vneg > self.dist[i][j]) then ineg = j vneg = self.dist[i][j] end end self.embeddings[i][1] = i self.embeddings[i][2] = ipos self.embeddings[i][3] = ineg end -- (ii) all anchor-positive pairs elseif self.samples > 1 then -- calculate nb of all pairs self.embeddings:resize(nb_batch*(self.samples-1), 3):zero() -- repeat batch (samples-1) times for i = 0, self.samples-2 do for j = 0, nb_blocks-1 do for k = 0, self.samples-1 do -- pick an element in distance matrix local row = j*self.samples + k + 1 local col = j*self.samples + i + 1 col = col < row and col or col + 1 -- find positive embedding local ipos = col local vpos = self.dist[row][col] -- find negative embedding local ineg = row local vneg = math.huge for l = self.samples*self.blocks+1, nb_batch do if target[l] ~= target[row] and self.dist[row][l] > vpos and self.dist[row][l] < vneg then ineg = l vneg = self.dist[row][l] end end self.embeddings[i*nb_batch + j*self.samples + k + 1][1] = row self.embeddings[i*nb_batch + j*self.samples + k + 1][2] = ipos self.embeddings[i*nb_batch + j*self.samples + k + 1][3] = ineg end end end end -- compute loss self.loss:resize(self.embeddings:size(1)) for i = 1, self.embeddings:size(1) do -- do not penalize if negative is not found if self.embeddings[i][1] == self.embeddings[i][3] then self.loss[i] = 0 else local d_ap = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][2]], 2) local d_an = torch.dist(input[self.embeddings[i][1]], input[self.embeddings[i][3]], 2) self.loss[i] = math.max(0, d_ap*d_ap + self.alpha - d_an*d_an) end end end if self.samples > 1 then self.output = self.loss:sum()/(self.blocks*self.samples*(self.samples-1)) else self.output = self.loss:sum()/input:size(1) end return self.output end function TripletCriterion:updateGradInput(input, target) self:updateOutput(input, target) if input:type() == 'torch.CudaTensor' then input.nn.TripletCriterion_updateGradInput(self, input, target) else local nb_pairs = self.loss:size(1) local length = input:size(2) self.gradInput:resize(nb_pairs, length) for i = 1, nb_pairs do if self.loss[i] > 0 then self.gradInput[i] = (input[self.embeddings[i][3]] - input[self.embeddings[i][2]])*2/nb_pairs else self.gradInput[i] = 0 end end end local nb_backwards = math.max(1, self.samples-1) local nb_batch = input:size(1) self.gradInput = gradInput:view(nb_backwards, nb_batch, length):sum(1):squeeze() return self.gradInput end
Fix gradInput dimensionality and computation
Fix gradInput dimensionality and computation
Lua
mit
jhjin/triplet-criterion
66ca3a742b1b4da5d6435efa7b31e198201fc046
build/Tests.lua
build/Tests.lua
-- Tests/examples helpers function SetupExampleProject() kind "ConsoleApp" language "C#" debugdir "." files { "**.cs", "./*.lua" } links { "CppSharp.AST", "CppSharp.Generator" } SetupManagedProject() SetupParser() end function SetupTestProject(name, file, lib) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name, file, lib) SetupTestProjectsCLI(name, file, lib) end function SetupTestCSharp(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name) end function SetupTestCLI(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCLI(name) end function SetupManagedTestProject() kind "SharedLib" language "C#" flags { "Unsafe" } SetupManagedProject() end function SetupTestGeneratorProject(name) project(name .. ".Gen") SetupManagedTestProject() kind "ConsoleApp" files { name .. ".cs" } dependson { name .. ".Native" } links { "CppSharp.AST", "CppSharp.Generator", } SetupParser() end function SetupTestGeneratorBuildEvent(name) local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe") if string.starts(action, "vs") then prebuildcommands { exePath } else prebuildcommands { "mono " .. exePath } end end function SetupTestNativeProject(name) project(name .. ".Native") SetupNativeProject() kind "SharedLib" language "C++" flags { common_flags } files { "**.h", "**.cpp" } end function LinkNUnit() libdirs { depsdir .. "/NUnit", depsdir .. "/NSubstitute" } links { "NUnit.Framework", "NSubstitute" } end function SetupTestProjectsCSharp(name, file, lib) project(name .. ".CSharp") SetupManagedTestProject() dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cs"), } links { "CppSharp.Runtime" } project(name .. ".Tests.CSharp") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CSharp" } dependson { name .. ".Native" } LinkNUnit() links { "CppSharp.Runtime" } end function SetupTestProjectsCLI(name, file, lib) project(name .. ".CLI") SetupNativeProject() kind "SharedLib" language "C++" flags { "Managed" } dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cpp"), path.join(gendir, name, name .. ".h"), } includedirs { path.join(testsdir, name), incdir } links { name .. ".Native" } project(name .. ".Tests.CLI") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CLI" } dependson { name .. ".Native" } LinkNUnit() end function IncludeExamples() print("Searching for examples...") IncludeDir(examplesdir) end function IncludeTests() print("Searching for tests...") IncludeDir(testsdir) end
-- Tests/examples helpers function SetupExampleProject() kind "ConsoleApp" language "C#" debugdir "." files { "**.cs", "./*.lua" } links { "CppSharp.AST", "CppSharp.Generator" } SetupManagedProject() SetupParser() end function SetupTestProject(name, file, lib) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name, file, lib) SetupTestProjectsCLI(name, file, lib) end function SetupTestCSharp(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name) end function SetupTestCLI(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCLI(name) end function SetupManagedTestProject() kind "SharedLib" language "C#" flags { "Unsafe" } SetupManagedProject() end function SetupTestGeneratorProject(name) project(name .. ".Gen") SetupManagedTestProject() kind "ConsoleApp" files { name .. ".cs" } dependson { name .. ".Native" } links { "CppSharp.AST", "CppSharp.Generator", } SetupParser() end function SetupTestGeneratorBuildEvent(name) if string.starts(action, "vs") then local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe") prebuildcommands { exePath } else local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe") prebuildcommands { "mono " .. exePath } end end function SetupTestNativeProject(name) project(name .. ".Native") SetupNativeProject() kind "SharedLib" language "C++" flags { common_flags } files { "**.h", "**.cpp" } end function LinkNUnit() libdirs { depsdir .. "/NUnit", depsdir .. "/NSubstitute" } links { "NUnit.Framework", "NSubstitute" } end function SetupTestProjectsCSharp(name, file, lib) project(name .. ".CSharp") SetupManagedTestProject() dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cs"), } links { "CppSharp.Runtime" } project(name .. ".Tests.CSharp") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CSharp" } dependson { name .. ".Native" } LinkNUnit() links { "CppSharp.Runtime" } end function SetupTestProjectsCLI(name, file, lib) project(name .. ".CLI") SetupNativeProject() kind "SharedLib" language "C++" flags { "Managed" } dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cpp"), path.join(gendir, name, name .. ".h"), } includedirs { path.join(testsdir, name), incdir } links { name .. ".Native" } project(name .. ".Tests.CLI") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CLI" } dependson { name .. ".Native" } LinkNUnit() end function IncludeExamples() print("Searching for examples...") IncludeDir(examplesdir) end function IncludeTests() print("Searching for tests...") IncludeDir(testsdir) end
Fixed the VS build.
Fixed the VS build. The version of Premake that's on the repository does not seem to like the token patterns.
Lua
mit
mono/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,mono/CppSharp,Samana/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,u255436/CppSharp,imazen/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,Samana/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,xistoso/CppSharp,inordertotest/CppSharp,mono/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,ddobrev/CppSharp,imazen/CppSharp,u255436/CppSharp,ddobrev/CppSharp,Samana/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp,mono/CppSharp,u255436/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,xistoso/CppSharp,xistoso/CppSharp,KonajuGames/CppSharp,u255436/CppSharp,txdv/CppSharp,mono/CppSharp,mono/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,txdv/CppSharp,zillemarco/CppSharp,mydogisbox/CppSharp
5b940cecaf10dec3ac2f0c8973fb1469cbfe212c
frontend/ui/widget/inputtext.lua
frontend/ui/widget/inputtext.lua
local InputContainer = require("ui/widget/container/inputcontainer") local ScrollTextWidget = require("ui/widget/scrolltextwidget") local TextBoxWidget = require("ui/widget/textboxwidget") local FrameContainer = require("ui/widget/container/framecontainer") local VirtualKeyboard = require("ui/widget/virtualkeyboard") local GestureRange = require("ui/gesturerange") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Device = require("ui/device") local Screen = require("ui/screen") local Font = require("ui/font") local DEBUG = require("dbg") local util = require("ffi/util") local InputText = InputContainer:new{ text = "", hint = "demo hint", charlist = {}, -- table to store input string charpos = 1, input_type = nil, text_type = nil, width = nil, height = nil, face = Font:getFace("cfont", 22), padding = 5, margin = 5, bordersize = 2, parent = nil, -- parent dialog that will be set dirty scroll = false, focused = true, } function InputText:init() self:StringToCharlist(self.text) self:initTextBox() self:initKeyboard() if Device:isTouchDevice() then self.ges_events = { TapTextBox = { GestureRange:new{ ges = "tap", range = self.dimen } } } end end function InputText:initTextBox() local bgcolor, fgcolor = 0.0, self.text == "" and 0.5 or 1.0 local text_widget = nil local show_text = self.text if self.text_type == "password" and show_text ~= "" then show_text = self.text:gsub("(.-).", function() return "*" end) show_text = show_text:gsub("(.)$", function() return self.text:sub(-1) end) elseif show_text == "" then show_text = self.hint end if self.scroll then text_widget = ScrollTextWidget:new{ text = show_text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } else text_widget = TextBoxWidget:new{ text = show_text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } end self[1] = FrameContainer:new{ bordersize = self.bordersize, padding = self.padding, margin = self.margin, color = self.focused and 15 or 8, text_widget, } self.dimen = self[1]:getSize() end function InputText:initKeyboard() local keyboard_layout = 2 if self.input_type == "number" then keyboard_layout = 3 end self.keyboard = VirtualKeyboard:new{ layout = keyboard_layout, inputbox = self, width = Screen:getWidth(), height = math.max(Screen:getWidth(), Screen:getHeight())*0.33, } end function InputText:onTapTextBox() if self.parent.onSwitchFocus then self.parent:onSwitchFocus(self) end end function InputText:unfocus() self.focused = false self[1].color = 8 end function InputText:focus() self.focused = true self[1].color = 15 end function InputText:onShowKeyboard() UIManager:show(self.keyboard) end function InputText:onCloseKeyboard() UIManager:close(self.keyboard) end function InputText:getKeyboardDimen() return self.keyboard.dimen end function InputText:addChar(char) if self.enter_callback and char == '\n' then UIManager:scheduleIn(0.3, function() self.enter_callback() end) return end table.insert(self.charlist, self.charpos, char) self.charpos = self.charpos + 1 self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:delChar() if self.charpos == 1 then return end self.charpos = self.charpos - 1 table.remove(self.charlist, self.charpos) self.text = self:CharlistToString() self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:clear() self.text = "" self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:getText() return self.text end function InputText:setText(text) self:StringToCharlist(text) self:initTextBox() UIManager:setDirty(self.parent, "partial") end function InputText:StringToCharlist(text) if text == nil then return end -- clear self.charlist = {} self.charpos = 1 local prevcharcode, charcode = 0 for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do charcode = util.utf8charcode(uchar) if prevcharcode then -- utf8 self.charlist[#self.charlist+1] = uchar end prevcharcode = charcode end self.text = self:CharlistToString() self.charpos = #self.charlist+1 end function InputText:CharlistToString() local s, i = "" for i=1, #self.charlist do s = s .. self.charlist[i] end return s end return InputText
local InputContainer = require("ui/widget/container/inputcontainer") local ScrollTextWidget = require("ui/widget/scrolltextwidget") local TextBoxWidget = require("ui/widget/textboxwidget") local FrameContainer = require("ui/widget/container/framecontainer") local VirtualKeyboard = require("ui/widget/virtualkeyboard") local GestureRange = require("ui/gesturerange") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Device = require("ui/device") local Screen = require("ui/screen") local Font = require("ui/font") local DEBUG = require("dbg") local util = require("ffi/util") local InputText = InputContainer:new{ text = "", hint = "demo hint", charlist = {}, -- table to store input string charpos = 1, input_type = nil, text_type = nil, width = nil, height = nil, face = Font:getFace("cfont", 22), padding = 5, margin = 5, bordersize = 2, parent = nil, -- parent dialog that will be set dirty scroll = false, focused = true, } function InputText:init() self:initTextBox(self.text) self:initKeyboard() if Device:isTouchDevice() then self.ges_events = { TapTextBox = { GestureRange:new{ ges = "tap", range = self.dimen } } } end end function InputText:initTextBox(text) self.text = text self:initCharlist(text) local bgcolor, fgcolor = 0.0, self.text == "" and 0.5 or 1.0 local text_widget = nil local show_text = self.text if self.text_type == "password" and show_text ~= "" then show_text = self.text:gsub("(.-).", function() return "*" end) show_text = show_text:gsub("(.)$", function() return self.text:sub(-1) end) elseif show_text == "" then show_text = self.hint end if self.scroll then text_widget = ScrollTextWidget:new{ text = show_text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } else text_widget = TextBoxWidget:new{ text = show_text, face = self.face, bgcolor = bgcolor, fgcolor = fgcolor, width = self.width, height = self.height, } end self[1] = FrameContainer:new{ bordersize = self.bordersize, padding = self.padding, margin = self.margin, color = self.focused and 15 or 8, text_widget, } self.dimen = self[1]:getSize() end function InputText:initCharlist(text) if text == nil then return end -- clear self.charlist = {} self.charpos = 1 local prevcharcode, charcode = 0 for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do charcode = util.utf8charcode(uchar) if prevcharcode then -- utf8 self.charlist[#self.charlist+1] = uchar end prevcharcode = charcode end self.charpos = #self.charlist+1 end function InputText:initKeyboard() local keyboard_layout = 2 if self.input_type == "number" then keyboard_layout = 3 end self.keyboard = VirtualKeyboard:new{ layout = keyboard_layout, inputbox = self, width = Screen:getWidth(), height = math.max(Screen:getWidth(), Screen:getHeight())*0.33, } end function InputText:onTapTextBox() if self.parent.onSwitchFocus then self.parent:onSwitchFocus(self) end end function InputText:unfocus() self.focused = false self[1].color = 8 end function InputText:focus() self.focused = true self[1].color = 15 end function InputText:onShowKeyboard() UIManager:show(self.keyboard) end function InputText:onCloseKeyboard() UIManager:close(self.keyboard) end function InputText:getKeyboardDimen() return self.keyboard.dimen end function InputText:addChar(char) if self.enter_callback and char == '\n' then UIManager:scheduleIn(0.3, function() self.enter_callback() end) return end table.insert(self.charlist, self.charpos, char) self.charpos = self.charpos + 1 self:initTextBox(table.concat(self.charlist)) UIManager:setDirty(self.parent, "partial") end function InputText:delChar() if self.charpos == 1 then return end self.charpos = self.charpos - 1 table.remove(self.charlist, self.charpos) self:initTextBox(table.concat(self.charlist)) UIManager:setDirty(self.parent, "partial") end function InputText:clear() self:initTextBox("") UIManager:setDirty(self.parent, "partial") end function InputText:getText() return self.text end function InputText:setText(text) self:initTextBox(text) UIManager:setDirty(self.parent, "partial") end return InputText
refactoring: hide the charlist implementation of InputText This patch also fix #875.
refactoring: hide the charlist implementation of InputText This patch also fix #875.
Lua
agpl-3.0
ashhher3/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,apletnev/koreader,NickSavage/koreader,Hzj-jie/koreader,noname007/koreader,chrox/koreader,koreader/koreader,NiLuJe/koreader,NiLuJe/koreader,Frenzie/koreader,frankyifei/koreader,mihailim/koreader,ashang/koreader,lgeek/koreader,robert00s/koreader,pazos/koreader,mwoz123/koreader,poire-z/koreader,chihyang/koreader,houqp/koreader,Markismus/koreader
d3f957729985a9b127279e81ba81af8b5c34fc46
lua/LUA/ak/strasse/KreuzungJsonCollector.lua
lua/LUA/ak/strasse/KreuzungJsonCollector.lua
print("Lade ak.strasse.KreuzungJsonCollector") KreuzungJsonCollector = {} local enabled = true local initialized = false KreuzungJsonCollector.name = "ak.data.KreuzungJsonCollector" local AkKreuzung = require("ak.strasse.AkKreuzung") local function collect(alleKreuzungen) local intersections = {} local intersectionLanes = {} local intersectionSwitching = {} local intersectionTrafficLights = {} local alleRichtungen = {} local richtungsSchaltungen = {} local intersectionIdCounter = 0 for _, kreuzung in ipairs(alleKreuzungen) do intersectionIdCounter = intersectionIdCounter + 1 local intersection = { id = intersectionIdCounter, name = kreuzung.name, currentSwitching = kreuzung.aktuelleSchaltung and kreuzung.aktuelleSchaltung.name or nil, manualSwitching = kreuzung.manuelleSchaltung and kreuzung.manuelleSchaltung.name or nil, nextSwitching = kreuzung.nextSchaltung and kreuzung.nextSchaltung.name or nil, ready = kreuzung.bereit, timeForGreen = kreuzung.gruenZeit, staticCams = kreuzung.staticCams } table.insert(intersections, intersection) for schaltung in pairs(kreuzung:getSchaltungen()) do local switching = { id = kreuzung.name .. "-" .. schaltung.name, intersectionId = kreuzung.name, name = schaltung.name, prio = schaltung.prio } table.insert(intersectionSwitching, switching) for richtung in pairs(schaltung:getAlleRichtungen()) do alleRichtungen[richtung] = intersection.id richtungsSchaltungen[richtung] = richtungsSchaltungen[richtung] or {} table.insert(richtungsSchaltungen[richtung], schaltung.name) end end end for lane, intersectionId in pairs(alleRichtungen) do local type if (lane.schaltungsTyp == AkRichtung.SchaltungsTyp.FUSSGAENGER) then type = "PEDESTRIAN" elseif (lane.trafficType == "TRAM") then type = "TRAM" else type = "NORMAL" end local phase = "NONE" if lane.phase == AkPhase.GELB then phase = "YELLOW" elseif lane.phase == AkPhase.ROT then phase = "RED" elseif lane.phase == AkPhase.ROTGELB then phase = "RED_YELLOW" elseif lane.phase == AkPhase.GRUEN then phase = "GREEN" elseif lane.phase == AkPhase.FG then phase = "PEDESTRIAN" end local countType = "CONTACTS" if lane.verwendeZaehlAmpeln then countType = "SIGNALS" elseif lane.verwendeZaehlStrassen then countType = "TRACKS" end local o = { id = intersectionId .. "-" .. lane.name, intersectionId = intersectionId, name = lane.name, phase = phase, vehicleMultiplier = lane.fahrzeugMultiplikator, eepSaveId = lane.eepSaveId, type = type, countType = countType, waitingTrains = {}, waitingForGreenCyclesCount = lane.warteZeit, directions = lane.richtungen, switchings = richtungsSchaltungen[lane] or {} } for i = 1, lane.fahrzeuge or 1, 1 do o.waitingTrains[i] = "?" end table.insert(intersectionLanes, o) for _, ampel in pairs(lane.ampeln) do local trafficLight = { id = ampel.signalId, type = type, signalId = ampel.signalId, modelId = ampel.ampelTyp.name, currentPhase = ampel.phase, laneId = lane.name, intersectionId = intersectionId, lightStructures = {}, axisStructures = {} } for axisStructure in pairs(ampel.achsenImmos) do local as = { structureName = axisStructure.immoName, axis = axisStructure.achse, positionDefault = axisStructure.grundStellung, positionRed = axisStructure.stellungRot, positionGreen = axisStructure.stellungGruen, positionYellow = axisStructure.stellungGelb, positionPedestrants = axisStructure.stellungFG, positionRedYellow = axisStructure.stellungRotGelb } table.insert(trafficLight.axisStructures, as) end local lsId = 0 for lightStructure in pairs(ampel.lichtImmos) do local ls = { structureRed = lightStructure.rotImmo, structureGreen = lightStructure.gruenImmo, structureYellow = lightStructure.gelbImmo or lightStructure.rotImmo, structureRequest = lightStructure.anforderungImmo } trafficLight.lightStructures[tostring(lsId)] = ls lsId = lsId + 1 end table.insert(intersectionTrafficLights, trafficLight) end end local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)") return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end table.sort( intersectionLanes, function(o1, o2) local a = o1.name local b = o2.name return tostring(a):gsub("%.?%d+", padnum) .. ("%3d"):format(#b) < tostring(b):gsub("%.?%d+", padnum) .. ("%3d"):format(#a) end ) return { ["intersections"] = intersections, ["intersection-lanes"] = intersectionLanes, ["intersection-switchings"] = intersectionSwitching, ["intersection-traffic-lights"] = intersectionTrafficLights } end function KreuzungJsonCollector.initialize() if not enabled or initialized then return end initialized = true end function KreuzungJsonCollector.collectData() if not enabled then return end if not initialized then KreuzungJsonCollector.initialize() end return collect(AkKreuzung.alleKreuzungen) end return KreuzungJsonCollector
print("Lade ak.strasse.KreuzungJsonCollector ...") KreuzungJsonCollector = {} local enabled = true local initialized = false KreuzungJsonCollector.name = "ak.data.KreuzungJsonCollector" local AkKreuzung = require("ak.strasse.AkKreuzung") local AkRichtung = require("ak.strasse.AkRichtung") local AkPhase = require("ak.strasse.AkPhase") local function collect(alleKreuzungen) local intersections = {} local intersectionLanes = {} local intersectionSwitching = {} local intersectionTrafficLights = {} local alleRichtungen = {} local richtungsSchaltungen = {} local intersectionIdCounter = 0 for _, kreuzung in pairs(alleKreuzungen) do intersectionIdCounter = intersectionIdCounter + 1 local intersection = { id = intersectionIdCounter, name = kreuzung.name, currentSwitching = kreuzung.aktuelleSchaltung and kreuzung.aktuelleSchaltung.name or nil, manualSwitching = kreuzung.manuelleSchaltung and kreuzung.manuelleSchaltung.name or nil, nextSwitching = kreuzung.nextSchaltung and kreuzung.nextSchaltung.name or nil, ready = kreuzung.bereit, timeForGreen = kreuzung.gruenZeit, staticCams = kreuzung.staticCams } table.insert(intersections, intersection) for schaltung in pairs(kreuzung:getSchaltungen()) do local switching = { id = kreuzung.name .. "-" .. schaltung.name, intersectionId = kreuzung.name, name = schaltung.name, prio = schaltung.prio } table.insert(intersectionSwitching, switching) for richtung in pairs(schaltung:getAlleRichtungen()) do alleRichtungen[richtung] = intersection.id richtungsSchaltungen[richtung] = richtungsSchaltungen[richtung] or {} table.insert(richtungsSchaltungen[richtung], schaltung.name) end end end for lane, intersectionId in pairs(alleRichtungen) do local type if (lane.schaltungsTyp == AkRichtung.SchaltungsTyp.FUSSGAENGER) then type = "PEDESTRIAN" elseif (lane.trafficType == "TRAM") then type = "TRAM" else type = "NORMAL" end local phase = "NONE" if lane.phase == AkPhase.GELB then phase = "YELLOW" elseif lane.phase == AkPhase.ROT then phase = "RED" elseif lane.phase == AkPhase.ROTGELB then phase = "RED_YELLOW" elseif lane.phase == AkPhase.GRUEN then phase = "GREEN" elseif lane.phase == AkPhase.FG then phase = "PEDESTRIAN" end local countType = "CONTACTS" if lane.verwendeZaehlAmpeln then countType = "SIGNALS" elseif lane.verwendeZaehlStrassen then countType = "TRACKS" end local o = { id = intersectionId .. "-" .. lane.name, intersectionId = intersectionId, name = lane.name, phase = phase, vehicleMultiplier = lane.fahrzeugMultiplikator, eepSaveId = lane.eepSaveId, type = type, countType = countType, waitingTrains = {}, waitingForGreenCyclesCount = lane.warteZeit, directions = lane.richtungen, switchings = richtungsSchaltungen[lane] or {} } for i = 1, lane.fahrzeuge or 1, 1 do o.waitingTrains[i] = "?" end table.insert(intersectionLanes, o) for _, ampel in pairs(lane.ampeln) do local trafficLight = { id = ampel.signalId, type = type, signalId = ampel.signalId, modelId = ampel.ampelTyp.name, currentPhase = ampel.phase, laneId = lane.name, intersectionId = intersectionId, lightStructures = {}, axisStructures = {} } for axisStructure in pairs(ampel.achsenImmos) do local as = { structureName = axisStructure.immoName, axis = axisStructure.achse, positionDefault = axisStructure.grundStellung, positionRed = axisStructure.stellungRot, positionGreen = axisStructure.stellungGruen, positionYellow = axisStructure.stellungGelb, positionPedestrants = axisStructure.stellungFG, positionRedYellow = axisStructure.stellungRotGelb } table.insert(trafficLight.axisStructures, as) end local lsId = 0 for lightStructure in pairs(ampel.lichtImmos) do local ls = { structureRed = lightStructure.rotImmo, structureGreen = lightStructure.gruenImmo, structureYellow = lightStructure.gelbImmo or lightStructure.rotImmo, structureRequest = lightStructure.anforderungImmo } trafficLight.lightStructures[tostring(lsId)] = ls lsId = lsId + 1 end table.insert(intersectionTrafficLights, trafficLight) end end local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)") return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end table.sort( intersectionLanes, function(o1, o2) local a = o1.name local b = o2.name return tostring(a):gsub("%.?%d+", padnum) .. ("%3d"):format(#b) < tostring(b):gsub("%.?%d+", padnum) .. ("%3d"):format(#a) end ) return { ["intersections"] = intersections, ["intersection-lanes"] = intersectionLanes, ["intersection-switchings"] = intersectionSwitching, ["intersection-traffic-lights"] = intersectionTrafficLights } end function KreuzungJsonCollector.initialize() if not enabled or initialized then return end initialized = true end function KreuzungJsonCollector.collectData() if not enabled then return end if not initialized then KreuzungJsonCollector.initialize() end return collect(AkKreuzung.alleKreuzungen) end return KreuzungJsonCollector
fix Kreuzungsausgabe nach Json
fix Kreuzungsausgabe nach Json
Lua
mit
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
535181b25ccbc492f741b9eeb111a02dfd038b41
configs/layering.lua
configs/layering.lua
-- This global variable has the current base offset for the input channels. -- We want to map 16 input channels (from MIDI) to 512 output channels (ArtNet), -- so we have 32 possible offsets (32 * 16 = 512) current_layer = 0 -- Set the current_layer based on the control input channel function control(value) current_layer = math.floor(value * 31.99); end -- Handler functions for the input channels -- Calculate the channel offset and just output the value the input channel provides function in0(value) output("out"..((current_layer * 16)), value) print("Output on out"..((current_layer * 16))) end function in1(value) output("out"..((current_layer * 16)) + 1, value) end function in2(value) output("out"..((current_layer * 16)) + 2, value) end function in3(value) output("out"..((current_layer * 16)) + 3, value) end function in4(value) output("out"..((current_layer * 16)) + 4, value) end function in5(value) output("out"..((current_layer * 16)) + 5, value) end function in6(value) output("out"..((current_layer * 16)) + 6, value) end function in7(value) output("out"..((current_layer * 16)) + 7, value) end function in8(value) output("out"..((current_layer * 16)) + 8, value) end function in9(value) output("out"..((current_layer * 16)) + 9, value) end function in10(value) output("out"..((current_layer * 16)) + 10, value) end function in11(value) output("out"..((current_layer * 16)) + 11, value) end function in12(value) output("out"..((current_layer * 16)) + 12, value) end function in13(value) output("out"..((current_layer * 16)) + 13, value) end function in14(value) output("out"..((current_layer * 16)) + 14, value) end function in15(value) output("out"..((current_layer * 16)) + 15, value) end
-- This global variable has the current base offset for the input channels. -- We want to map 16 input channels (from MIDI) to 512 output channels (ArtNet), -- so we have 32 possible offsets (32 * 16 = 512) current_layer = 0 -- Set the current_layer based on the control input channel function control(value) current_layer = math.floor(value * 31.99); end -- Handler functions for the input channels -- Calculate the channel offset and just output the value the input channel provides function in0(value) output("out"..((current_layer * 16)), value) print("Output on out"..(current_layer * 16)) end function in1(value) output("out"..((current_layer * 16) + 1), value) end function in2(value) output("out"..((current_layer * 16) + 2), value) end function in3(value) output("out"..((current_layer * 16) + 3), value) end function in4(value) output("out"..((current_layer * 16) + 4), value) end function in5(value) output("out"..((current_layer * 16) + 5), value) end function in6(value) output("out"..((current_layer * 16) + 6), value) end function in7(value) output("out"..((current_layer * 16) + 7), value) end function in8(value) output("out"..((current_layer * 16) + 8), value) end function in9(value) output("out"..((current_layer * 16) + 9), value) end function in10(value) output("out"..((current_layer * 16) + 10), value) end function in11(value) output("out"..((current_layer * 16) + 11), value) end function in12(value) output("out"..((current_layer * 16) + 12), value) end function in13(value) output("out"..((current_layer * 16) + 13), value) end function in14(value) output("out"..((current_layer * 16) + 14), value) end function in15(value) output("out"..((current_layer * 16) + 15), value) end
Fix lua order of operations
Fix lua order of operations
Lua
bsd-2-clause
cbdevnet/midimonster,cbdevnet/midimonster,cbdevnet/midimonster,cbdevnet/midimonster
1516b367106aa6a8f351b6eebcc4f75e8051187a
conf/health.lua
conf/health.lua
local cjson = require "cjson" local inspect = require "inspect" local response = { status = "red", } if ngx.shared.apis:get("last_fetched_at") and ngx.shared.api_users:get("last_fetched_at") then response["status"] = "yellow" end local http = require "resty.http" local httpc = http.new() local res, err = httpc:request_uri(config["elasticsearch"]["hosts"][1] .. "/_cluster/health") if not err and res.body then local elasticsearch_health = cjson.decode(res.body) if elasticsearch_health["status"] == "green" then response["status"] = "green" end end ngx.say(cjson.encode(response))
local cjson = require "cjson" local inspect = require "inspect" local response = { status = "red", details = { apis_config = "red", api_users = "red", analytics_db = "red", }, } if ngx.shared.apis:get("last_fetched_at") then response["details"]["apis_config"] = "green" end if ngx.shared.api_users:get("last_fetched_at") then response["details"]["api_users"] = "green" end local http = require "resty.http" local httpc = http.new() local res, err = httpc:request_uri(config["elasticsearch"]["hosts"][1] .. "/_cluster/health") if not err and res.body then local elasticsearch_health = cjson.decode(res.body) response["details"]["analytics_db"] = elasticsearch_health["status"] end if response["details"]["apis_config"] == "green" and response["details"]["api_users"] == "green" and response["details"]["analytics_db"] == "green" then response["status"] = "green" elseif response["details"]["apis_config"] == "green" and response["details"]["api_users"] == "green" then response["status"] = "yellow" end ngx.say(cjson.encode(response))
Fix erroneous passing health check when config fetching failed.
Fix erroneous passing health check when config fetching failed. If elasticsearch was up, but the config fetching from Mongo had failed, we were erroneously returning a "green" status. Also provide more details on the breakdown of the health status to better indicate what pieces are functional or not.
Lua
mit
apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella
788d625549a342a58e7061b94b028f9b7e61b456
OS/DiskOS/Runtime/Globals/01_Lua.lua
OS/DiskOS/Runtime/Globals/01_Lua.lua
--Complete the standard Lua functions. local Globals = (...) or {} local co = select(2,...) or {} local function callevfunc(evf, a,b,c,d,e,f) if evf and type(evf) == "function" then local ok, err = pcall(evf, a,b,c,d,e,f) if not ok then local err = tostring(err) if err:sub(1,12) == '[string ""]:' then err = err:sub(13,-1) end coroutine.yield("RUN:exit", "ERR :"..err) return false end end return true end local function evloop() if not callevfunc(Globals["_init"]) then return end if not ((Globals["_update"] and type(Globals["_update"]) == "function") or (Globals["_draw"] and type(Globals["_draw"]) == "function") or Globals["_eventLoop"]) then return end local time30, time60 = 1/30, 1/60 local timer30, timer60 = 0, 0 while true do local event, a,b,c,d,e,f = pullEvent() if not callevfunc(Globals["_"..event], a,b,c,d,e,f) then return end if event == "update" then if not callevfunc(Globals["_draw"], a,b,c,d,e,f) then return end end local update60, update30 = Globals["_update60"], Globals["_update30"] local draw60, draw30 = Globals["_draw60"], Globals["_draw30"] local has60, has30 = update60 or draw60, update30 or draw30 if event == "update" then if has60 then timer60 = timer60 + a end if has30 then timer30 = timer30 + a end local fallTo30 = (timer60 >= time30) --Originally: timer60 > time60*2 if has60 then if timer60 >= time60 then timer60 = timer60 % time60 if update60 and not (update30 and fallTo30) then if not callevfunc(Globals["_update60"]) then return end end if draw60 and not (draw30 and fallTo30) then if not callevfunc(Globals["_draw60"]) then return end end end end if has30 then if timer30 >= time30 then timer30 = timer30 % time30 if update30 and (fallTo30 or not update60) then if not callevfunc(Globals["_update30"]) then return end end if draw30 and (fallTo30 or not draw60) then if not callevfunc(Globals["_draw30"]) then return end end end end end if event == "keypressed" then Globals.__BTNKeypressed(a,c) elseif event == "update" then Globals.__BTNUpdate(a) elseif event == "touchcontrol" then Globals.__BTNTouchControl(a,b) elseif event == "gamepad" then Globals.__BTNGamepad(a,b,c) end end end local evco = coroutine.create(evloop) Globals.__evco = evco --So the the runtime recieves the event loop coroutine. --Lua functions-- Globals.getfenv = function(f) if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end local ok, env = pcall(getfenv,f) if not ok then return error(env) end if env == _G then env = {} end --Protection return env end Globals.setfenv = function(f,env) if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end local oldenv = getfenv(f) if oldenv == _G then return end --Trying to make a crash ! evil. local ok, err = pcall(setfenv,f,env) if not ok then return error(err) end end Globals.loadstring = function(data) local chunk, err = loadstring(data) if not chunk then return nil, err end setfenv(chunk,glob) return chunk end Globals.coroutine.running = function() local curco = coroutine.running() if co and (curco == co or evco == co) then return end return curco end Globals.dofile = function(path,...) local chunk, err = fs.load(path) if not chunk then return error(err) end setfenv(chunk,Globals) local ok, err = pcall(chunk,...) if not ok then return error(err) end end return Globals
--Complete the standard Lua functions. local Globals = (...) or {} local co = select(2,...) or {} local function callevfunc(evf, a,b,c,d,e,f) if evf and type(evf) == "function" then local ok, err = pcall(evf, a,b,c,d,e,f) if not ok then local err = tostring(err) if err:sub(1,12) == '[string ""]:' then err = err:sub(13,-1) end coroutine.yield("RUN:exit", "ERR :"..err) return false end end return true end local function evloop() if not callevfunc(Globals["_init"]) then return end local functionsToLoop = { "_update", "_draw", "_update60", "_draw60", "_update30", "_draw30" } local shouldLoop = false for id,funcName in pairs(functionsToLoop) do if Globals[funcName] and type(Globals[funcName]) == "function" then shouldLoop = true break end end if type(Globals["_eventLoop"]) == "boolean" then shouldLoop = Globals["_eventLoop"] end if not shouldLoop then return end local time30, time60 = 1/30, 1/60 local timer30, timer60 = 0, 0 while true do local event, a,b,c,d,e,f = pullEvent() if not callevfunc(Globals["_"..event], a,b,c,d,e,f) then return end if event == "update" then if not callevfunc(Globals["_draw"], a,b,c,d,e,f) then return end end local update60, update30 = Globals["_update60"], Globals["_update30"] local draw60, draw30 = Globals["_draw60"], Globals["_draw30"] local has60, has30 = update60 or draw60, update30 or draw30 if event == "update" then if has60 then timer60 = timer60 + a end if has30 then timer30 = timer30 + a end local fallTo30 = (timer60 >= time30) --Originally: timer60 > time60*2 if has60 then if timer60 >= time60 then timer60 = timer60 % time60 if update60 and not (update30 and fallTo30) then if not callevfunc(Globals["_update60"]) then return end end if draw60 and not (draw30 and fallTo30) then if not callevfunc(Globals["_draw60"]) then return end end end end if has30 then if timer30 >= time30 then timer30 = timer30 % time30 if update30 and (fallTo30 or not update60) then if not callevfunc(Globals["_update30"]) then return end end if draw30 and (fallTo30 or not draw60) then if not callevfunc(Globals["_draw30"]) then return end end end end end if event == "keypressed" then Globals.__BTNKeypressed(a,c) elseif event == "update" then Globals.__BTNUpdate(a) elseif event == "touchcontrol" then Globals.__BTNTouchControl(a,b) elseif event == "gamepad" then Globals.__BTNGamepad(a,b,c) end end end local evco = coroutine.create(evloop) Globals.__evco = evco --So the the runtime recieves the event loop coroutine. --Lua functions-- Globals.getfenv = function(f) if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end local ok, env = pcall(getfenv,f) if not ok then return error(env) end if env == _G then env = {} end --Protection return env end Globals.setfenv = function(f,env) if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end local oldenv = getfenv(f) if oldenv == _G then return end --Trying to make a crash ! evil. local ok, err = pcall(setfenv,f,env) if not ok then return error(err) end end Globals.loadstring = function(data) local chunk, err = loadstring(data) if not chunk then return nil, err end setfenv(chunk,glob) return chunk end Globals.coroutine.running = function() local curco = coroutine.running() if co and (curco == co or evco == co) then return end return curco end Globals.dofile = function(path,...) local chunk, err = fs.load(path) if not chunk then return error(err) end setfenv(chunk,Globals) local ok, err = pcall(chunk,...) if not ok then return error(err) end end return Globals
Fix not event looping if only `_update60` is defined.
Fix not event looping if only `_update60` is defined. Former-commit-id: c0ec311db68a8cabcf9244ffa215d14fcc0cf7b3
Lua
mit
RamiLego4Game/LIKO-12
067231a3d1bd366482fecce727a687ffc45fe1fa
core/ext/find.lua
core/ext/find.lua
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then if next then buffer:goto_pos(buffer.current_pos + increment) buffer:search_anchor() result = buffer:search_next(flags, text) else buffer:goto_pos(buffer.anchor - increment) buffer:search_anchor() result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain Lua escape -- sequences to use text captured by a Lua pattern. (%n where 1 <= n <= 9.) function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('[^%%]?[^%%]?%%'..i, v) -- not entirely correct end end buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then if next then buffer:goto_pos(buffer.current_pos + increment) buffer:search_anchor() result = buffer:search_next(flags, text) else buffer:goto_pos(buffer.anchor - increment) buffer:search_anchor() result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain both Lua -- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %() -- sequences for embedding Lua code for any search. function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() rtext = rtext:gsub('%%%%', '\\037') -- escape '%%' if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('%%'..i, v) end end local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())', function(code) local ret, val = pcall( loadstring('return '..code) ) if not ret then os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"') error() end return val end ) if ret then rtext = rtext:gsub('\\037', '%%') -- unescape '%' buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement else -- Since find is called after replace returns, have it 'find' the current -- text again, rather than the next occurance so the user can fix the error. buffer:goto_pos(buffer.current_pos) end end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
Fixed escapes in replace, added %() sequence; core/ext/find.lua '%%' is now properly escaped. %() sequence executes Lua code, showing an error dialog if one occured.
Fixed escapes in replace, added %() sequence; core/ext/find.lua '%%' is now properly escaped. %() sequence executes Lua code, showing an error dialog if one occured.
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
43fc4bca58da9288dda0dc001b647ed45e5267d5
inputters/sil.lua
inputters/sil.lua
local base = require("inputters.base") local epnf = require("epnf") local inputter = pl.class(base) inputter._name = "sil" inputter.order = 50 inputter.appropriate = function (round, filename, doc) if round == 1 then return filename:match(".sil$") elseif round == 2 then local sniff = doc:sub(1, 100) local promising = sniff:match("\\begin") or sniff:match("\\document") or sniff:match("\\sile") return promising and inputter.appropriate(3, filename, doc) elseif round == 3 then local _parser = epnf.define(inputter._grammar) local status, tree = pcall(epnf.parsestring, _parser, doc) local cmd = tree[1][1].command return status and (cmd == "document" or cmd == "sile") end end local bits = SILE.parserBits inputter.passthroughCommands = { ftl = true, lua = true, math = true, raw = true, script = true, sil = true, use = true, xml = true } function inputter:_init () -- Save time when parsing strings by only setting up the grammar once per -- instantiation then re-using it on every use. self._parser = self:rebuildParser() base._init(self) end -- luacheck: push ignore ---@diagnostic disable: undefined-global, unused-local, lowercase-global function inputter._grammar (_ENV) local isPassthrough = function (_, _, command) return inputter.passthroughCommands[command] or false end local isNotPassthrough = function (...) return not isPassthrough(...) end local isMatchingEndEnv = function (a, b, thisCommand, lastCommand) return thisCommand == lastCommand end local _ = WS^0 local eol = S"\r\n" local specials = S"{}%\\" local escaped_specials = P"\\" * specials local unescapeSpecials = function (str) return str:gsub('\\([{}%%\\])', '%1') end local myID = C(bits.silidentifier) / 1 local cmdID = myID - P"beign" - P"end" local wrapper = function (a) return type(a)=="table" and a or {} end local parameters = (P"[" * bits.parameters * P"]")^-1 / wrapper local comment = ( P"%" * P(1-eol)^0 * eol^-1 ) / "" START "document" document = V"texlike_stuff" * EOF"Unexpected character at end of input" texlike_stuff = Cg( V"environment" + comment + V"texlike_text" + V"texlike_braced_stuff" + V"texlike_command" )^0 passthrough_stuff = C(Cg( V"passthrough_text" + V"passthrough_debraced_stuff" )^0) passthrough_env_stuff = Cg( V"passthrough_env_text" )^0 texlike_text = C((1 - specials + escaped_specials)^1) / unescapeSpecials passthrough_text = C((1-S("{}"))^1) passthrough_env_text = C((1 - (P"\\end{" * Cmt(cmdID * Cb"command", isMatchingEndEnv) * P"}"))^1) texlike_braced_stuff = P"{" * V"texlike_stuff" * ( P"}" + E("} expected") ) passthrough_braced_stuff = P"{" * V"passthrough_stuff" * ( P"}" + E("} expected") ) passthrough_debraced_stuff = C(V"passthrough_braced_stuff") texlike_command = ( P"\\" * Cg(cmdID, "command") * Cg(parameters, "options") * ( (Cmt(Cb"command", isPassthrough) * V"passthrough_braced_stuff") + (Cmt(Cb"command", isNotPassthrough) * V"texlike_braced_stuff") )^0 ) local notpass_end = P"\\end{" * ( Cmt(cmdID * Cb"command", isMatchingEndEnv) + E"Environment mismatch") * ( P"}" * _ ) + E"Environment begun but never ended" local pass_end = P"\\end{" * ( cmdID * Cb"command" ) * ( P"}" * _ ) + E"Environment begun but never ended" environment = P"\\begin" * Cg(parameters, "options") * P"{" * Cg(cmdID, "command") * P"}" * ( (Cmt(Cb"command", isPassthrough) * V"passthrough_env_stuff" * pass_end) + (Cmt(Cb"command", isNotPassthrough) * V"texlike_stuff" * notpass_end) ) end -- luacheck: pop ---@diagnostic enable: undefined-global, unused-local, lowercase-global local linecache = {} local lno, col, lastpos local function resetCache () lno = 1 col = 1 lastpos = 0 linecache = { { lno = 1, pos = 1} } end local function getline (str, pos) local start = 1 lno = 1 if pos > lastpos then lno = linecache[#linecache].lno start = linecache[#linecache].pos + 1 col = 1 else for j = 1, #linecache-1 do if linecache[j+1].pos >= pos then lno = linecache[j].lno col = pos - linecache[j].pos return lno, col end end end for i = start, pos do if string.sub( str, i, i ) == "\n" then lno = lno + 1 col = 1 linecache[#linecache+1] = { pos = i, lno = lno } lastpos = i end col = col + 1 end return lno, col end local function massage_ast (tree, doc) -- Sort out pos if type(tree) == "string" then return tree end if tree.pos then tree.lno, tree.col = getline(doc, tree.pos) end if tree.id == "document" or tree.id == "texlike_braced_stuff" or tree.id == "passthrough_stuff" or tree.id == "passthrough_braced_stuff" or tree.id == "passthrough_env_stuff" then return massage_ast(tree[1], doc) end if tree.id == "texlike_text" or tree.id == "passthrough_text" or tree.id == "passthrough_env_text" then return tree[1] end for key, val in ipairs(tree) do if val.id == "texlike_stuff" then SU.splice(tree, key, key, massage_ast(val, doc)) else tree[key] = massage_ast(val, doc) end end return tree end function inputter:rebuildParser () return epnf.define(self._grammar) end function inputter:parse (doc) local tree = epnf.parsestring(self._parser, doc)[1] if not tree then return SU.error("Unable to parse input document to an AST tree") end resetCache() local ast = massage_ast(tree, doc) return ast end return inputter
local base = require("inputters.base") local epnf = require("epnf") local inputter = pl.class(base) inputter._name = "sil" inputter.order = 50 inputter.appropriate = function (round, filename, doc) if round == 1 then return filename:match(".sil$") elseif round == 2 then local sniff = doc:sub(1, 100) local promising = sniff:match("\\begin") or sniff:match("\\document") or sniff:match("\\sile") return promising and inputter.appropriate(3, filename, doc) or false elseif round == 3 then local _parser = epnf.define(inputter._grammar) local status, _ = pcall(epnf.parsestring, _parser, doc) return status end end local bits = SILE.parserBits inputter.passthroughCommands = { ftl = true, lua = true, math = true, raw = true, script = true, sil = true, use = true, xml = true } function inputter:_init () -- Save time when parsing strings by only setting up the grammar once per -- instantiation then re-using it on every use. self._parser = self:rebuildParser() base._init(self) end -- luacheck: push ignore ---@diagnostic disable: undefined-global, unused-local, lowercase-global function inputter._grammar (_ENV) local isPassthrough = function (_, _, command) return inputter.passthroughCommands[command] or false end local isNotPassthrough = function (...) return not isPassthrough(...) end local isMatchingEndEnv = function (a, b, thisCommand, lastCommand) return thisCommand == lastCommand end local _ = WS^0 local eol = S"\r\n" local specials = S"{}%\\" local escaped_specials = P"\\" * specials local unescapeSpecials = function (str) return str:gsub('\\([{}%%\\])', '%1') end local myID = C(bits.silidentifier) / 1 local cmdID = myID - P"beign" - P"end" local wrapper = function (a) return type(a)=="table" and a or {} end local parameters = (P"[" * bits.parameters * P"]")^-1 / wrapper local comment = ( P"%" * P(1-eol)^0 * eol^-1 ) / "" START "document" document = V"texlike_stuff" * EOF"Unexpected character at end of input" texlike_stuff = Cg( V"environment" + comment + V"texlike_text" + V"texlike_braced_stuff" + V"texlike_command" )^0 passthrough_stuff = C(Cg( V"passthrough_text" + V"passthrough_debraced_stuff" )^0) passthrough_env_stuff = Cg( V"passthrough_env_text" )^0 texlike_text = C((1 - specials + escaped_specials)^1) / unescapeSpecials passthrough_text = C((1-S("{}"))^1) passthrough_env_text = C((1 - (P"\\end{" * Cmt(cmdID * Cb"command", isMatchingEndEnv) * P"}"))^1) texlike_braced_stuff = P"{" * V"texlike_stuff" * ( P"}" + E("} expected") ) passthrough_braced_stuff = P"{" * V"passthrough_stuff" * ( P"}" + E("} expected") ) passthrough_debraced_stuff = C(V"passthrough_braced_stuff") texlike_command = ( P"\\" * Cg(cmdID, "command") * Cg(parameters, "options") * ( (Cmt(Cb"command", isPassthrough) * V"passthrough_braced_stuff") + (Cmt(Cb"command", isNotPassthrough) * V"texlike_braced_stuff") )^0 ) local notpass_end = P"\\end{" * ( Cmt(cmdID * Cb"command", isMatchingEndEnv) + E"Environment mismatch") * ( P"}" * _ ) + E"Environment begun but never ended" local pass_end = P"\\end{" * ( cmdID * Cb"command" ) * ( P"}" * _ ) + E"Environment begun but never ended" environment = P"\\begin" * Cg(parameters, "options") * P"{" * Cg(cmdID, "command") * P"}" * ( (Cmt(Cb"command", isPassthrough) * V"passthrough_env_stuff" * pass_end) + (Cmt(Cb"command", isNotPassthrough) * V"texlike_stuff" * notpass_end) ) end -- luacheck: pop ---@diagnostic enable: undefined-global, unused-local, lowercase-global local linecache = {} local lno, col, lastpos local function resetCache () lno = 1 col = 1 lastpos = 0 linecache = { { lno = 1, pos = 1} } end local function getline (str, pos) local start = 1 lno = 1 if pos > lastpos then lno = linecache[#linecache].lno start = linecache[#linecache].pos + 1 col = 1 else for j = 1, #linecache-1 do if linecache[j+1].pos >= pos then lno = linecache[j].lno col = pos - linecache[j].pos return lno, col end end end for i = start, pos do if string.sub( str, i, i ) == "\n" then lno = lno + 1 col = 1 linecache[#linecache+1] = { pos = i, lno = lno } lastpos = i end col = col + 1 end return lno, col end local function massage_ast (tree, doc) -- Sort out pos if type(tree) == "string" then return tree end if tree.pos then tree.lno, tree.col = getline(doc, tree.pos) end if tree.id == "document" or tree.id == "texlike_braced_stuff" or tree.id == "passthrough_stuff" or tree.id == "passthrough_braced_stuff" or tree.id == "passthrough_env_stuff" then return massage_ast(tree[1], doc) end if tree.id == "texlike_text" or tree.id == "passthrough_text" or tree.id == "passthrough_env_text" then return tree[1] end for key, val in ipairs(tree) do if val.id == "texlike_stuff" then SU.splice(tree, key, key, massage_ast(val, doc)) else tree[key] = massage_ast(val, doc) end end return tree end function inputter:rebuildParser () return epnf.define(self._grammar) end function inputter:parse (doc) local tree = epnf.parsestring(self._parser, doc)[1] if not tree then return SU.error("Unable to parse input document to an AST tree") end resetCache() local ast = massage_ast(tree, doc) return ast end return inputter
fix(inputters): Relax SIL format sniffing to allow valid syntax
fix(inputters): Relax SIL format sniffing to allow valid syntax This allows the content sniffer to succeed and tag content as SIL when the syntax is valid even if the document is invalid (e.g. not wrapped in a single top level document tag). This helps with correctly identifying STDIN streams that happen to be SIL and moves the ball down the road. Our later parsing step basically redoes the same work but then has better checks for a valid AST tree and hence better error messages in the event of a malformed document.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
d2f6309d694944eff0b1c93a4bde3283a12db3e3
config/nvim/init.lua
config/nvim/init.lua
local ext = require("ext") require = ext.require vim = _G.vim vim.map = ext.vim.mapping("") vim.imap = ext.vim.mapping("i") vim.nmap = ext.vim.mapping("n") vim.omap = ext.vim.mapping("o") vim.smap = ext.vim.mapping("s") vim.vmap = ext.vim.mapping("v") vim.xmap = ext.vim.mapping("x") vim.hl = ext.vim.highlight vim.hl_link = ext.vim.highlight_link --- General vim.g.mapleader = " " vim.opt.clipboard = {"unnamedplus"} vim.opt.hidden = true vim.opt.shell = vim.fn.system("which bash"):trim() vim.opt.shellcmdflag = "-lc" vim.opt.showmatch = true vim.opt.splitbelow = true vim.opt.splitright = true vim.opt.updatetime = 300 vim.opt.wildmode = vim.opt.wildmode ^ {"longest:full"} vim.cmd("syntax on") --- Appearance vim.opt.cmdheight = 1 vim.opt.completeopt = {"menuone", "noselect"} vim.opt.cursorline = true vim.opt.list = true vim.opt.listchars = {eol = "↵", tab = "⇥ ", trail = "·"} vim.opt.number = true vim.opt.scrolloff = 20 vim.opt.shortmess = vim.opt.shortmess + {c = true} vim.opt.showmode = false vim.opt.showtabline = 2 vim.opt.signcolumn = "yes" vim.opt.termguicolors = true vim.opt.wrap = false --- Tabbing vim.opt.cindent = true vim.opt.expandtab = true vim.opt.shiftwidth = 2 vim.opt.softtabstop = 2 vim.opt.tabstop = 2 --- Search & History vim.opt.ignorecase = true vim.opt.inccommand = "nosplit" vim.opt.swapfile = false vim.opt.writebackup = false vim.opt.smartcase = true --- Key bindings vim.nmap("<Leader>q", ":q<CR>") vim.nmap("<Leader>w", ":w<CR>") -- No confusing window vim.map("q:", "<NOP>") -- No Ex mode vim.map("Q", "<NOP>") -- No help window vim.map("<F1>", "<Esc>") vim.imap("<F1>", "<Esc>") -- Quickly clear highlighted search vim.nmap("<Leader><Leader>", ":nohlsearch<CR>", {silent = true}) -- Consistent indent/unindent across all modes vim.nmap("<C-d>", "<<") vim.nmap("<C-t>", ">>") vim.xmap("<C-d>", "<gv") vim.xmap("<C-t>", ">gv") -- Move around more quickly vim.nmap("<C-b>", "<NOP>") vim.xmap("<C-b>", "<NOP>") vim.nmap("<C-f>", "<NOP>") vim.xmap("<C-f>", "<NOP>") vim.nmap("<C-n>", "<NOP>") vim.xmap("<C-n>", "<NOP>") vim.nmap("<C-u>", "<NOP>") vim.xmap("<C-u>", "<NOP>") vim.nmap("<M-k>", "{") vim.xmap("<M-k>", "{") vim.nmap("<M-j>", "}") vim.xmap("<M-j>", "}") vim.nmap("<M-h>", "0") vim.xmap("<M-h>", "0") vim.nmap("<M-l>", "$") vim.xmap("<M-l>", "$") -- Splits vim.nmap("<C-w>|", ":vsplit<CR>", {silent = true}) vim.nmap("<C-w>_", ":split<CR>", {silent = true}) vim.nmap("<C-w>h", ":vertical resize +5<CR>", {silent = true}) vim.nmap("<C-w>j", ":resize -5<CR>", {silent = true}) vim.nmap("<C-w>k", ":resize +5<CR>", {silent = true}) vim.nmap("<C-w>l", ":vertical resize -5<CR>", {silent = true}) -- Ctag navigation vim.nmap("<Leader>[", ":pop<CR>", {silent = true}) vim.nmap("<Leader>]", "<C-]>") -- Automatically jump to end of pasted text vim.nmap("p", "p`]", {silent = true}) vim.xmap("p", "p`]", {silent = true}) vim.xmap("y", "y`]", {silent = true}) -- LSP vim.fn.sign_define("LspDiagnosticsSignError", {text = "", texthl = "LspDiagnosticsSignError"}) vim.fn.sign_define("LspDiagnosticsSignHint", {text = "", texthl = "LspDiagnosticsSignHint"}) vim.fn.sign_define("LspDiagnosticsSignInformation", {text = "", texthl = "LspDiagnosticsSignInformation"}) vim.fn.sign_define("LspDiagnosticsSignWarning", {text = "", texthl = "LspDiagnosticsSignWarning"}) vim.nmap("gd", "v:lua.vim.lsp.buf.definition()", {expr = true}) vim.nmap("gD", "v:lua.vim.lsp.buf.declaration()", {expr = true}) vim.nmap("gi", "v:lua.vim.lsp.buf.implementation()", {expr = true}) vim.nmap("gr", "v:lua.vim.lsp.buf.references()", {expr = true}) vim.nmap("F", "v:lua.vim.lsp.buf.formatting()", {expr = true}) vim.nmap("K", "v:lua.vim.lsp.buf.hover()", {expr = true}) --- Plugins require("plugins") --- Overrides require("init.plugins") require.tree("init")
local ext = require("ext") require = ext.require vim = _G.vim vim.map = ext.vim.mapping("") vim.imap = ext.vim.mapping("i") vim.nmap = ext.vim.mapping("n") vim.omap = ext.vim.mapping("o") vim.smap = ext.vim.mapping("s") vim.vmap = ext.vim.mapping("v") vim.xmap = ext.vim.mapping("x") vim.hl = ext.vim.highlight vim.hl_link = ext.vim.highlight_link --- General vim.g.mapleader = " " vim.opt.clipboard = {"unnamedplus"} vim.opt.hidden = true vim.opt.shell = vim.fn.system("which bash"):trim() vim.opt.shellcmdflag = "-lc" vim.opt.showmatch = true vim.opt.splitbelow = true vim.opt.splitright = true vim.opt.updatetime = 300 vim.opt.wildmode = vim.opt.wildmode ^ {"longest:full"} vim.cmd("syntax on") --- Appearance vim.opt.cmdheight = 1 vim.opt.completeopt = {"menuone", "noselect"} vim.opt.cursorline = true vim.opt.list = true vim.opt.listchars = {eol = "↵", tab = "⇥ ", trail = "·"} vim.opt.number = true vim.opt.scrolloff = 20 vim.opt.shortmess = vim.opt.shortmess + {c = true} vim.opt.showmode = false vim.opt.showtabline = 2 vim.opt.signcolumn = "yes" vim.opt.termguicolors = true vim.opt.wrap = false --- Tabbing vim.opt.cindent = true vim.opt.expandtab = true vim.opt.shiftwidth = 2 vim.opt.softtabstop = 2 vim.opt.tabstop = 2 --- Search & History vim.opt.ignorecase = true vim.opt.inccommand = "nosplit" vim.opt.swapfile = false vim.opt.writebackup = false vim.opt.smartcase = true --- Key bindings vim.nmap("<Leader>q", ":q<CR>") vim.nmap("<Leader>w", ":w<CR>") -- No confusing window vim.map("q:", "<NOP>") -- No Ex mode vim.map("Q", "<NOP>") -- No help window vim.map("<F1>", "<Esc>") vim.imap("<F1>", "<Esc>") -- Quickly clear highlighted search vim.nmap("<Leader><Leader>", ":nohlsearch<CR>", {silent = true}) -- Consistent indent/unindent across all modes vim.nmap("<C-d>", "<<") vim.nmap("<C-t>", ">>") vim.xmap("<C-d>", "<gv") vim.xmap("<C-t>", ">gv") -- Move around more quickly vim.nmap("<C-b>", "<NOP>") vim.xmap("<C-b>", "<NOP>") vim.nmap("<C-f>", "<NOP>") vim.xmap("<C-f>", "<NOP>") vim.nmap("<C-n>", "<NOP>") vim.xmap("<C-n>", "<NOP>") vim.nmap("<C-u>", "<NOP>") vim.xmap("<C-u>", "<NOP>") vim.nmap("<M-k>", "{") vim.xmap("<M-k>", "{") vim.nmap("<M-j>", "}") vim.xmap("<M-j>", "}") vim.nmap("<M-h>", "0") vim.xmap("<M-h>", "0") vim.nmap("<M-l>", "$") vim.xmap("<M-l>", "$") -- Splits vim.nmap("<C-w>|", ":vsplit<CR>", {silent = true}) vim.nmap("<C-w>_", ":split<CR>", {silent = true}) vim.nmap("<C-w>h", ":vertical resize +5<CR>", {silent = true}) vim.nmap("<C-w>j", ":resize -5<CR>", {silent = true}) vim.nmap("<C-w>k", ":resize +5<CR>", {silent = true}) vim.nmap("<C-w>l", ":vertical resize -5<CR>", {silent = true}) -- Ctag navigation vim.nmap("<Leader>[", ":pop<CR>", {silent = true}) vim.nmap("<Leader>]", "<C-]>") -- Automatically jump to end of pasted text vim.nmap("p", "p`]", {silent = true}) vim.xmap("p", "p`]", {silent = true}) vim.xmap("y", "y`]", {silent = true}) -- LSP vim.fn.sign_define("LspDiagnosticsSignError", {text = "", texthl = "LspDiagnosticsSignError"}) vim.fn.sign_define("LspDiagnosticsSignHint", {text = "", texthl = "LspDiagnosticsSignHint"}) vim.fn.sign_define("LspDiagnosticsSignInformation", {text = "", texthl = "LspDiagnosticsSignInformation"}) vim.fn.sign_define("LspDiagnosticsSignWarning", {text = "", texthl = "LspDiagnosticsSignWarning"}) vim.nmap("gd", ":lua vim.lsp.buf.definition()<CR>", {silent = true}) vim.nmap("gD", ":lua vim.lsp.buf.declaration()<CR>", {silent = true}) vim.nmap("gi", ":lua vim.lsp.buf.implementation()<CR>", {silent = true}) vim.nmap("gr", ":lua vim.lsp.buf.references()<CR>", {silent = true}) vim.nmap("F", ":lua vim.lsp.buf.formatting()<CR>", {silent = true}) vim.nmap("K", ":lua vim.lsp.buf.hover()<CR>", {silent = true}) --- Plugins require("plugins") --- Overrides require("init.plugins") require.tree("init")
Fix keybindings
Fix keybindings
Lua
mit
charlesbjohnson/dotfiles,charlesbjohnson/dotfiles
7c60d0749f1696ef5f9b7a5ec31c653c6e70c254
data/notmnist.lua
data/notmnist.lua
------------------------------------------------------------------------ --[[ NotMnist ]]-- -- http://yaroslavvb.blogspot.ca/2011/09/notmnist-dataset.html -- http://yaroslavvb.com/upload/notMNIST/ -- A 500k+ example alternative to MNIST using unicode fonts. ------------------------------------------------------------------------ local NotMnist, DataSource = torch.class("dp.NotMnist", "dp.DataSource") NotMnist.isNotMnist= true NotMnist._name = 'notMnist' NotMnist._image_size = {28, 28, 1} NotMnist._image_axes = 'bhwc' NotMnist._feature_size = 28*28*1 NotMnist._classes = {'A','B','C','D','E','F','G','H','I','J'} function NotMnist:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local load_all, input_preprocess, target_preprocess self._args, self._valid_ratio, self._train_dir, self._test_dir, self._data_path, self._scale, self._binarize, self._download_url, load_all, input_preprocess, target_preprocess = xlua.unpack( {config}, 'NotMnist', nil, {arg='valid_ratio', type='number', default=1/6, help='proportion of training set to use for cross-validation.'}, {arg='train_dir', type='string', default='notMNIST_large', help='name of test_dir'}, {arg='test_dir', type='string', default='notMNIST_small', help='name of test_dir'}, {arg='data_path', type='string', default=dp.DATA_DIR, help='path to data repository'}, {arg='scale', type='table', help='bounds to scale the values between', default={0,1}}, {arg='binarize', type='boolean', help='binarize the inputs (0s and 1s)', default=false}, {arg='download_url', type='string', default='http://yaroslavvb.com/upload/notMNIST/', help='URL from which to download dataset if not found on disk.'}, {arg='load_all', type='boolean', help='Load all datasets : train, valid, test.', default=true}, {arg='input_preprocess', type='table | dp.Preprocess', help='to be performed on set inputs, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'}, {arg='target_preprocess', type='table | dp.Preprocess', help='to be performed on set targets, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'} ) if load_all then self:loadTrainValid() self:loadTest() end DataSource.__init(self, {train_set=self:trainSet(), valid_set=self:validSet(), test_set=self:testSet(), input_preprocess=input_preprocess, target_preprocess=target_preprocess}) end function NotMnist:loadTrainValid() local bad_png = { --these wont load as PNGs, ignore them ['A'] = { 'RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png', 'Um9tYW5hIEJvbGQucGZi.png', 'SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png' }, ['B'] = {'TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png'}, ['D'] = {'VHJhbnNpdCBCb2xkLnR0Zg==.png'} } local inputs, targets = self:loadData( self._train_dir, self._download_url, bad_png ) -- train local start = 1 local size = math.floor(inputs:size(1)*(1-self._valid_ratio)) self:setTrainSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'train' ) ) -- valid start = size + 1 size = inputs:size(1) - start self:setValidSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'valid' ) ) return self:trainSet(), self:validSet() end function NotMnist:loadTest() local bad_png = { ['A'] = {'RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png'}, ['F'] = {'Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png'} } local inputs, targets = self:loadData( self._test_dir, self._download_url, bad_png ) self:setTestSet(self:createDataSet(inputs, targets, 'test')) return self:testSet() end --Creates an Mnist Dataset out of data and which_set function NotMnist:createDataSet(inputs, targets, which_set) if self._binarize then DataSource.binarize(inputs, 128) end if self._scale and not self._binarize then DataSource.rescale(inputs, self._scale[1], self._scale[2]) end -- construct inputs and targets dp.Views local input_v, target_v = dp.ImageView(), dp.ClassView() input_v:forward(self._image_axes, inputs) target_v:forward('b', targets) target_v:setClasses(self._classes) -- construct dataset return dp.DataSet{inputs=input_v,targets=target_v,which_set=which_set} end -- Get the raw, unprocessed DataSet. -- Returns a 60,000 x 785 tensor, where each image is 28*28 = 784 values in the -- range [0-255], and the 785th element is the class ID. function NotMnist:loadData(file_name, download_url, bad_png) local doc_path = DataSource.getDataPath{ name=self._name, url=download_url..file_name..'.tar.gz', decompress_file=file_name, data_dir=self._data_path } local n_example = 0 local classes = self._classes local n_example = 0 for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then n_example = n_example + 1 else --print(class, file) end end end local inputs = torch.FloatTensor(n_example, unpack(self._image_size)) local targets = torch.Tensor(n_example) local shuffle = torch.randperm(n_example) --useless for test set local example_idx = 1 for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then local filename = paths.concat(classpath, file) local ds_idx = shuffle[example_idx] inputs[{ds_idx,{},{},{}}] = image.loadPNG(filename):float() targets[ds_idx] = classidx example_idx = example_idx + 1 end end end return inputs, targets end
------------------------------------------------------------------------ --[[ NotMnist ]]-- -- http://yaroslavvb.blogspot.ca/2011/09/notmnist-dataset.html -- http://yaroslavvb.com/upload/notMNIST/ -- A 500k+ example alternative to MNIST using unicode fonts. ------------------------------------------------------------------------ local NotMnist, DataSource = torch.class("dp.NotMnist", "dp.DataSource") NotMnist.isNotMnist= true NotMnist._name = 'notMnist' NotMnist._image_size = {28, 28, 1} NotMnist._image_axes = 'bhwc' NotMnist._feature_size = 28*28*1 NotMnist._classes = {'A','B','C','D','E','F','G','H','I','J'} function NotMnist:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local load_all, input_preprocess, target_preprocess self._args, self._valid_ratio, self._train_dir, self._test_dir, self._data_path, self._scale, self._binarize, self._download_url, load_all, input_preprocess, target_preprocess = xlua.unpack( {config}, 'NotMnist', nil, {arg='valid_ratio', type='number', default=1/6, help='proportion of training set to use for cross-validation.'}, {arg='train_dir', type='string', default='notMNIST_large', help='name of test_dir'}, {arg='test_dir', type='string', default='notMNIST_small', help='name of test_dir'}, {arg='data_path', type='string', default=dp.DATA_DIR, help='path to data repository'}, {arg='scale', type='table', help='bounds to scale the values between', default={0,1}}, {arg='binarize', type='boolean', help='binarize the inputs (0s and 1s)', default=false}, {arg='download_url', type='string', default='http://yaroslavvb.com/upload/notMNIST/', help='URL from which to download dataset if not found on disk.'}, {arg='load_all', type='boolean', help='Load all datasets : train, valid, test.', default=true}, {arg='input_preprocess', type='table | dp.Preprocess', help='to be performed on set inputs, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'}, {arg='target_preprocess', type='table | dp.Preprocess', help='to be performed on set targets, measuring statistics ' .. '(fitting) on the train_set only, and reusing these to ' .. 'preprocess the valid_set and test_set.'} ) if load_all then self:loadTrainValid() self:loadTest() end DataSource.__init(self, {train_set=self:trainSet(), valid_set=self:validSet(), test_set=self:testSet(), input_preprocess=input_preprocess, target_preprocess=target_preprocess}) end function NotMnist:loadTrainValid() local bad_png = { --these wont load as PNGs, ignore them ['A'] = { 'RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png', 'Um9tYW5hIEJvbGQucGZi.png', 'SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png' }, ['B'] = {'TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png'}, ['D'] = {'VHJhbnNpdCBCb2xkLnR0Zg==.png'} } local inputs, targets = self:loadData( self._train_dir, self._download_url, bad_png ) -- train local start = 1 local size = math.floor(inputs:size(1)*(1-self._valid_ratio)) self:setTrainSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'train' ) ) -- valid start = size + 1 size = inputs:size(1) - start self:setValidSet( self:createDataSet( inputs:narrow(1, start, size), targets:narrow(1, start, size), 'valid' ) ) return self:trainSet(), self:validSet() end function NotMnist:loadTest() local bad_png = { ['A'] = {'RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png'}, ['F'] = {'Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png'} } local inputs, targets = self:loadData( self._test_dir, self._download_url, bad_png ) self:setTestSet(self:createDataSet(inputs, targets, 'test')) return self:testSet() end --Creates an NotMnist Dataset out of data and which_set function NotMnist:createDataSet(inputs, targets, which_set) if self._binarize then DataSource.binarize(inputs, 128) end if self._scale and not self._binarize then DataSource.rescale(inputs, self._scale[1], self._scale[2]) end -- construct inputs and targets dp.Views local input_v, target_v = dp.ImageView(), dp.ClassView() input_v:forward(self._image_axes, inputs) target_v:forward('b', targets) target_v:setClasses(self._classes) -- construct dataset return dp.DataSet{inputs=input_v,targets=target_v,which_set=which_set} end function NotMnist:loadData(file_name, download_url, bad_png) local doc_path = DataSource.getDataPath{ name=self._name, url=download_url..file_name..'.tar.gz', decompress_file=file_name, data_dir=self._data_path } local n_example = 0 local classes = self._classes for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then n_example = n_example + 1 else --print(class, file) end end end local inputs = torch.FloatTensor(n_example, unpack(self._image_size)) local targets = torch.Tensor(n_example) local shuffle = torch.randperm(n_example) --useless for test set local example_idx = 1 for classidx, class in ipairs(classes) do local classpath = paths.concat(doc_path, class) for file in lfs.dir(classpath) do if #file > 2 and not _.contains(bad_png[class] or {}, file) then local filename = paths.concat(classpath, file) local ds_idx = shuffle[example_idx] inputs[{ds_idx,{},{},{}}] = image.loadPNG(filename):float() targets[ds_idx] = classidx example_idx = example_idx + 1 end end end return inputs, targets end
NotMnist fixes
NotMnist fixes
Lua
bsd-3-clause
nicholas-leonard/dp,sagarwaghmare69/dp,kracwarlock/dp,rickyHong/dptorchLib,fiskio/dp,jnhwkim/dp,eulerreich/dp
8deab10dd8ef2e03277c919054e02380d3cad2d8
PokePrecSucc.lua
PokePrecSucc.lua
--[[ Navigation bar with previous and next Pokémon in dex order. This module exports two functions. One is the "PokePrecSucc", intended to be used within Pokémon pages, that links the previous and next Pokémon pages. The other is "subpage", intended to be used in Pokémon subpages to link corresponding subpages of previous and next Pokémon. --]] local m = {} local mw = require('mw') local txt = require('Wikilib-strings') -- luacheck: no unused local multigen = require('Wikilib-multigen') local prevnext = require('PrevNext') local data = require("Wikilib-data") local pokes = require("Poké-data") --[[ Base (internal) function to create a PokePrecSucc. Performs basic operations such as computing previous and next Pokémon ndex, and preparing the printed text. Parameters: - poke: the Pokémon name - linksuffix: (optional) the suffix to append to links. It defaults to nothing (ie: links base Pokémon pages). This suffix is appended as is; it's not modified, for instance, adding a leading "/". - list: (optional) the page to link in the middle of the prevnext. --]] local function basePokePrecSucc(poke, linksuffix, list) linksuffix = linksuffix or "" list = list or "Elenco Pokémon secondo il Pokédex Nazionale" local pokeData = multigen.getGen(pokes[poke] or pokes[mw.text.decode(poke)]) local type1, type2 = pokeData.type1, pokeData.type2 local prev = (pokeData.ndex - 2 + data.pokeNum) % data.pokeNum + 1 local next = pokeData.ndex % data.pokeNum + 1 local prevTf, nextTf = string.tf(prev), string.tf(next) local prevname, nextname = pokes[prev].name, pokes[next].name return prevnext.PrevNextLua{ color = type1, color2 = type2, series = pokeData.name, list = list, prev = table.concat{"#", prevTf, ": ", prevname}, prevlink = prevname .. linksuffix, prevspr = prevTf, next = table.concat{"#", nextTf, ": ", nextname}, nextlink = nextname .. linksuffix, nextspr = nextTf, } end --[[ Function to create a PrecSucc of subpages. Usage: {{#invoke: PokePrecSucc | subpage | <Pokémon name> | <suffix> | ... }} - 1: (optional) the name of a Pokémon. In a Pokémon subpage the suggested value for this is "{{ROOTPAGENAME}}", that evaluates to the page name that (often) is the Pokémon name desired. It defaults to the root page title. - 2: (optional) if given, it is used to determine the subpage to link. It should be the name of the subpage to link without the leading /. It defaults to the same suffix as the page it's invoked in. - list: (optional) the page to link from the middle text (the name of the current Pokémon). Defaults to "Elenco Pokémon secondo il Pokédex Nazionale" --]] m.subpage = function(frame) local poke = string.trim(frame.args[1] or mw.title.getCurrentTitle().rootText):lower() local subpageSuffix = "" if frame.args[2] then subpageSuffix = "/" .. string.trim(frame.args[2]) else local title = mw.title.getCurrentTitle() if title.isSubpage then subpageSuffix = "/" .. mw.title.getCurrentTitle().subpageText end end local list = frame.args.list and string.trim(frame.args.list) or "Elenco Pokémon secondo il Pokédex Nazionale" return basePokePrecSucc(poke, subpageSuffix, list) end --[[ Function to create a PrecSucc in a Pokémon page. Usage: {{#invoke: PokePrecSucc | PokePrecSucc | <Pokémon name> }} - 1: (optional) the name of a Pokémon. In a Pokémon the suggested value for this is "{{PAGENAME}}", that evaluates to the page name that (often) is the Pokémon name desired. If not given, it defaults to the page title. --]] m.PokePrecSucc = function(frame) local poke = string.trim(frame.args[1] or mw.title.getCurrentTitle().text):lower() return basePokePrecSucc(poke) end m.pokeprecsucc, m.pokePrecSucc = m.PokePrecSucc, m.PokePrecSucc return m
--[[ Navigation bar with previous and next Pokémon in dex order. This module exports two functions. One is the "PokePrecSucc", intended to be used within Pokémon pages, that links the previous and next Pokémon pages. The other is "subpage", intended to be used in Pokémon subpages to link corresponding subpages of previous and next Pokémon. --]] local m = {} local mw = require('mw') local txt = require('Wikilib-strings') -- luacheck: no unused local multigen = require('Wikilib-multigen') local prevnext = require('PrevNext') local data = require("Wikilib-data") local pokes = require("Poké-data") --[[ Base (internal) function to create a PokePrecSucc. Performs basic operations such as computing previous and next Pokémon ndex, and preparing the printed text. Parameters: - poke: the Pokémon name - linksuffix: (optional) the suffix to append to links. It defaults to nothing (ie: links base Pokémon pages). This suffix is appended as is; it's not modified, for instance, adding a leading "/". - list: (optional) the page to link in the middle of the prevnext. --]] local function basePokePrecSucc(poke, linksuffix, list) linksuffix = linksuffix or "" list = list or "Elenco Pokémon secondo il Pokédex Nazionale" local pokeData = multigen.getGen(pokes[poke] or pokes[mw.text.decode(poke)]) local type1, type2 = pokeData.type1, pokeData.type2 local prev = (pokeData.ndex - 2 + data.pokeNum) % data.pokeNum + 1 local next = pokeData.ndex % data.pokeNum + 1 local prevTf, nextTf = string.tf(prev), string.tf(next) local prevname, nextname = pokes[prev].name, pokes[next].name return prevnext.PrevNextLua{ color = type1, color2 = type2, series = pokeData.name, list = list, prev = table.concat{"#", prevTf, ": ", prevname}, prevlink = prevname .. linksuffix, prevspr = prevTf, next = table.concat{"#", nextTf, ": ", nextname}, nextlink = nextname .. linksuffix, nextspr = nextTf, } end --[[ Function to create a PrecSucc of subpages. Usage: {{#invoke: PokePrecSucc | subpage | <Pokémon name> | <suffix> | ... }} - 1: (optional) the name of a Pokémon. In a Pokémon subpage the suggested value for this is "{{ROOTPAGENAME}}", that evaluates to the page name that (often) is the Pokémon name desired. It defaults to the root page title. - 2: (optional) if given, it is used to determine the subpage to link. It should be the name of the subpage to link without the leading /. It defaults to the same suffix as the page it's invoked in. - list: (optional) the page to link from the middle text (the name of the current Pokémon). Defaults to "Elenco Pokémon secondo il Pokédex Nazionale" --]] m.subpage = function(frame) local poke = string.trim(frame.args[1] or mw.title.getCurrentTitle().rootText):lower() local subpageSuffix = "" if frame.args[2] then subpageSuffix = "/" .. string.trim(frame.args[2]) else local title = mw.title.getCurrentTitle() if title.isSubpage then subpageSuffix = "/" .. mw.title.getCurrentTitle().subpageText end end return basePokePrecSucc(poke, subpageSuffix, poke) end --[[ Function to create a PrecSucc in a Pokémon page. Usage: {{#invoke: PokePrecSucc | PokePrecSucc | <Pokémon name> }} - 1: (optional) the name of a Pokémon. In a Pokémon the suggested value for this is "{{PAGENAME}}", that evaluates to the page name that (often) is the Pokémon name desired. If not given, it defaults to the page title. --]] m.PokePrecSucc = function(frame) local poke = string.trim(frame.args[1] or mw.title.getCurrentTitle().text):lower() return basePokePrecSucc(poke) end m.pokeprecsucc, m.pokePrecSucc = m.PokePrecSucc, m.PokePrecSucc return m
Fixing link of PrevNext in Pokémon subpages
Fixing link of PrevNext in Pokémon subpages
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
2afdcddad880ad5f3694070bb3b8a7692ac375ec
TemporalAdapter.lua
TemporalAdapter.lua
require 'torch' require 'nn' --[[ A TemporalAdapter wraps a module intended to work on a minibatch of inputs and allows you to use it on a minibatch of sequences of inputs. The constructor accepts a module; we assume that the module operates expects to receive a minibatch of inputs of shape (N, A) and produce a minibatch of outputs of shape (N, B). The resulting TemporalAdapter then expects inputs of shape (N, T, A) and returns outputs of shape (N, T, B), applying the wrapped module at all timesteps. TODO: Extend this to work with modules that want inputs of arbitrary dimension; right now it can only wrap modules expecting a 2D input. --]] local layer, parent = torch.class('nn.TemporalAdapter', 'nn.Module') function layer:__init(module) self.view_in = nn.View(1, -1):setNumInputDims(3) self.view_out = nn.View(1, -1):setNumInputDims(2) self.net = nn.Sequential() self.net:add(self.view_in) self.net:add(module) self.net:add(self.view_out) end function layer:updateOutput(input) local N, T = input:size(1), input:size(2) self.view_in:resetSize(N * T, -1) self.view_out:resetSize(N, T, -1) self.output = self.net:forward(input) return self.output end function layer:updateGradInput(input, gradOutput) self.gradInput = self.net:updateGradInput(input, gradOutput) return self.gradInput end
require 'torch' require 'nn' --[[ A TemporalAdapter wraps a module intended to work on a minibatch of inputs and allows you to use it on a minibatch of sequences of inputs. The constructor accepts a module; we assume that the module operates expects to receive a minibatch of inputs of shape (N, A) and produce a minibatch of outputs of shape (N, B). The resulting TemporalAdapter then expects inputs of shape (N, T, A) and returns outputs of shape (N, T, B), applying the wrapped module at all timesteps. TODO: Extend this to work with modules that want inputs of arbitrary dimension; right now it can only wrap modules expecting a 2D input. --]] local layer, parent = torch.class('nn.TemporalAdapter', 'nn.Module') function layer:__init(module) self.view_in = nn.View(1, -1):setNumInputDims(3) self.view_out = nn.View(1, -1):setNumInputDims(2) self.net = nn.Sequential() self.net:add(self.view_in) self.net:add(module) self.net:add(self.view_out) end function layer:updateOutput(input) local N, T = input:size(1), input:size(2) self.view_in:resetSize(N * T, -1) self.view_out:resetSize(N, T, -1) self.output = self.net:forward(input) return self.output end function layer:updateGradInput(input, gradOutput) self.gradInput = self.net:updateGradInput(input, gradOutput) return self.gradInput end function layer:training() self.net:training() parent.training(self) end function layer:evaluate() self.net:evaluate() parent.evaluate(self) end function layer:parameters() return self.net:parameters() end function layer:accGradParameters(input, gradOutput, scale) return self.net:accGradParameters(input, gradOutput, scale) end function layer:backward(input, gradOutput, scale) return self.net:backward(input, gradOutput, scale) end function layer:zeroGradParameters() return self.net:zeroGradParameters() end function layer:updateParameters(learningRate) return self.net:updateParameters(learningRate) end function layer:accUpdateGradParameters(input, gradOutput, learningRate) return self.net:accUpdateGradParameters(input, gradOutput, learningRate) end
Fix TemporalAdapter
Fix TemporalAdapter
Lua
mit
antihutka/torch-rnn
dcb8215a3f89d2d3c3acb4e6e923568a2b71db55
frontend/version.lua
frontend/version.lua
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") year = tonumber(year) month = tonumber(month) point = tonumber(point) revision = tonumber(revision) local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 1000000 + (point or 0) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see getNormalizedVersion function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end --- Returns current version of KOReader, in short form. -- @treturn string version, without the git details (i.e., at most YYYY.MM.P-R) function Version:getShortVersion() if not self.short then local rev = self:getCurrentRevision() local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") self.short = year .. "." .. month if point then self.short = self.short .. "." .. point end if revision then self.short = self.short .. "-" .. revision end end return self.short end return Version
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read() rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") year = tonumber(year) month = tonumber(month) point = tonumber(point) revision = tonumber(revision) local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 1000000 + (point or 0) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see getNormalizedVersion function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end --- Returns current version of KOReader, in short form. -- @treturn string version, without the git details (i.e., at most YYYY.MM.P-R) function Version:getShortVersion() if not self.short then local rev = self:getCurrentRevision() local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") self.short = year .. "." .. month if point and point ~= "" then self.short = self.short .. "." .. point end if revision and revision ~= "" then self.short = self.short .. "-" .. revision end end return self.short end return Version
Fix point release and revision detection in Version:getShortVersion (#6693)
Fix point release and revision detection in Version:getShortVersion (#6693)
Lua
agpl-3.0
Hzj-jie/koreader,koreader/koreader,mwoz123/koreader,pazos/koreader,Markismus/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,NiLuJe/koreader
d41336cb488f558a7c8086813d8b284ac6cf46bb
Resources/Scripts/Modes/Xsera/MainMenu.lua
Resources/Scripts/Modes/Xsera/MainMenu.lua
import('GlobalVars') -- main menu script lastTime = 0 ships = {} math.randomseed(os.time()) math.random() if (math.random() < 0.5) then -- allied ships going to war allies = true shipVelocity = { -340, 70 } shipType = { "Human/Gunship", "Human/Fighter", "Human/Cruiser", "Human/Destroyer", "Human/Fighter", "Human/Gunship", "Human/AssaultTransport", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Ishiman/Gunship", "Ishiman/ResearchVessel", "Obish/Cruiser", "Ishiman/AssaultTransport", "Ishiman/Engineer", "Human/AssaultTransport", "Elejeetian/Cruiser", "Human/GateShip", "Human/Destroyer", "Ishiman/Transport", "Human/Carrier", "Ishiman/Carrier", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Ishiman/Fighter", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Human/Cruiser", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/AssaultTransport" } numShips = 150 else -- oppressive axis ships invading shipVelocity = { 340, -70 } allies = false shipType = { "Gaitori/Gunship", "Gaitori/Fighter", "Gaitori/Cruiser", "Gaitori/Destroyer", "Gaitori/Fighter", "Gaitori/Gunship", "Gaitori/AssaultTransport", "Cantharan/Fighter", "Cantharan/HeavyCruiser", "Cantharan/Gunship", "Cantharan/Drone", "Cantharan/HeavyCruiser", "Cantharan/AssaultTransport", "Cantharan/Engineer", "Audemedon/Cruiser", "Cantharan/Engineer", "Audemedon/Destroyer", "Cantharan/Transport", "Salrilian/Carrier", "Audemedon/Carrier", "Cantharan/Fighter", "Cantharan/HeavyCruiser", "Salrilian/Fighter", "Gaitori/Fighter", "Cantharan/HeavyDestroyer", "Salrilian/Destroyer", "Cantharan/Fighter", "Cantharan/Fighter", "Salrilian/Fighter", "Audemedon/Fighter", "Audemedon/Fighter", "Cantharan/Fighter", "Cantharan/Schooner", "Salrilian/Fighter", "Salrilian/Fighter", "Salrilian/Fighter", "Salrilian/AssaultTransport" } numShips = 50 end versionInformation = "" timeFactor = 1.0 sizeFactor = 1.0 function SortShips () table.sort(ships, function (a, b) return a[4] < b[4] end) -- print "Sorted ships!" end function ShipSpeed ( type ) local sz = graphics.sprite_dimensions("Ships/" .. type) local szt = math.sqrt(sz.x*sz.x + sz.y*sz.y) return 45.0 / szt end function RandomShipType () return shipType[math.random(1, #shipType)] end for i=1,numShips do local shipType = RandomShipType() if allies then ships[i] = { RandomReal(700, 1000), RandomReal(-580, 20), shipType, RandomReal(-1, 1), ShipSpeed(shipType) } else ships[i] = { RandomReal(-700, -1000), RandomReal(580, -20), shipType, RandomReal(-1, 1), ShipSpeed(shipType) } end end SortShips() function DistanceFactor ( distance ) distance = distance + 1.3 return distance / 1.4 end function render () graphics.begin_frame() graphics.set_camera(-500, -240, 500, 240) graphics.draw_image("Bootloader/Xsera", { x = 0, y = 0 }, { x = 1000, y = 480 }) for id, ship in ipairs(ships) do local sz = graphics.sprite_dimensions("Ships/" .. ship[3], goodSpriteSheetX, goodSpriteSheetY) graphics.draw_sprite("Ships/" .. ship[3], { x = ship[1], y = ship[2] }, { x = sz.x * sizeFactor * DistanceFactor(ship[4]), y = sz.y * sizeFactor * DistanceFactor(ship[4])}, math.atan2(shipVelocity[2], shipVelocity[1])) end graphics.draw_text("D - Demo", MAIN_FONT, "left", { x = -450, y = 0 }, 60) graphics.draw_text("T - Test", MAIN_FONT, "left", { x = -450, y = -50 }, 60) graphics.draw_text("C - Xsera/Credits", MAIN_FONT, "left", { x = -450, y = -100 }, 60) graphics.draw_text(versionInformation, MAIN_FONT, "left", { x = -450, y = -220 }, 28) graphics.draw_text("Level selected: " .. demoLevel .. " (" .. gameData["Scenarios"][demoLevel].name ..")", MAIN_FONT, "right", { x = 450, y = 220 }, 60) graphics.end_frame() end function key ( k ) if k == "i" then timeFactor = timeFactor + 0.05 elseif k == "u" then timeFactor = timeFactor - 0.05 elseif k == "l" then sizeFactor = sizeFactor + 0.1 elseif k == "k" then sizeFactor = sizeFactor - 0.1 elseif k == "d" then mode_manager.switch("Demo4") elseif k == "x" then if RELEASE_BUILD == false then mode_manager.switch("Xsera/ConsoleDrawer") else mode_manager.switch("Ares/Splash") end elseif k == "t" then mode_manager.switch("../Tests/TurretTest") elseif k == "c" then mode_manager.switch("Xsera/Credits") elseif k == "tab" then mode_manager.switch("Ares/Splash") elseif k == "escape" then os.exit() elseif k == "1" then mode_manager.switch("../Tests/CSTest") elseif k == "2" then print("CALLING SPECIAL SWITCH") tabl = { "THIS", "IS", "XSERAAAAAAAAAAAAA" } mode_manager.switch("../Tests/CSTest", tabl) elseif k == "3" then mode_manager.switch("../Tests/WindowTest") elseif k == "4" then mode_manager.switch("../Tests/TextTests") else print("Uninterpreted keystroke " .. k) end end function update () newTime = mode_manager.time() local dt = newTime - lastTime lastTime = newTime dt = dt * timeFactor local gvx = shipVelocity[1] local gvy = shipVelocity[2] -- print("Advancing simulation with timestep " .. dt .. " and velocity vector " .. gvx .. ", " .. gvy) local resortShips = false for ship in pairs(ships) do ships[ship][1] = ships[ship][1] + (shipVelocity[1] * DistanceFactor(ships[ship][4]) * ships[ship][5]) * dt ships[ship][2] = ships[ship][2] + (shipVelocity[2] * DistanceFactor(ships[ship][4]) * ships[ship][5]) * dt if (ships[ship][1] < -800 or ships[ship][1] > 800) then resortShips = true if allies then ships[ship][1] = RandomReal(520, 800) ships[ship][2] = RandomReal(-450, 190) else ships[ship][1] = RandomReal(-520, -800) ships[ship][2] = RandomReal(450, -190) end ships[ship][3] = RandomShipType() ships[ship][4] = RandomReal(-1, 1) end end if resortShips then SortShips() end end function init () local xmlData = xml.load("Config/Version.xml") local versionData = xmlData[1] versionInformation = "Xsera " .. versionData[1][1] .. " <" .. versionData[2][1] .. ">" print(versionInformation) if versionData.n == 3 then print("Signed off by: " .. versionData[3][1]) end lastTime = mode_manager.time() if sound.current_music() ~= "Doomtroopers" then sound.play_music("Doomtroopers") end end
import('GlobalVars') -- main menu script lastTime = 0 ships = {} math.randomseed(os.time()) math.random() if (math.random() < 0.5) then -- allied ships going to war allies = true shipVelocity = { -340, 70 } shipType = { "Human/Gunship", "Human/Fighter", "Human/Cruiser", "Human/Destroyer", "Human/Fighter", "Human/Gunship", "Human/AssaultTransport", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Ishiman/Gunship", "Ishiman/ResearchVessel", "Obish/Cruiser", "Ishiman/AssaultTransport", "Ishiman/Engineer", "Human/AssaultTransport", "Elejeetian/Cruiser", "Human/GateShip", "Human/Destroyer", "Ishiman/Transport", "Human/Carrier", "Ishiman/Carrier", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Ishiman/Fighter", "Ishiman/Fighter", "Ishiman/HeavyCruiser", "Human/Cruiser", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/Fighter", "Human/AssaultTransport" } numShips = 150 else -- oppressive axis ships invading shipVelocity = { 340, -70 } allies = false shipType = { "Gaitori/Gunship", "Gaitori/Fighter", "Gaitori/Cruiser", "Gaitori/Destroyer", "Gaitori/Fighter", "Gaitori/Gunship", "Gaitori/AssaultTransport", "Cantharan/Fighter", "Cantharan/HeavyCruiser", "Cantharan/Gunship", "Cantharan/Drone", "Cantharan/HeavyCruiser", "Cantharan/AssaultTransport", "Cantharan/Engineer", "Audemedon/Cruiser", "Cantharan/Engineer", "Audemedon/Destroyer", "Cantharan/Transport", "Salrilian/Carrier", "Audemedon/Carrier", "Cantharan/Fighter", "Cantharan/HeavyCruiser", "Salrilian/Fighter", "Gaitori/Fighter", "Cantharan/HeavyDestroyer", "Salrilian/Destroyer", "Cantharan/Fighter", "Cantharan/Fighter", "Salrilian/Fighter", "Audemedon/Fighter", "Audemedon/Fighter", "Cantharan/Fighter", "Cantharan/Schooner", "Salrilian/Fighter", "Salrilian/Fighter", "Salrilian/Fighter", "Salrilian/AssaultTransport" } numShips = 50 end versionInformation = "" timeFactor = 1.0 sizeFactor = 1.0 function SortShips () table.sort(ships, function (a, b) return a[4] < b[4] end) -- print "Sorted ships!" end function ShipSpeed ( type ) local sz = graphics.sprite_dimensions("Ships/" .. type) local szt = math.sqrt(sz.x*sz.x + sz.y*sz.y) return 45.0 / szt end function RandomShipType () return shipType[math.random(1, #shipType)] end for i=1,numShips do local shipType = RandomShipType() if allies then ships[i] = { RandomReal(700, 1000), RandomReal(-580, 20), shipType, RandomReal(-1, 1), ShipSpeed(shipType) } else ships[i] = { RandomReal(-700, -1000), RandomReal(580, -20), shipType, RandomReal(-1, 1), ShipSpeed(shipType) } end end SortShips() function DistanceFactor ( distance ) distance = distance + 1.3 return distance / 1.4 end function render () graphics.begin_frame() graphics.set_camera(-500, -240, 500, 240) graphics.draw_image("Bootloader/Xsera", { x = 0, y = 0 }, { x = 1000, y = 480 }) for id, ship in ipairs(ships) do local sz = graphics.sprite_dimensions("Ships/" .. ship[3], goodSpriteSheetX, goodSpriteSheetY) graphics.draw_sprite("Ships/" .. ship[3], { x = ship[1], y = ship[2] }, { x = sz.x * sizeFactor * DistanceFactor(ship[4]), y = sz.y * sizeFactor * DistanceFactor(ship[4])}, math.atan2(shipVelocity[2], shipVelocity[1])) end graphics.draw_text("D - Demo", MAIN_FONT, "left", { x = -450, y = 0 }, 60) graphics.draw_text("T - Test", MAIN_FONT, "left", { x = -450, y = -50 }, 60) graphics.draw_text("C - Credits", MAIN_FONT, "left", { x = -450, y = -100 }, 60) graphics.draw_text(versionInformation, MAIN_FONT, "left", { x = -450, y = -220 }, 28) graphics.draw_text("Level selected: " .. demoLevel .. " (" .. gameData["Scenarios"][demoLevel].name ..")", MAIN_FONT, "right", { x = 450, y = 220 }, 60) graphics.end_frame() end function key ( k ) if RELEASE_BUILD == true then if k == "x" then mode_manager.switch("Ares/Splash") end else -- debug build utilities / tests if k == "x" then mode_manager.switch("Xsera/ConsoleDrawer") elseif k == "t" then mode_manager.switch("../Tests/TurretTest") elseif k == "1" then mode_manager.switch("../Tests/CSTest") elseif k == "2" then -- this does not work. [ALISTAIR] You said you thought of a different way to do this? print("CALLING SPECIAL SWITCH") tabl = { "THIS", "IS", "XSERAAAAAAAAAAAAA" } mode_manager.switch("../Tests/CSTest", tabl) elseif k == "3" then mode_manager.switch("../Tests/WindowTest") elseif k == "4" then mode_manager.switch("../Tests/TextTests") end end if k == "i" then timeFactor = timeFactor + 0.05 elseif k == "u" then timeFactor = timeFactor - 0.05 elseif k == "l" then sizeFactor = sizeFactor + 0.1 elseif k == "k" then sizeFactor = sizeFactor - 0.1 elseif k == "d" then mode_manager.switch("Demo4") elseif k == "c" then mode_manager.switch("Xsera/Credits") elseif k == "tab" then mode_manager.switch("Ares/Splash") elseif k == "escape" then os.exit() else print("Uninterpreted keystroke " .. k) end end function update () newTime = mode_manager.time() local dt = newTime - lastTime lastTime = newTime dt = dt * timeFactor local gvx = shipVelocity[1] local gvy = shipVelocity[2] -- print("Advancing simulation with timestep " .. dt .. " and velocity vector " .. gvx .. ", " .. gvy) local resortShips = false for ship in pairs(ships) do ships[ship][1] = ships[ship][1] + (shipVelocity[1] * DistanceFactor(ships[ship][4]) * ships[ship][5]) * dt ships[ship][2] = ships[ship][2] + (shipVelocity[2] * DistanceFactor(ships[ship][4]) * ships[ship][5]) * dt if (ships[ship][1] < -800 or ships[ship][1] > 800) then resortShips = true if allies then ships[ship][1] = RandomReal(520, 800) ships[ship][2] = RandomReal(-450, 190) else ships[ship][1] = RandomReal(-520, -800) ships[ship][2] = RandomReal(450, -190) end ships[ship][3] = RandomShipType() ships[ship][4] = RandomReal(-1, 1) end end if resortShips then SortShips() end end function init () local xmlData = xml.load("Config/Version.xml") local versionData = xmlData[1] versionInformation = "Xsera " .. versionData[1][1] .. " <" .. versionData[2][1] .. ">" print(versionInformation) if versionData.n == 3 then print("Signed off by: " .. versionData[3][1]) end lastTime = mode_manager.time() print(sound.current_music()) if sound.current_music() ~= "Doomtroopers" then sound.play_music("Doomtroopers") end end
Fixed up the main menu key control system.
Fixed up the main menu key control system. Signed-off-by: Adam Hintz <96c833980ca266d81f358ac8bd40898278f74af6@gmail.com>
Lua
mit
adam000/xsera,adam000/xsera,prophile/xsera,prophile/xsera,prophile/xsera,prophile/xsera,adam000/xsera,adam000/xsera,prophile/xsera
39b5fd1bf37b217c9082ac2db0621e4a01736e37
Examples/smplayer-debian-sandbox.cfg.lua
Examples/smplayer-debian-sandbox.cfg.lua
-- example config for smplayer sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua -- using debian-sandbox.cfg.lua config file as base -- opengl acceleration should work with opensurce mesa drivers, tested on Intel HD graphics. -- for proprietary NVIDIA and AMD drivers it may be neccesary to forward it's libgl (and x11 drivers) from host system to sandbox: -- you can write mount rules for this (see mounts section), or simply copy all files neccesary into external debian chroot -- this config is based on example.cfg.lua, most comments removed. -- redefine some parameters tunables.datadir=loader.path.combine(loader.workdir,"userdata-mpv") defaults.recalculate() -- load base config dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua")) -- remove some unneded features and mounts loader.table.remove_value(sandbox.features,"dbus") loader.table.remove_value(sandbox.features,"gvfs_fix") -- remove some mounts loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.resolvconf_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount) -- modify PATH env table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"}) -- add host mounts, readonly table.insert(sandbox.setup.mounts,{prio=99,"ro-bind","/mnt/data","/mnt/data"}) table.insert(sandbox.setup.mounts,{prio=99,"ro-bind","/mnt/nas","/mnt/nas"}) -- add bwrap unshare-net option to cut off sandbox from network table.insert(sandbox.bwrap,defaults.bwrap.unshare_net) print(loader.lua_version.num) smplayer_log={ exec="/usr/bin/smplayer", path="/home/sandboxer", term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, -- for now it is needed for logging to work log_stderr=loader.path.combine(loader.workdir,"smplayer_dbg.err.log"), log_stdout=loader.path.combine(loader.workdir,"smplayer_dbg.out.log"), } smplayer={ exec="/usr/bin/smplayer", path="/home/sandboxer", args=loader.args, term_signal=defaults.signals.SIGTERM, attach=false, pty=false, desktop={ name = "SMPlayer (in sandbox)", comment = "SMPlayer, sandbox uid "..config.sandbox_uid, field_code="%U", icon = loader.path.combine(tunables.chrootdir,"usr","share","pixmaps","smplayer.xpm"), mimetype = "audio/ac3;audio/mp4;audio/mpeg;audio/vnd.rn-realaudio;audio/vorbis;audio/x-adpcm;audio/x-matroska;audio/x-mp2;audio/x-mp3;audio/x-ms-wma;audio/x-vorbis;audio/x-wav;audio/mpegurl;audio/x-mpegurl;audio/x-pn-realaudio;audio/x-scpls;audio/aac;audio/flac;audio/ogg;video/avi;video/mp4;video/flv;video/mpeg;video/quicktime;video/vnd.rn-realvideo;video/x-matroska;video/x-ms-asf;video/x-msvideo;video/x-ms-wmv;video/x-ogm;video/x-theora;video/webm;", terminal = false, startupnotify = false, categories="Qt;AudioVideo;Video;Player;" }, }
-- example config for smplayer sandbox, which is created on top of external debian chroot, prepared by debian-setup.cfg.lua -- using debian-sandbox.cfg.lua config file as base -- opengl acceleration should work with opensurce mesa drivers, tested on Intel HD graphics. -- for proprietary NVIDIA and AMD drivers it may be neccesary to forward it's libgl (and x11 drivers) from host system to sandbox: -- you can write mount rules for this (see mounts section), or simply copy all files neccesary into external debian chroot -- this config is based on example.cfg.lua, most comments removed. -- redefine some parameters tunables.datadir=loader.path.combine(loader.workdir,"userdata-mpv") defaults.recalculate() -- load base config dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua")) -- remove some unneded features and mounts loader.table.remove_value(sandbox.features,"dbus") loader.table.remove_value(sandbox.features,"gvfs_fix") -- remove some mounts loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.resolvconf_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount) -- modify PATH env table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"}) -- add host mounts, readonly table.insert(sandbox.setup.mounts,{prio=99,"ro-bind","/mnt/data","/mnt/data"}) table.insert(sandbox.setup.mounts,{prio=99,"ro-bind","/mnt/nas","/mnt/nas"}) -- add bwrap unshare-net option to cut off sandbox from network table.insert(sandbox.bwrap,defaults.bwrap.unshare_net) smplayer_log={ exec="/usr/bin/smplayer", path="/home/sandboxer", term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, -- for now it is needed for logging to work log_stderr=loader.path.combine(loader.workdir,"smplayer_dbg.err.log"), log_stdout=loader.path.combine(loader.workdir,"smplayer_dbg.out.log"), } smplayer={ exec="/usr/bin/smplayer", path="/home/sandboxer", args=loader.args, term_signal=defaults.signals.SIGTERM, attach=false, pty=false, desktop={ name = "SMPlayer (in sandbox)", comment = "SMPlayer, sandbox uid "..config.sandbox_uid, field_code="%U", icon = loader.path.combine(tunables.chrootdir,"usr","share","pixmaps","smplayer.xpm"), mimetype = "audio/ac3;audio/mp4;audio/mpeg;audio/vnd.rn-realaudio;audio/vorbis;audio/x-adpcm;audio/x-matroska;audio/x-mp2;audio/x-mp3;audio/x-ms-wma;audio/x-vorbis;audio/x-wav;audio/mpegurl;audio/x-mpegurl;audio/x-pn-realaudio;audio/x-scpls;audio/aac;audio/flac;audio/ogg;video/avi;video/mp4;video/flv;video/mpeg;video/quicktime;video/vnd.rn-realvideo;video/x-matroska;video/x-ms-asf;video/x-msvideo;video/x-ms-wmv;video/x-ogm;video/x-theora;video/webm;", terminal = false, startupnotify = false, categories="Qt;AudioVideo;Video;Player;" }, }
fixup! Examples: rework and simplify smplayer-debian-sandbox.cfg.lua
fixup! Examples: rework and simplify smplayer-debian-sandbox.cfg.lua
Lua
mit
DarkCaster/Sandboxer,DarkCaster/Sandboxer
e0fe1a08c573cb82e3d950ba6c0cbe321f528b04
mods/stairs/init.lua
mods/stairs/init.lua
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called stairs:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description) minetest.register_node("stairs:stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, }) minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called stairs:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description) minetest.register_node("stairs:slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) local n1 = minetest.env:get_node(p1) if n0.name == "stairs:slab_" .. subname then slabpos = p0 slabnode = n0 elseif n1.name == "stairs:slab_" .. subname then slabpos = p1 slabnode = n1 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_craft({ output = 'stairs:slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called stairs:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab) stairs.register_stair(subname, recipeitem, groups, images, desc_stair) stairs.register_slab(subname, recipeitem, groups, images, desc_slab) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab") stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab") stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab") stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab") stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab")
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. stairs = {} -- Node will be called stairs:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description) minetest.register_node("stairs:stair_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = true, groups = groups, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, }) minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {recipeitem, "", ""}, {recipeitem, recipeitem, ""}, {recipeitem, recipeitem, recipeitem}, }, }) -- Flipped recipe for the silly minecrafters minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 4', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) end -- Node will be called stairs:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description) minetest.register_node("stairs:slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", is_ground_content = true, groups = groups, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end -- If it's being placed on an another similar one, replace it with -- a full block local slabpos = nil local slabnode = nil local p0 = pointed_thing.under local p1 = pointed_thing.above local n0 = minetest.env:get_node(p0) if n0.name == "stairs:slab_" .. subname and p0.y+1 == p1.y then slabpos = p0 slabnode = n0 end if slabpos then -- Remove the slab at slabpos minetest.env:remove_node(slabpos) -- Make a fake stack of a single item and try to place it local fakestack = ItemStack(recipeitem) pointed_thing.above = slabpos fakestack = minetest.item_place(fakestack, placer, pointed_thing) -- If the item was taken from the fake stack, decrement original if not fakestack or fakestack:is_empty() then itemstack:take_item(1) -- Else put old node back else minetest.env:set_node(slabpos, slabnode) end return itemstack end -- Otherwise place regularly return minetest.item_place(itemstack, placer, pointed_thing) end, }) minetest.register_craft({ output = 'stairs:slab_' .. subname .. ' 3', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) end -- Nodes will be called stairs:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab) stairs.register_stair(subname, recipeitem, groups, images, desc_stair) stairs.register_slab(subname, recipeitem, groups, images, desc_slab) end stairs.register_stair_and_slab("wood", "default:wood", {snappy=2,choppy=2,oddly_breakable_by_hand=2}, {"default_wood.png"}, "Wooden stair", "Wooden slab") stairs.register_stair_and_slab("stone", "default:stone", {cracky=3}, {"default_stone.png"}, "Stone stair", "Stone slab") stairs.register_stair_and_slab("cobble", "default:cobble", {cracky=3}, {"default_cobble.png"}, "Cobble stair", "Cobble slab") stairs.register_stair_and_slab("brick", "default:brick", {cracky=3}, {"default_brick.png"}, "Brick stair", "Brick slab") stairs.register_stair_and_slab("sandstone", "default:sandstone", {crumbly=2,cracky=2}, {"default_sandstone.png"}, "Sandstone stair", "Sandstone slab")
Fix slab -> full block transformation
Fix slab -> full block transformation
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
072680c9077bfbdce48155435ebbb61e155a9f01
OS/DiskOS/Runtime/Globals/04_GameAPI.lua
OS/DiskOS/Runtime/Globals/04_GameAPI.lua
--Games special API loader local term = require("terminal") local MainDrive = term.getMainDrive() local Globals = (...) or {} local sw,sh = screenSize() function Globals.pause() if Globals._DISABLE_PAUSE then return end pushMatrix() pushPalette() pushColor() palt() pal() colorPalette() cam() local oldClip = clip() local bkimg = screenshot():image() local scimg = screenshot(sw/8,sh/8, sw*0.75,sh*0.75) ImageUtils.darken(scimg,2) scimg = scimg:image() palt(0,false) scimg:draw(sw/8,sh/8) rect(sw/8,sh/8,sw*0.75,sh*0.75, true, 0) --Black rect(sw/8+1,sh/8+1,sw*0.75-2,sh*0.75-2, true, 7) --White rect(sw/8+2,sh/8+2,sw*0.75-4,sh*0.75-4, true, 0) --Black color(7) print("GAME IS PAUSED",0,sh*0.4, sw, "center") print("Press escape/return to resume",sw*0.175,sh*0.6, sw*0.65, "center") clearEStack() for event, a,b,c,d,e,f in pullEvent do if event == "keypressed" then if a == "escape" or a == "return" then break end end end bkimg:draw(0,0) if oldClip then clip(unpack(oldClip)) end popColor() popPalette() popMatrix() end local pkeys = {} --Pressed keys local rkeys = {} --Repeated keys local dkeys = {} --Down keys local tbtn = {false,false,false,false,false,false,false} --Touch buttons local gpads = {} --Gamepads local defaultbmap = { {"left","right","up","down","z","x","c"}, --Player 1 {"s","f","e","d","tab","q","w"} --Player 2 } local mobilebnames = { "Left","Right","Up","Down","Green button","Red button","Blue button" } do --So I can hide this part in ZeroBran studio local bmap = ConfigUtils.get("GamesKeymap") if not bmap[1] then bmap[1] = {unpack(defaultbmap[1])} ConfigUtils.saveConfig() end if not bmap[2] then bmap[2] = {unpack(defaultbmap[2])} ConfigUtils.saveConfig() end function Globals.getBtnName(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end if isMobile() and p == 1 then return mobilebnames[n] else local map = bmap[p] local bname = map[n] return string.upper(string.sub(bname,1,1))..string.sub(bname,2,-1) end end function Globals.btn(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller return dkeys[map[n]] or (p == 1 and tbtn[n]) or (gmap and gmap[n]) end function Globals.btnp(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller if rkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] >= 1) or (gmap and gmap[n] and gmap[n] >= 1) then return true, true else return pkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] == 0) or (gmap and gmap[n] and gmap[n] == 0) end end Globals.__BTNUpdate = function(dt) pkeys = {} --Reset the table (easiest way) rkeys = {} --Reset the table (easiest way) for k,v in pairs(dkeys) do if not isKDown(k) then dkeys[k] = nil end end for k,v in ipairs(tbtn) do if v then if tbtn[k] >= 1 then tbtn[k] = 0.9 end tbtn[k] = tbtn[k] + dt end end for id, gpad in pairs(gpads) do for k,v in ipairs(gpad) do if v then if gpad[k] >= 1 then gpad[k] = 0.9 end gpad[k] = gpad[k] + dt end end end end Globals.__BTNKeypressed = function(a,b) pkeys[a] = true rkeys[a] = b dkeys[a] = true end Globals.__BTNTouchControl = function(state,n) if state then tbtn[n] = 0 else tbtn[n] = false end end Globals.__BTNGamepad = function(state,n,id) if not gpads[id] then gpads[id] = {false,false,false,false,false,false} end if state then gpads[id][n] = 0 else gpads[id][n] = false end end end --Persistent data API local GameSaveID local GameSaveData local GameSaveSize = 1024*2 --2KB if not fs.exists(MainDrive..":/GamesData") then fs.newDirectory(MainDrive..":/GamesData") end function Globals.SaveID(name) if type(name) ~= "string" then return error("SaveID should be a string, provided: "..type(name)) end if GameSaveID then return error("SaveID could be only set once !") end GameSaveID, GameSaveData = name, "" if fs.exists(string.format(MainDrive..":/GamesData/%s.bin",GameSaveID)) then GameSaveData = fs.read(string.format(MainDrive..":/GamesData/%s.bin",GameSaveID), GameSaveSize) end end function Globals.SaveData(data) if type(data) ~= "string" then return error("Save data should be a string, provided: "..type(data)) end if #data > GameSaveSize then return error("Save data can be 2KB maximum !") end if not GameSaveID then return error("Set SaveID inorder to save data !") end --Write the game data fs.write(string.format(MainDrive..":/GamesData/%s.bin",GameSaveID), data, GameSaveSize) end function Globals.LoadData() if not GameSaveID then return error("Set SaveID inorder to load data !") end return GameSaveData end --Helpers local helpersloader, err = fs.load(MainDrive..":/Libraries/diskHelpers.lua") if not helpersloader then error(err) end setfenv(helpersloader,Globals) helpersloader() return Globals
--Games special API loader local term = require("terminal") local MainDrive = term.getMainDrive() local Globals = (...) or {} local sw,sh = screenSize() function Globals.pause() if Globals._DISABLE_PAUSE then return end pushMatrix() pushPalette() pushColor() palt() pal() colorPalette() cam() local oldClip = clip() local bkimg = screenshot():image() local scimg = screenshot(sw/8,sh/8, sw*0.75,sh*0.75) ImageUtils.darken(scimg,2) scimg = scimg:image() palt(0,false) scimg:draw(sw/8,sh/8) rect(sw/8,sh/8,sw*0.75,sh*0.75, true, 0) --Black rect(sw/8+1,sh/8+1,sw*0.75-2,sh*0.75-2, true, 7) --White rect(sw/8+2,sh/8+2,sw*0.75-4,sh*0.75-4, true, 0) --Black color(7) print("GAME IS PAUSED",0,sh*0.4, sw, "center") print("Press escape/return to resume",sw*0.175,sh*0.6, sw*0.65, "center") clearEStack() for event, a,b,c,d,e,f in pullEvent do if event == "keypressed" then if a == "escape" or a == "return" then break end end end bkimg:draw(0,0) if oldClip then clip(unpack(oldClip)) end popColor() popPalette() popMatrix() end local pkeys = {} --Pressed keys local rkeys = {} --Repeated keys local dkeys = {} --Down keys local tbtn = {false,false,false,false,false,false,false} --Touch buttons local gpads = {} --Gamepads local defaultbmap = { {"left","right","up","down","z","x","c"}, --Player 1 {"s","f","e","d","tab","q","w"} --Player 2 } local mobilebnames = { "Left","Right","Up","Down","Green button","Red button","Blue button" } do --So I can hide this part in ZeroBran studio local bmap = ConfigUtils.get("GamesKeymap") if not bmap[1] then bmap[1] = {unpack(defaultbmap[1])} ConfigUtils.saveConfig() end if not bmap[2] then bmap[2] = {unpack(defaultbmap[2])} ConfigUtils.saveConfig() end function Globals.getBtnName(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end if isMobile() and p == 1 then return mobilebnames[n] else local map = bmap[p] local bname = map[n] return string.upper(string.sub(bname,1,1))..string.sub(bname,2,-1) end end function Globals.btn(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller return dkeys[map[n]] or (p == 1 and tbtn[n]) or (gmap and gmap[n]) end function Globals.btnp(n,p) local p = p or 1 if type(n) ~= "number" then return error("Button id must be a number, provided: "..type(n)) end if type(p) ~= "number" then return error("Player id must be a number or nil, provided: "..type(p)) end n, p = math.floor(n), math.floor(p) if p < 1 then return error("The Player id is negative ("..p..") it must be positive !") end if n < 1 or n > 7 then return error("The Button id is out of range ("..n..") must be [1,7]") end local map = bmap[p] local gmap = gpads[p] if not (map or gmap) then return false end --Failed to find a controller if rkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] >= 1) or (gmap and gmap[n] and gmap[n] >= 1) then return true, true else return pkeys[map[n]] or (p == 1 and tbtn[n] and tbtn[n] == 0) or (gmap and gmap[n] and gmap[n] == 0) end end Globals.__BTNUpdate = function(dt) pkeys = {} --Reset the table (easiest way) rkeys = {} --Reset the table (easiest way) for k,v in pairs(dkeys) do if not isKDown(k) then dkeys[k] = nil end end for k,v in ipairs(tbtn) do if v then if tbtn[k] >= 1 then tbtn[k] = 0.9 end tbtn[k] = tbtn[k] + dt end end for id, gpad in pairs(gpads) do for k,v in ipairs(gpad) do if v then if gpad[k] >= 1 then gpad[k] = 0.9 end gpad[k] = gpad[k] + dt end end end end Globals.__BTNKeypressed = function(a,b) pkeys[a] = true rkeys[a] = b dkeys[a] = true end Globals.__BTNTouchControl = function(state,n) if state then tbtn[n] = 0 else tbtn[n] = false end end Globals.__BTNGamepad = function(state,n,id) if not gpads[id] then gpads[id] = {false,false,false,false,false,false} end if state then gpads[id][n] = 0 else gpads[id][n] = false end end end --Persistent data API local GameSaveID local GameSaveData local GameSaveSize = 1024*2 --2KB if not fs.exists(MainDrive..":/GamesData") then fs.newDirectory(MainDrive..":/GamesData") end function Globals.SaveID(name) if type(name) ~= "string" then return error("SaveID should be a string, provided: "..type(name)) end if GameSaveID then return error("SaveID could be only set once !") end GameSaveID, GameSaveData = name, "" if fs.exists(MainDrive..":/GamesData/"..GameSaveID..".bin") then GameSaveData = fs.read(MainDrive..":/GamesData/"..GameSaveID..".bin"), GameSaveSize) end end function Globals.SaveData(data) if type(data) ~= "string" then return error("Save data should be a string, provided: "..type(data)) end if #data > GameSaveSize then return error("Save data can be 2KB maximum !") end if not GameSaveID then return error("Set SaveID inorder to save data !") end GameSaveData = data --Write the game data fs.write(string.format(MainDrive..":/GamesData/%s.bin",GameSaveID), GameSaveData) end function Globals.LoadData() if not GameSaveID then return error("Set SaveID inorder to load data !") end return GameSaveData end --Helpers local helpersloader, err = fs.load(MainDrive..":/Libraries/diskHelpers.lua") if not helpersloader then error(err) end setfenv(helpersloader,Globals) helpersloader() return Globals
Fix gamedata saving
Fix gamedata saving Former-commit-id: 4c1a6724a48acbb313150d9d7c8a38dfdb4e9441
Lua
mit
RamiLego4Game/LIKO-12
74407312e33b1f10d9f5a472b4a79e6eb6fb8edc
extensions/tabs/init.lua
extensions/tabs/init.lua
--- === hs.tabs === --- --- Place the windows of an application into tabs drawn on its titlebar local tabs = {} local drawing = require "hs.drawing" local uielement = require "hs.uielement" local watcher = uielement.watcher local fnutils = require "hs.fnutils" local application = require "hs.application" local appwatcher = application.watcher tabs.leftPad = 10 tabs.topPad = 2 tabs.tabPad = 2 tabs.tabWidth = 80 tabs.tabHeight = 17 tabs.tabRound = 4 tabs.textLeftPad = 2 tabs.textTopPad = 2 tabs.textSize = 10 tabs.fillColor = {red = 1.0, green = 1.0, blue = 1.0, alpha = 0.5} tabs.selectedColor = {red = .9, green = .9, blue = .9, alpha = 0.5} tabs.strokeColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.7} tabs.textColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.6} tabs.maxTitle = 11 local function realWindow(win) -- AXScrollArea is weird role of special finder desktop window return (win:isStandard() and win:role() ~= "AXScrollArea") end --- hs.tabs.tabWindows(app) --- Function --- Gets a list of the tabs of a window --- --- Parameters: --- * app - An `hs.application` object --- --- Returns: --- * An array of the tabbed windows of an app in the same order as they would be tabbed --- --- Notes: --- * This function can be used when writing tab switchers function tabs.tabWindows(app) local tabWins = fnutils.filter(app:allWindows(),realWindow) table.sort(tabWins, function(a,b) return a:title() < b:title() end) return tabWins end local drawTable = {} local function trashTabs(pid) local tab = drawTable[pid] if not tab then return end for _,obj in ipairs(tab) do obj:delete() end end local function drawTabs(app) local pid = app:pid() trashTabs(pid) drawTable[pid] = {} local proto = app:focusedWindow() if not proto or not app:isFrontmost() then return end local geom = app:focusedWindow():frame() local tabWins = tabs.tabWindows(app) local pt = {x = geom.x+geom.w-tabs.leftPad, y = geom.y+tabs.topPad} local objs = drawTable[pid] -- iterate in reverse order because we draw right to left local numTabs = #tabWins for i=0,(numTabs-1) do local win = tabWins[numTabs-i] pt.x = pt.x - tabs.tabWidth - tabs.tabPad local r = drawing.rectangle({x=pt.x,y=pt.y,w=tabs.tabWidth,h=tabs.tabHeight}) r:setClickCallback(nil, function() tabs.focusTab(app, #tabs.tabWindows(app) - i) end) r:setFill(true) if win == proto then r:setFillColor(tabs.selectedColor) else r:setFillColor(tabs.fillColor) end r:setStrokeColor(tabs.strokeColor) r:setRoundedRectRadii(tabs.tabRound,tabs.tabRound) r:bringToFront() r:show() table.insert(objs,r) local tabText = win:title():sub(1,tabs.maxTitle) local t = drawing.text({x=pt.x+tabs.textLeftPad,y=pt.y+tabs.textTopPad, w=tabs.tabWidth,h=tabs.tabHeight},tabText) t:setTextSize(tabs.textSize) t:setTextColor(tabs.textColor) t:show() table.insert(objs,t) end end local function reshuffle(app) local proto = app:focusedWindow() if not proto then return end local geom = app:focusedWindow():frame() for _,win in ipairs(app:allWindows()) do if win:isStandard() then win:setFrame(geom) end end drawTabs(app) end local function manageWindow(win, app) if not win:isStandard() then return end -- only trigger on focused window movements otherwise the reshuffling triggers itself local newWatch = win:newWatcher(function(el) if el == app:focusedWindow() then reshuffle(app) end end) newWatch:start({watcher.windowMoved, watcher.windowResized, watcher.elementDestroyed}) local redrawWatch = win:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.elementDestroyed, watcher.titleChanged}) -- resize this window to match possible others local notThis = fnutils.filter(app:allWindows(), function(x) return (x ~= win and realWindow(x)) end) local protoWindow = notThis[1] if protoWindow then print("Prototyping to '" .. protoWindow:title() .. "'") win:setFrame(protoWindow:frame()) end end local function watchApp(app) -- print("Enabling tabs for " .. app:title()) for _,win in ipairs(app:allWindows()) do manageWindow(win,app) end local winWatch = app:newWatcher(function(el,_,_,appl) manageWindow(el,appl) end,app) winWatch:start({watcher.windowCreated}) local redrawWatch = app:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.applicationActivated, watcher.applicationDeactivated, watcher.applicationHidden, watcher.focusedWindowChanged}) reshuffle(app) end local appWatcherStarted = false local appWatches = {} --- hs.tabs.enableForApp(app) --- Function --- Places all the windows of an app into one place and tab them --- --- Parameters: --- * app - An `hs.application` object or the app title --- --- Returns: --- * None function tabs.enableForApp(app) if type(app) == "string" then appWatches[app] = true app = application.get(app) end -- might already be running if app then watchApp(app) end -- set up a watcher to catch any watched app launching or terminating if appWatcherStarted then return end appWatcherStarted = true local watch = appwatcher.new(function(name,event,theApp) -- print("Event from " .. name) if event == appwatcher.launched and appWatches[name] then watchApp(theApp) elseif event == appwatcher.terminated then trashTabs(theApp:pid()) end end) watch:start() end --- hs.tabs.focusTab(app, num) --- Function --- Focuses a specific tab of an app --- --- Parameters: --- * app - An `hs.application` object previously enabled for tabbing --- * num - A tab number to switch to --- --- Returns: --- * None --- --- Notes: --- * If num is higher than the number of tabs, the last tab will be focussed function tabs.focusTab(app,num) if not app or not appWatches[app:title()] then return end local theTabs = tabs.tabWindows(app) local bounded = num --print(hs.inspect(tabs)) if num > #theTabs then bounded = #theTabs end theTabs[bounded]:focus() end return tabs
--- === hs.tabs === --- --- Place the windows of an application into tabs drawn on its titlebar local tabs = {} local drawing = require "hs.drawing" local uielement = require "hs.uielement" local watcher = uielement.watcher local fnutils = require "hs.fnutils" local application = require "hs.application" local appwatcher = application.watcher tabs.leftPad = 10 tabs.topPad = 2 tabs.tabPad = 2 tabs.tabWidth = 80 tabs.tabHeight = 17 tabs.tabRound = 4 tabs.textLeftPad = 2 tabs.textTopPad = 2 tabs.textSize = 10 tabs.fillColor = {red = 1.0, green = 1.0, blue = 1.0, alpha = 0.5} tabs.selectedColor = {red = .9, green = .9, blue = .9, alpha = 0.5} tabs.strokeColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.7} tabs.textColor = {red = 0.0, green = 0.0, blue = 0.0, alpha = 0.6} tabs.maxTitle = 11 local function realWindow(win) -- AXScrollArea is weird role of special finder desktop window return (win:isStandard() and win:role() ~= "AXScrollArea") end --- hs.tabs.tabWindows(app) --- Function --- Gets a list of the tabs of a window --- --- Parameters: --- * app - An `hs.application` object --- --- Returns: --- * An array of the tabbed windows of an app in the same order as they would be tabbed --- --- Notes: --- * This function can be used when writing tab switchers function tabs.tabWindows(app) local tabWins = fnutils.filter(app:allWindows(),realWindow) table.sort(tabWins, function(a,b) return a:title() < b:title() end) return tabWins end local drawTable = {} local function trashTabs(pid) local tab = drawTable[pid] if not tab then return end for _,obj in ipairs(tab) do obj:delete() end end local function drawTabs(app) local pid = app:pid() trashTabs(pid) drawTable[pid] = {} local proto = app:focusedWindow() if not proto or not app:isFrontmost() then return end local geom = app:focusedWindow():frame() local tabWins = tabs.tabWindows(app) local pt = {x = geom.x+geom.w-tabs.leftPad, y = geom.y+tabs.topPad} local objs = drawTable[pid] -- iterate in reverse order because we draw right to left local numTabs = #tabWins for i=0,(numTabs-1) do local win = tabWins[numTabs-i] pt.x = pt.x - tabs.tabWidth - tabs.tabPad local r = drawing.rectangle({x=pt.x,y=pt.y,w=tabs.tabWidth,h=tabs.tabHeight}) r:setClickCallback(nil, function() tabs.focusTab(app, #tabs.tabWindows(app) - i) end) r:setFill(true) if win == proto then r:setFillColor(tabs.selectedColor) else r:setFillColor(tabs.fillColor) end r:setStrokeColor(tabs.strokeColor) r:setRoundedRectRadii(tabs.tabRound,tabs.tabRound) r:bringToFront() r:show() table.insert(objs,r) local tabText = win:title():sub(1,tabs.maxTitle) local t = drawing.text({x=pt.x+tabs.textLeftPad,y=pt.y+tabs.textTopPad, w=tabs.tabWidth,h=tabs.tabHeight},tabText) t:setTextSize(tabs.textSize) t:setTextColor(tabs.textColor) t:show() table.insert(objs,t) end end local function reshuffle(app) local proto = app:focusedWindow() if not proto then return end local geom = app:focusedWindow():frame() for _,win in ipairs(app:allWindows()) do if win:isStandard() then win:setFrame(geom) end end drawTabs(app) end local function manageWindow(win, app) if not win:isStandard() then return end -- only trigger on focused window movements otherwise the reshuffling triggers itself local newWatch = win:newWatcher(function(el) if el == app:focusedWindow() then reshuffle(app) end end) newWatch:start({watcher.windowMoved, watcher.windowResized, watcher.elementDestroyed}) local redrawWatch = win:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.elementDestroyed, watcher.titleChanged}) -- resize this window to match possible others local notThis = fnutils.filter(app:allWindows(), function(x) return (x ~= win and realWindow(x)) end) local protoWindow = notThis[1] if protoWindow then print("Prototyping to '" .. protoWindow:title() .. "'") win:setFrame(protoWindow:frame()) end end local function watchApp(app) -- print("Enabling tabs for " .. app:title()) for _,win in ipairs(app:allWindows()) do manageWindow(win,app) end local winWatch = app:newWatcher(function(el,_,_,appl) manageWindow(el,appl) end,app) winWatch:start({watcher.windowCreated}) local redrawWatch = app:newWatcher(function () drawTabs(app) end) redrawWatch:start({watcher.applicationActivated, watcher.applicationDeactivated, watcher.applicationHidden, watcher.focusedWindowChanged}) reshuffle(app) end local appWatcherStarted = false local appWatches = {} --- hs.tabs.enableForApp(app) --- Function --- Places all the windows of an app into one place and tab them --- --- Parameters: --- * app - An `hs.application` object or the app title --- --- Returns: --- * None function tabs.enableForApp(app) if type(app) == "string" then appWatches[app] = true app = application.get(app) end -- might already be running if app then appWatches[app:title()] = true watchApp(app) end -- set up a watcher to catch any watched app launching or terminating if appWatcherStarted then return end appWatcherStarted = true local watch = appwatcher.new(function(name,event,theApp) -- print("Event from " .. name) if event == appwatcher.launched and appWatches[name] then watchApp(theApp) elseif event == appwatcher.terminated then trashTabs(theApp:pid()) end end) watch:start() end --- hs.tabs.focusTab(app, num) --- Function --- Focuses a specific tab of an app --- --- Parameters: --- * app - An `hs.application` object previously enabled for tabbing --- * num - A tab number to switch to --- --- Returns: --- * None --- --- Notes: --- * If num is higher than the number of tabs, the last tab will be focussed function tabs.focusTab(app,num) if not app or not appWatches[app:title()] then return end local theTabs = tabs.tabWindows(app) local bounded = num --print(hs.inspect(tabs)) if num > #theTabs then bounded = #theTabs end theTabs[bounded]:focus() end return tabs
Update init.lua
Update init.lua fix code logic bug (show as when click tab / invoke tabs.focusTab, but cannot switch to app's corresponding window)
Lua
mit
latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,asmagill/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon
d7227cfd1a77981c1951a11b3da058d4429f5444
service/watchdog.lua
service/watchdog.lua
local skynet = require "skynet" local command = {} local agent_all = {} local gate = skynet.launch("gate" , skynet.self(), ...) print("gate",gate) function command:open(parm) local fd,addr = string.match(parm,"(%d+) ([^%s]+)") fd = tonumber(fd) print("agent open",self,string.format("%d %d %s",self,fd,addr)) local client = skynet.launch("client",fd) print("client",client) local agent = skynet.launch("snlua","agent",client) print("watchdog launch agent client:",agent,client) if agent then agent_all[self] = { agent , client } skynet.send(gate, "forward ".. self .. " " .. agent .. " " .. client) end end function command:close() print("agent close",self,string.format("close %d",self)) local agent = agent_all[self] agent_all[self] = nil skynet.kill(agent[1]) skynet.kill(agent[2]) end function command:data(data, session) local agent = agent_all[self] if agent then skynet.redirect(agent[1], agent[2], session, data) else skynet.error(string.format("agent data drop %d size=%d",self,#data)) end end skynet.dispatch(function(msg, sz, session, address) local message = skynet.tostring(msg,sz) local id, cmd , parm = string.match(message, "(%d+) (%w+) ?(.*)") id = tonumber(id) local f = command[cmd] if f then f(id,parm,session) else skynet.error(string.format("[watchdog] Unknown command : %s",message)) end end) skynet.register(".watchdog")
local skynet = require "skynet" local command = {} local agent_all = {} local gate = skynet.launch("gate" , skynet.self(), ...) print("gate",gate) function command:open(parm) local fd,addr = string.match(parm,"(%d+) ([^%s]+)") fd = tonumber(fd) print("agent open",self,string.format("%d %d %s",self,fd,addr)) local client = skynet.launch("client",fd) print("client",client) local agent = skynet.launch("snlua","agent",client) print("watchdog launch agent client:",agent,client) if agent then agent_all[self] = { agent , client } skynet.send(gate, "forward ".. self .. " " .. agent .. " " .. client) end end function command:close() print("agent close",self,string.format("close %d",self)) local agent = agent_all[self] agent_all[self] = nil skynet.kill(agent[1]) skynet.kill(agent[2]) end function command:data(data, session) local agent = agent_all[self] if agent then -- 0x7fffffff means it's a client skynet.redirect(agent[1], agent[2], 0x7fffffff, data) else skynet.error(string.format("agent data drop %d size=%d",self,#data)) end end skynet.dispatch(function(msg, sz, session, address) local message = skynet.tostring(msg,sz) local id, cmd , parm = string.match(message, "(%d+) (%w+) ?(.*)") id = tonumber(id) local f = command[cmd] if f then f(id,parm,session) else skynet.error(string.format("[watchdog] Unknown command : %s",message)) end end) skynet.register(".watchdog")
bugfix: watchdog forward client message to agent, set session = 0x7fffffff
bugfix: watchdog forward client message to agent, set session = 0x7fffffff
Lua
mit
ypengju/skynet_comment,xcjmine/skynet,qyli/test,zzh442856860/skynet,kyle-wang/skynet,fhaoquan/skynet,MetSystem/skynet,ruleless/skynet,LiangMa/skynet,QuiQiJingFeng/skynet,longmian/skynet,letmefly/skynet,codingabc/skynet,kyle-wang/skynet,togolwb/skynet,boyuegame/skynet,LuffyPan/skynet,pichina/skynet,cpascal/skynet,wangyi0226/skynet,boyuegame/skynet,microcai/skynet,chfg007/skynet,bingo235/skynet,matinJ/skynet,cloudwu/skynet,puXiaoyi/skynet,KittyCookie/skynet,codingabc/skynet,LiangMa/skynet,sdgdsffdsfff/skynet,korialuo/skynet,xinmingyao/skynet,firedtoad/skynet,sundream/skynet,peimin/skynet,xubigshu/skynet,korialuo/skynet,puXiaoyi/skynet,winglsh/skynet,plsytj/skynet,xinmingyao/skynet,jiuaiwo1314/skynet,bigrpg/skynet,codingabc/skynet,ludi1991/skynet,liuxuezhan/skynet,great90/skynet,zzh442856860/skynet,catinred2/skynet,yunGit/skynet,cpascal/skynet,yunGit/skynet,nightcj/mmo,wangjunwei01/skynet,lynx-seu/skynet,MRunFoss/skynet,fztcjjl/skynet,puXiaoyi/skynet,zzh442856860/skynet-Note,catinred2/skynet,chenjiansnail/skynet,qyli/test,plsytj/skynet,enulex/skynet,fhaoquan/skynet,helling34/skynet,felixdae/skynet,zhaijialong/skynet,u20024804/skynet,zhouxiaoxiaoxujian/skynet,gitfancode/skynet,MoZhonghua/skynet,iskygame/skynet,ypengju/skynet_comment,xinjuncoding/skynet,zhangshiqian1214/skynet,korialuo/skynet,QuiQiJingFeng/skynet,wangyi0226/skynet,ludi1991/skynet,cuit-zhaxin/skynet,yinjun322/skynet,cpascal/skynet,wangjunwei01/skynet,MoZhonghua/skynet,chenjiansnail/skynet,ilylia/skynet,iskygame/skynet,dymx101/skynet,pichina/skynet,kebo/skynet,vizewang/skynet,cmingjian/skynet,zhoukk/skynet,lynx-seu/skynet,enulex/skynet,samael65535/skynet,LuffyPan/skynet,Markal128/skynet,ludi1991/skynet,cdd990/skynet,LuffyPan/skynet,leezhongshan/skynet,cloudwu/skynet,pigparadise/skynet,bingo235/skynet,bttscut/skynet,ilylia/skynet,gitfancode/skynet,sdgdsffdsfff/skynet,qyli/test,xjdrew/skynet,kezhuw/skynet,firedtoad/skynet,peimin/skynet,asanosoyokaze/skynet,zzh442856860/skynet-Note,bttscut/skynet,jxlczjp77/skynet,letmefly/skynet,zhoukk/skynet,zzh442856860/skynet-Note,pigparadise/skynet,longmian/skynet,JiessieDawn/skynet,MetSystem/skynet,kebo/skynet,QuiQiJingFeng/skynet,rainfiel/skynet,zhouxiaoxiaoxujian/skynet,qyli/test,jxlczjp77/skynet,togolwb/skynet,asanosoyokaze/skynet,sdgdsffdsfff/skynet,MetSystem/skynet,plsytj/skynet,javachengwc/skynet,xcjmine/skynet,leezhongshan/skynet,winglsh/skynet,zhaijialong/skynet,lc412/skynet,bingo235/skynet,sanikoyes/skynet,MRunFoss/skynet,lawnight/skynet,nightcj/mmo,Ding8222/skynet,ag6ag/skynet,your-gatsby/skynet,cuit-zhaxin/skynet,dymx101/skynet,your-gatsby/skynet,fztcjjl/skynet,pigparadise/skynet,samael65535/skynet,cdd990/skynet,lynx-seu/skynet,peimin/skynet_v0.1_with_notes,great90/skynet,zhangshiqian1214/skynet,MRunFoss/skynet,JiessieDawn/skynet,LiangMa/skynet,jiuaiwo1314/skynet,zhoukk/skynet,xcjmine/skynet,enulex/skynet,ypengju/skynet_comment,matinJ/skynet,chuenlungwang/skynet,lc412/skynet,cloudwu/skynet,letmefly/skynet,icetoggle/skynet,fhaoquan/skynet,bigrpg/skynet,zzh442856860/skynet-Note,xinjuncoding/skynet,javachengwc/skynet,chenjiansnail/skynet,zhangshiqian1214/skynet,firedtoad/skynet,czlc/skynet,letmefly/skynet,KittyCookie/skynet,liuxuezhan/skynet,ruleless/skynet,nightcj/mmo,javachengwc/skynet,longmian/skynet,harryzeng/skynet,Markal128/skynet,KAndQ/skynet,microcai/skynet,cuit-zhaxin/skynet,rainfiel/skynet,chfg007/skynet,vizewang/skynet,peimin/skynet_v0.1_with_notes,Ding8222/skynet,pichina/skynet,gitfancode/skynet,ag6ag/skynet,felixdae/skynet,jiuaiwo1314/skynet,cmingjian/skynet,sundream/skynet,microcai/skynet,Ding8222/skynet,ruleless/skynet,JiessieDawn/skynet,chuenlungwang/skynet,your-gatsby/skynet,sanikoyes/skynet,zhouxiaoxiaoxujian/skynet,Zirpon/skynet,bigrpg/skynet,KittyCookie/skynet,kyle-wang/skynet,Zirpon/skynet,liuxuezhan/skynet,KAndQ/skynet,winglsh/skynet,hongling0/skynet,lawnight/skynet,helling34/skynet,zzh442856860/skynet,wangyi0226/skynet,catinred2/skynet,zhangshiqian1214/skynet,wangjunwei01/skynet,ag6ag/skynet,leezhongshan/skynet,sanikoyes/skynet,vizewang/skynet,Zirpon/skynet,matinJ/skynet,KAndQ/skynet,ludi1991/skynet,harryzeng/skynet,icetoggle/skynet,lc412/skynet,yunGit/skynet,dymx101/skynet,togolwb/skynet,ilylia/skynet,asanosoyokaze/skynet,hongling0/skynet,felixdae/skynet,u20024804/skynet,xjdrew/skynet,xinjuncoding/skynet,chfg007/skynet,rainfiel/skynet,czlc/skynet,jxlczjp77/skynet,liuxuezhan/skynet,boyuegame/skynet,yinjun322/skynet,u20024804/skynet,cmingjian/skynet,Markal128/skynet,chuenlungwang/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,yinjun322/skynet,xubigshu/skynet,iskygame/skynet,bttscut/skynet,samael65535/skynet,MoZhonghua/skynet,lawnight/skynet,harryzeng/skynet,helling34/skynet,zhaijialong/skynet,xjdrew/skynet,icetoggle/skynet,fztcjjl/skynet,hongling0/skynet,sundream/skynet,great90/skynet,czlc/skynet,lawnight/skynet,cdd990/skynet,kebo/skynet
29dd0cf7262545f9297317b84874a49b66fb6b31
resources/prosody-plugins/mod_limits_exception.lua
resources/prosody-plugins/mod_limits_exception.lua
-- we use async to detect Prosody 0.10 and earlier local have_async = pcall(require, 'util.async'); if not have_async then return; end local unlimited_jids = module:get_option_inherited_set("unlimited_jids", {}); -- rises the limit of the stanza size for the unlimited jids, default is 10MB local unlimited_stanza_size_limit = module:get_option_number("unlimited_size", 10*1024*1024); if unlimited_jids:empty() then return; end module:hook("authentication-success", function (event) local session = event.session; local jid = session.username .. "@" .. session.host; if unlimited_jids:contains(jid) then if session.conn and session.conn.setlimit then session.conn:setlimit(0); elseif session.throttle then session.throttle = nil; end if unlimited_stanza_size_limit then module:log('info', 'Setting stanza size limits for %s to %s', jid, unlimited_stanza_size_limit) session.stream:set_stanza_size_limit(unlimited_stanza_size_limit); end end end);
-- we use async to detect Prosody 0.10 and earlier local have_async = pcall(require, 'util.async'); if not have_async then return; end local unlimited_jids = module:get_option_inherited_set("unlimited_jids", {}); -- rises the limit of the stanza size for the unlimited jids, default is 10MB local unlimited_stanza_size_limit = module:get_option_number("unlimited_size", 10*1024*1024); if unlimited_jids:empty() then return; end module:hook("authentication-success", function (event) local session = event.session; local jid = session.username .. "@" .. session.host; if unlimited_jids:contains(jid) then if session.conn and session.conn.setlimit then session.conn:setlimit(0); elseif session.throttle then session.throttle = nil; end if unlimited_stanza_size_limit and session.stream.set_stanza_size_limit then module:log('info', 'Setting stanza size limits for %s to %s', jid, unlimited_stanza_size_limit) session.stream:set_stanza_size_limit(unlimited_stanza_size_limit); end end end);
fix: Adds a null check in mod_limits_exceptions.
fix: Adds a null check in mod_limits_exceptions. It is failing on prosody 0.11.4 with mod_limits_exception.lua:29: attempt to call method 'set_stanza_size_limit' (a nil value). That prosody misses set_stanza_size_limit.
Lua
apache-2.0
gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet
0ae03260bab355d34feabeadae2c2677b9d16ca2
src/debugger.lua
src/debugger.lua
local List = require 'list' local window = require 'window' local fonts = require 'fonts' local gamestate = require 'vendor/gamestate' local window = require 'window' local camera = require 'camera' local Debugger = { on=false, bbox=false } Debugger.__index = Debugger Debugger.sampleRate = 0.05 Debugger.lastSample = 0 Debugger.infoToShow = {} Debugger.infowidth = 100 Debugger.infoheight = 100 Debugger.graphData = { { name = 'gc', color = { 255, 0, 0, 150 } } } function Debugger:reset() love.mouse.setVisible( not ( Debugger.on and Debugger.bbox ) ) for k,_ in pairs(Debugger.graphData) do Debugger.graphData[k].list = List.new() end end function Debugger.set( d, bb ) Debugger.on = d Debugger.bbox = bb Debugger:reset() end function Debugger:toggle() if Debugger.on and not Debugger.bbox then Debugger.bbox = true elseif Debugger.on and Debugger.bbox then Debugger.on = false Debugger.bbox = false else Debugger.on = true end Debugger:reset() end function Debugger:getData(name) for k,v in pairs(Debugger.graphData) do if v.name == name then return Debugger.graphData[k] end end return false end function Debugger:listPush( list, val ) List.pushleft( list, val ) if math.abs(list.first) - math.abs(list.last) > window.screen_width then List.popright( list ) end end function Debugger:update( dt ) if Debugger.on and Debugger.lastSample > Debugger.sampleRate then Debugger:listPush( Debugger:getData('gc').list, collectgarbage( 'count' ) / 100 ) Debugger.lastSample = 0 else Debugger.lastSample = Debugger.lastSample + dt end end local function scale(t,s) for i=1,#t do t[i] = t[i] * s end return t end function Debugger:draw() if Debugger.bbox and gamestate.currentState().collider then local x, y = love.mouse.getPosition() x, y = x + camera.x, y + camera.y Debugger.infoToShow = {} camera:set() -- draw the boxes for _,shape in pairs(gamestate.currentState().collider._active_shapes) do Debugger.drawShape( shape, x, y, 255, 0, 0 ) end for _,shape in pairs(gamestate.currentState().collider._passive_shapes) do if shape.node.isActive then Debugger.drawShape( shape, x, y, 255, 255, 0 ) else Debugger.drawShape( shape, x, y, 0, 255, 0 ) end end for _,shape in pairs(gamestate.currentState().collider._ghost_shapes) do Debugger.drawShape( shape, x, y, 0, 0, 255 ) end Debugger.drawInfoBox( x, y ) camera:unset() love.graphics.setColor(255,255,255,255) end for k,v in pairs( Debugger.graphData ) do love.graphics.setColor( v.color ) for i=v.list.first, v.list.last do if v.list[i] then love.graphics.line( window.screen_width + v.list.first - i, window.screen_height - v.list[i], window.screen_width + v.list.first - i, window.screen_height ) end end end love.graphics.setColor( 255, 255, 255, 255 ) fonts.set('big') love.graphics.print( math.floor( collectgarbage( 'count' ) / 10 ) / 10 , window.screen_width - 30, window.screen_height - 10,0,0.5,0.5 ) fonts.revert() end function Debugger.drawShape( s, x, y, r, g, b ) love.graphics.setColor(r,g,b,100) s:draw('fill') love.graphics.setColor(r,g,b,50) s:draw('line') if s:contains( x, y ) and s.node and s.node.node then table.insert( Debugger.infoToShow, s.node.node ) end end function Debugger.drawInfoBox( x, y ) love.graphics.setColor(0,0,0,255) love.graphics.line( x - 2, y, x + 2, y ) love.graphics.line( x, y - 2, x, y + 2 ) if #Debugger.infoToShow > 0 then if x + Debugger.infowidth * #Debugger.infoToShow >= camera.x + window.width then x = x - Debugger.infowidth * #Debugger.infoToShow end if y + Debugger.infoheight >= camera.y + window.height then y = y - Debugger.infoheight end love.graphics.setColor(0,0,0,100) love.graphics.rectangle( 'fill', x, y, Debugger.infowidth * #Debugger.infoToShow, Debugger.infoheight ) love.graphics.setColor(0,0,0,50) love.graphics.rectangle( 'line', x, y, Debugger.infowidth * #Debugger.infoToShow, Debugger.infoheight ) love.graphics.setColor(255,255,255,255) x, y = x + 5, y + 5 local origy = y for _,info in pairs(Debugger.infoToShow) do for key,value in pairs(info) do if type( value ) ~= 'table' then love.graphics.print( key .. ' = ' .. value, x, y, 0, 0.5 ) else love.graphics.print( key .. ' = {', x, y, 0, 0.5 ) y = y + 6 for tablekey,tablevalue in pairs(value) do love.graphics.print( ' ' .. tablekey .. ' = ' .. tablevalue, x, y, 0, 0.5 ) y = y + 6 end love.graphics.print( '}', x, y, 0, 0.5 ) end y = y + 6 end x = x + Debugger.infowidth y = origy end end end return Debugger
local List = require 'list' local window = require 'window' local fonts = require 'fonts' local gamestate = require 'vendor/gamestate' local window = require 'window' local camera = require 'camera' local Debugger = { on=false, bbox=false } Debugger.__index = Debugger Debugger.sampleRate = 0.05 Debugger.lastSample = 0 Debugger.infoToShow = {} Debugger.infowidth = 100 Debugger.infoheight = 125 Debugger.graphData = { { name = 'gc', color = { 255, 0, 0, 150 } } } function Debugger:reset() love.mouse.setVisible( not ( Debugger.on and Debugger.bbox ) ) for k,_ in pairs(Debugger.graphData) do Debugger.graphData[k].list = List.new() end end function Debugger.set( d, bb ) Debugger.on = d Debugger.bbox = bb Debugger:reset() end function Debugger:toggle() if Debugger.on and not Debugger.bbox then Debugger.bbox = true elseif Debugger.on and Debugger.bbox then Debugger.on = false Debugger.bbox = false else Debugger.on = true end Debugger:reset() end function Debugger:getData(name) for k,v in pairs(Debugger.graphData) do if v.name == name then return Debugger.graphData[k] end end return false end function Debugger:listPush( list, val ) List.pushleft( list, val ) if math.abs(list.first) - math.abs(list.last) > window.screen_width then List.popright( list ) end end function Debugger:update( dt ) if Debugger.on and Debugger.lastSample > Debugger.sampleRate then Debugger:listPush( Debugger:getData('gc').list, collectgarbage( 'count' ) / 100 ) Debugger.lastSample = 0 else Debugger.lastSample = Debugger.lastSample + dt end end local function scale(t,s) for i=1,#t do t[i] = t[i] * s end return t end function Debugger:draw() if Debugger.bbox and gamestate.currentState().collider then local x, y = love.mouse.getPosition() x, y = x + camera.x, y + camera.y Debugger.infoToShow = {} camera:set() -- draw the boxes for _,shape in pairs(gamestate.currentState().collider._active_shapes) do Debugger.drawShape( shape, x, y, 255, 0, 0 ) end for _,shape in pairs(gamestate.currentState().collider._passive_shapes) do if shape.node.isActive then Debugger.drawShape( shape, x, y, 255, 255, 0 ) else Debugger.drawShape( shape, x, y, 0, 255, 0 ) end end for _,shape in pairs(gamestate.currentState().collider._ghost_shapes) do Debugger.drawShape( shape, x, y, 0, 0, 255 ) end Debugger.drawInfoBox( x, y ) camera:unset() love.graphics.setColor(255,255,255,255) end for k,v in pairs( Debugger.graphData ) do love.graphics.setColor( v.color ) for i=v.list.first, v.list.last do if v.list[i] then love.graphics.line( window.screen_width + v.list.first - i, window.screen_height - v.list[i], window.screen_width + v.list.first - i, window.screen_height ) end end end love.graphics.setColor( 255, 255, 255, 255 ) fonts.set('big') love.graphics.print( math.floor( collectgarbage( 'count' ) / 10 ) / 10 , window.screen_width - 30, window.screen_height - 10,0,0.5,0.5 ) fonts.revert() end function Debugger.drawShape( s, x, y, r, g, b ) love.graphics.setColor(r,g,b,100) s:draw('fill') love.graphics.setColor(r,g,b,50) s:draw('line') if s:contains( x, y ) and s.node and s.node.node then table.insert( Debugger.infoToShow, s.node.node ) end end function Debugger.drawInfoBox( x, y ) love.graphics.setColor(0,0,0,255) love.graphics.line( x - 2, y, x + 2, y ) love.graphics.line( x, y - 2, x, y + 2 ) if #Debugger.infoToShow > 0 then if x + Debugger.infowidth * #Debugger.infoToShow >= camera.x + window.width then x = x - Debugger.infowidth * #Debugger.infoToShow end if y + Debugger.infoheight >= camera.y + window.height then y = y - Debugger.infoheight end love.graphics.setColor(0,0,0,100) love.graphics.rectangle( 'fill', x, y, Debugger.infowidth * #Debugger.infoToShow, Debugger.infoheight ) love.graphics.setColor(0,0,0,50) love.graphics.rectangle( 'line', x, y, Debugger.infowidth * #Debugger.infoToShow, Debugger.infoheight ) love.graphics.setColor(255,255,255,255) x, y = x + 5, y + 5 local origy = y for _,info in pairs(Debugger.infoToShow) do for key,value in pairs(info) do if type( value ) ~= 'table' then love.graphics.print( key .. ' = ' .. value, x, y, 0, 0.5 ) else love.graphics.print( key .. ' = {', x, y, 0, 0.5 ) y = y + 6 for tablekey,tablevalue in pairs(value) do if type(tablevalue) == 'table' then local newtable = '' for i,n in pairs(tablevalue) do newtable = newtable .. i .. '=' .. n .. ' ' end tablevalue = newtable end love.graphics.print( ' ' .. tablekey .. ' = ' .. tablevalue, x, y, 0, 0.5 ) y = y + 6 end love.graphics.print( '}', x, y, 0, 0.5 ) end y = y + 6 end x = x + Debugger.infowidth y = origy end end end return Debugger
Fixes debugger crash when mousing over polygons.
Fixes debugger crash when mousing over polygons.
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
9c45de9aa9e72601057f50f82b7e1ed8e8cdbd1a
feedback/fkdkaggle.lua
feedback/fkdkaggle.lua
------------------------------------------------------------------------ --[[ FKDKaggle ]]-- -- Feedback -- Prepares a kaggle submission -- Requires csvigo ------------------------------------------------------------------------ local FKDKaggle, parent = torch.class("dp.FKDKaggle", "dp.Feedback") FKDKaggle.isFKDKaggle = true function FKDKaggle:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local args, submission, file_name, save_dir, name = xlua.unpack( {config}, 'FKDKaggle', 'Used to prepare a Kaggle Submission for the '.. 'Facial Keypoints Detection challenge', {arg='submission', type='table', req=true}, {arg='file_name', type='string', req=true}, {arg='save_dir', type='string', help='defaults to dp.SAVE_DIR'}, {arg='name', type='string', default='FKDKaggle'} ) require 'csvigo' config.name = name self._save_dir = save_dir self._submission = submission self._file_name = file_name parent.__init(self, config) self._pixels = torch.randn(0,97):float() self._pixelView = torch.FloatTensor() self._output = torch.FloatTensor() self._keypoints = torch.FloatTensor() self._keypoint = torch.FloatTensor() self._i = 2 end function FKDKaggle:setup(config) parent.setup(self, config) self._path = paths.concat(self._save_dir, self._file_name) self._mediator:subscribe("foundMinima", self, "foundMinima") end function FKDKaggle:_add(batch, output, carry, report) local act = output:forward('bwc', 'torch.FloatTensor') self._pixelView:view(self._pixels, act:size()) self._output:cmul(act, self._pixelView) self._keypoints:sum(self._output, 3) for i=1,act:size(1) do local keypoint = self._keypoints:select(1,i):select(2,1) for j=1,act:size(2) do self._submision[self._i][4] = keypoint[j] self._i = self._i + 1 end end end function FKDKaggle:_reset() self._i = 2 end function FKDKaggle:foundMinima() csvigo.save{path=self._path,data=self._submission,mode='raw'} end
------------------------------------------------------------------------ --[[ FKDKaggle ]]-- -- Feedback -- Prepares a kaggle submission -- Requires csvigo ------------------------------------------------------------------------ local FKDKaggle, parent = torch.class("dp.FKDKaggle", "dp.Feedback") FKDKaggle.isFKDKaggle = true function FKDKaggle:__init(config) config = config or {} assert(torch.type(config) == 'table' and not config[1], "Constructor requires key-value arguments") local args, submission, file_name, save_dir, name = xlua.unpack( {config}, 'FKDKaggle', 'Used to prepare a Kaggle Submission for the '.. 'Facial Keypoints Detection challenge', {arg='submission', type='table', req=true}, {arg='file_name', type='string', req=true}, {arg='save_dir', type='string', help='defaults to dp.SAVE_DIR'}, {arg='name', type='string', default='FKDKaggle'} ) require 'csvigo' config.name = name self._save_dir = save_dir self._submission = submission self._file_name = file_name parent.__init(self, config) self._pixels = torch.range(0,97):float():view(1,1,98) self._pixelView = torch.FloatTensor() self._output = torch.FloatTensor() self._keypoints = torch.FloatTensor() self._keypoint = torch.FloatTensor() self._i = 2 end function FKDKaggle:setup(config) parent.setup(self, config) self._path = paths.concat(self._save_dir, self._file_name) self._mediator:subscribe("foundMinima", self, "foundMinima") end function FKDKaggle:_add(batch, output, carry, report) local act = output:forward('bwc', 'torch.FloatTensor') self._pixelView:view(self._pixels, 1,1,self._pixels:size(1)) self._output:cmul(act, self._pixelView) self._keypoints:sum(self._output, 3) for i=1,act:size(1) do local keypoint = self._keypoints:select(1,i):select(2,1) for j=1,act:size(2) do self._submision[self._i][4] = keypoint[j] self._i = self._i + 1 end end end function FKDKaggle:_reset() self._i = 2 end function FKDKaggle:foundMinima() csvigo.save{path=self._path,data=self._submission,mode='raw'} end
FKDKaggle fixes
FKDKaggle fixes
Lua
bsd-3-clause
fiskio/dp,nicholas-leonard/dp,rickyHong/dptorchLib,eulerreich/dp,sagarwaghmare69/dp,jnhwkim/dp,kracwarlock/dp
91dc0004aa7c089558f3bf6bb788f94cc976cc85
plugins/database.lua
plugins/database.lua
local function callback_group_database(extra, success, result) local database = extra.database local chat_id = result.peer_id -- save group info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "), long_id = result.id } else database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = result.print_name:gsub("_"," "), long_id = result.id } end save_data(_config.database.db, database) -- save users info for k, v in pairs(result.members) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) end save_data(_config.database.db, database) database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } save_data(_config.database.db, database) else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } save_data(_config.database.db, database) database["users"][tostring(v.peer_id)]["groups"] = { } save_data(_config.database.db, database) database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) save_data(_config.database.db, database) end end send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked) end local function callback_supergroup_database(extra, success, result) local database = extra.database local chat_id = string.match(extra.receiver, '%d+') -- save supergroup info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "), old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'), long_id = extra.id } else database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = extra.print_name:gsub("_"," "), old_usernames = extra.username or 'NOUSER', long_id = extra.id } end save_data(_config.database.db, database) -- save users info for k, v in pairsByKeys(result) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) end save_data(_config.database.db, database) database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } save_data(_config.database.db, database) else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } save_data(_config.database.db, database) database["users"][tostring(v.peer_id)]["groups"] = { } save_data(_config.database.db, database) database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) save_data(_config.database.db, database) end end send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked) end local function run(msg, matches) if is_sudo(msg) then if matches[1]:lower() == 'createdatabase' then local f = io.open(_config.database.db, 'w+') f:write('{"groups":{},"users":{}}') f:close() reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false) return end local database = load_data(_config.database.db) if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then local receiver = get_receiver(msg) if msg.to.type == 'channel' then channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id }) elseif msg.to.type == 'chat' then chat_info(receiver, callback_group_database, { receiver = receiver, database = database }) else return end end else return langs[msg.lang].require_sudo end end return { description = "DATABASE", patterns = { "^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", "^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", -- database "^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", }, run = run, min_rank = 5 -- usage -- SUDO -- #createdatabase -- (#database|[sasha] database) }
local function callback_group_database(extra, success, result) local database = extra.database local chat_id = result.peer_id -- save group info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "), long_id = result.id } else database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = result.print_name:gsub("_"," "), long_id = result.id } end -- save users info for k, v in pairs(result.members) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)]["groups"] = { [tostring(chat_id)] = tonumber(chat_id) } end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked) end local function callback_supergroup_database(extra, success, result) local database = extra.database local chat_id = string.match(extra.receiver, '%d+') -- save supergroup info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "), old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'), long_id = extra.id } else database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = extra.print_name:gsub("_"," "), old_usernames = extra.username or 'NOUSER', long_id = extra.id } end -- save users info for k, v in pairsByKeys(result) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)]["groups"] = { [tostring(chat_id)] = tonumber(chat_id) } end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked) end local function run(msg, matches) if is_sudo(msg) then if matches[1]:lower() == 'createdatabase' then local f = io.open(_config.database.db, 'w+') f:write('{"groups":{},"users":{}}') f:close() reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false) return end local database = load_data(_config.database.db) if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then local receiver = get_receiver(msg) if msg.to.type == 'channel' then channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id }) elseif msg.to.type == 'chat' then chat_info(receiver, callback_group_database, { receiver = receiver, database = database }) else return end end else return langs[msg.lang].require_sudo end end return { description = "DATABASE", patterns = { "^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", "^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", -- database "^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", }, run = run, min_rank = 5 -- usage -- SUDO -- #createdatabase -- (#database|[sasha] database) }
fix database
fix database
Lua
agpl-3.0
xsolinsx/AISasha
a4868c1653ef6c2509e2c8723c0a853f99527620
src/premake4.lua
src/premake4.lua
os_properties = { windows = { dir = 'win32', pythondir = 'windows' }, macosx = { dir = 'osx', pythondir = 'osx' }, linux = { dir = 'linux', pythondir = 'linux' }, } props = {} if _OPTIONS.os == nil then error('Please specify your target os!') elseif os_properties[_OPTIONS.os] == nil then error('Unsupported os!') else props = os_properties[_OPTIONS.os] props.outdir = "..\\..\\ds_mod_tools_out\\" props.skuoutdir = props.outdir..props.dir.."\\mod_tools\\" props.tooldir = '..\\tools\\bin\\'..props.dir.."\\" end apps = { 'scml', 'png', 'autocompiler', --'textureconverter' } libs = { --'texturelib', 'modtoollib' } solution('mod_tools') configurations { "debug", "release" } location ( props.outdir.."proj" ) flags { "Symbols", "NoRTTI", "NoEditAndContinue", "NoExceptions", "NoPCH" } includedirs { "lib", "../lib/" } targetdir ( props.skuoutdir ) configuration { "debug" } defines { "DEBUG", "_CRT_SECURE_NO_WARNINGS" } configuration { "release" } defines { "RELEASE", "_CRT_SECURE_NO_WARNINGS" } flags { "Optimize" } for k, app in pairs(apps) do project(app) kind "ConsoleApp" language "C++" files { "app/"..app.."/**.h", "app/"..app.."/**.cpp" } for k, lib in pairs(libs) do links{ lib } end end for k, lib in pairs(libs) do project(lib) kind "StaticLib" language "C++" files { "lib/"..lib.."/**.h", "lib/"..lib.."/**.cpp" } end local function extract(file, folder) cmd = props.tooldir..'7z.exe -y x '..file..' -o'..folder os.execute(cmd) end extract('..\\pkg\\cmn\\mod_tools.zip', props.outdir..props.dir) extract('..\\pkg\\tst\\wand.zip', props.outdir..'dont_starve\\mods') extract('..\\pkg\\'..props.dir..'\\mod_tools.zip', props.outdir..props.dir) extract('..\\pkg\\'..props.dir..'\\Python27.zip', props.skuoutdir..'\\buildtools\\'..props.pythondir..'\\')
os_properties = { windows = { dir = 'win32', pythondir = 'windows' }, macosx = { dir = 'osx', pythondir = 'osx' }, linux = { dir = 'linux', pythondir = 'linux' }, } props = {} if _OPTIONS.os == nil then error('Please specify your target os!') elseif os_properties[_OPTIONS.os] == nil then error('Unsupported os!') else props = os_properties[_OPTIONS.os] props.outdir = "..\\..\\ds_mod_tools_out\\" props.skuoutdir = props.outdir..props.dir.."\\mod_tools\\" props.tooldir = '..\\tools\\bin\\'..props.dir.."\\" end apps = { 'scml', 'png', 'autocompiler', --'textureconverter' } libs = { --texturelib = { include_lib = true }, modtoollib = { include_lib = false }, } solution('mod_tools') configurations { "debug", "release" } location ( props.outdir.."proj" ) flags { "Symbols", "NoRTTI", "NoEditAndContinue", "NoExceptions", "NoPCH" } includedirs { "lib", "../lib/" } targetdir ( props.skuoutdir ) configuration { "debug" } defines { "DEBUG", "_CRT_SECURE_NO_WARNINGS" } configuration { "release" } defines { "RELEASE", "_CRT_SECURE_NO_WARNINGS" } flags { "Optimize" } for k, app in pairs(apps) do project(app) kind "ConsoleApp" language "C++" files { "app/"..app.."/**.h", "app/"..app.."/**.cpp" } for lib, settings in pairs(libs) do links{ lib } end end for lib, settings in pairs(libs) do project(lib) kind "StaticLib" language "C++" files { "lib/"..lib.."/**.h", "lib/"..lib.."/**.cpp" } if settings.include_lib then includedirs { "lib/"..lib } end end local function extract(file, folder) cmd = props.tooldir..'7z.exe -y x '..file..' -o'..folder os.execute(cmd) end extract('..\\pkg\\cmn\\mod_tools.zip', props.outdir..props.dir) extract('..\\pkg\\tst\\wand.zip', props.outdir..'dont_starve\\mods') extract('..\\pkg\\'..props.dir..'\\mod_tools.zip', props.outdir..props.dir) extract('..\\pkg\\'..props.dir..'\\Python27.zip', props.skuoutdir..'\\buildtools\\'..props.pythondir..'\\')
Fixed some linker issues with textureconverter.
Fixed some linker issues with textureconverter.
Lua
mit
kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools,kleientertainment/ds_mod_tools
b4239a68c57cc1794161a649f7f791164809b073
cfg/mpi/config/scripts/image_statusbar.lua
cfg/mpi/config/scripts/image_statusbar.lua
local on = mp.get_opt('images-statusbar') == 'yes' -- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function roundNumber(num, digits) local fmt = "%." .. digits .. "f" return tonumber(fmt:format(num)) end local function get_file_size(size) if size == 0 or size == nil then return "0" .. si[1] end local exponent = math.floor(math.log(size) / math.log(1024)) if exponent > 8 then exponent = 8 end local value = roundNumber( size / math.pow(2, exponent * 10), exponent > 0 and 1 or 0) local suffix = si[exponent + 1] return tostring(value):gsub('%.0$', '') .. suffix end function get_property_number_or_nil(name) if mp.get_property(name) == nil then return nil end return mp.get_property_number(name) end function update_statusbar() if on == true then local playlist_pos = mp.get_property_number('playlist-pos') + 1 local playlist_count = mp.get_property_number('playlist-count') local width = get_property_number_or_nil('width') local height = get_property_number_or_nil('height') local size = get_file_size(mp.get_property_number('file-size')) local path = mp.get_property('filename') mp.set_property( 'options/osd-msg1', string.format( '%s %sx%s %s (%d/%d)', path, width or '?', height or '?', size, playlist_pos, playlist_count)) else mp.set_property('options/osd-msg1', '') end end function toggle_statusbar() on = not on update_statusbar() mp.osd_message('', 0) end mp.register_event('file-loaded', update_statusbar) mp.register_script_message('toggle-statusbar', toggle_statusbar)
local on = mp.get_opt('images-statusbar') == 'yes' -- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function roundNumber(num, digits) local fmt = "%." .. digits .. "f" return tonumber(fmt:format(num)) end local function get_file_size(size) if size == 0 or size == nil then return "0" .. si[1] end local exponent = math.floor(math.log(size) / math.log(1024)) if exponent > 8 then exponent = 8 end local value = roundNumber( size / math.pow(2, exponent * 10), exponent > 0 and 1 or 0) local suffix = si[exponent + 1] return tostring(value):gsub('%.0$', '') .. suffix end function get_property_number_or_nil(name) if mp.get_property(name) == nil then return nil end return mp.get_property_number(name) end function update_statusbar() if on == true then local playlist_pos = mp.get_property_number('playlist-pos') + 1 local playlist_count = mp.get_property_number('playlist-count') local width = get_property_number_or_nil('width') local height = get_property_number_or_nil('height') local size = get_file_size(mp.get_property_number('file-size')) local path = mp.get_property('filename') mp.set_property( 'options/osd-msg1', string.format( '%s %sx%s %s (%d/%d)', path, width or '?', height or '?', size, playlist_pos, playlist_count)) else mp.set_property('options/osd-msg1', '') end end function toggle_statusbar() on = not on update_statusbar() mp.osd_message('', 0) end mp.register_event('file-loaded', update_statusbar) mp.register_event('playback-restart', update_statusbar) mp.register_script_message('toggle-statusbar', toggle_statusbar)
cfg/mpi: fix dimensions not shown for JPEG files
cfg/mpi: fix dimensions not shown for JPEG files
Lua
mit
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
797b75213c4d1133012aff568b2bf75b4270068e
luapress/util.lua
luapress/util.lua
-- Luapress -- File: luapress/util.lua -- Desc: internal Luapress utilities! local os = os local io = io local print = print local pairs = pairs local error = error local table = table local string = string local lfs = require('lfs') local markdown = require('luapress.lib.markdown') local template = require('luapress.template') -- Writes a header/footer wrapped HTML file depending on the modification time local function write_html(destination, object, object_type, templates, config) -- Check modification time on post & destination files local attributes = lfs.attributes(destination) if not config.cache or not attributes or object.time > attributes.modification then local output = template:process(templates.header, templates[object_type], templates.footer) -- Write the file f, err = io.open(destination, 'w') if not f then error(err) end local result, err = f:write(output) if not result then error(err) end f:close() if config.print then print('\t' .. object.title) end end end -- Returns the destination file given our config local function ensure_destination(directory, object_type, link, config) if config.link_dirs then lfs.mkdir(directory .. '/build/' .. object_type .. '/' .. link) return 'build/' .. object_type .. '/' .. link .. '/index.html' end return 'build/' .. object_type .. '/' .. link end -- Builds link list based on the currently active page local function page_links(pages, active, config) local output = '' for k, page in pairs(pages) do if not page.hidden then if page.link == active then output = output .. '<li class="active"><a href="' .. config.url .. '/pages/' .. active .. '">' .. page.title .. '</a></li>\n' else output = output .. '<li><a href="' .. config.url .. '/pages/' .. page.link .. '">' .. page.title .. '</a></li>\n' end end end return output end -- Load markdown files in a directory local function load_markdowns(directory, config) local outs = {} for file in lfs.dir(directory) do if file:sub(-3) == '.md' then local title = file:sub(0, -4) file = directory .. '/' .. file local attributes = lfs.attributes(file) -- Work out title local link = title:gsub(' ', '_'):gsub('[^_aA-zZ0-9]', '') if not config.link_dirs then link = link .. '.html' end -- Get basic attributes local out = { link = link, title = title, content = '', time = attributes.modification } -- Now read the file local f, err = io.open(file, 'r') if not f then error(err) end local s, err = f:read('*a') if not s then error(err) end -- Set $=key's s = s:gsub('%$=url', config.url) -- Get $key=value's for k, v, c, d in s:gmatch('%$([%w]+)=(.-)\n') do out[k] = v s = s:gsub('%$[%w]+=.-\n', '') end -- Excerpt local start, finish = s:find('--MORE--') if start then s = s:sub(0, start - 1) out.excerpt = markdown(s) end s = s:gsub('--MORE--', '') out.content = markdown(s) -- Date set? if out.date then local _, _, d, m, y = out.date:find('(%d+)%/(%d+)%/(%d+)') out.time = os.time({day = d, month = m, year = y}) end -- Insert to outs table.insert(outs, out) if config.print then print('\t' .. out.title) end end end return outs end -- Loads lhtml templates in a directory local function load_templates(directory) local templates = {} for file in lfs.dir(directory) do if file:sub(-5) == 'lhtml' then local tmpl_name = file:sub(0, -7) file = directory .. '/' .. file local f, err = io.open(file, 'r') if not f then error(err) end local s, err = f:read('*a') if not s then error(err) end f:close() templates[tmpl_name] = s end end -- RSS template templates.rss = { time = 0, content = [[ <?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title><?=self:get('title') ?></title> <link><?=self:get('url') ?></link> <? for k, post in pairs(self:get('posts')) do ?> <item> <title><?=post.title ?></title> <description><?=post.excerpt ?></description> <link><?=self:get('url') ?>/posts/<?=post.link ?></link> <guid><?=self:get('url') ?>/posts/<?=post.link ?></guid> </item> <? end ?> </channel> </rss> ]]} return templates end -- Recursively duplicates a directory local function copy_dir(directory, destination) for file in lfs.dir(directory) do if file ~= '.' and file ~= '..' then local attributes = lfs.attributes(directory .. file) or {} -- Directory? if attributes.mode and attributes.mode == 'directory' then -- Ensure destination directory if not io.open(destination .. file, 'r') then lfs.mkdir(destination .. file) end copy_dir(directory .. file .. '/', destination .. file .. '/') end -- File? if attributes.mode and attributes.mode == 'file' then local dest_attributes = lfs.attributes(destination .. file) if not dest_attributes or attributes.modification > dest_attributes.modification then -- Open current file local f, err = io.open(directory .. file, 'r') if not f then error(err) end -- Read file local s, err = f:read('*a') if not s then error(err) end f:close() -- Open new file for creation local f, err = io.open(destination .. file, 'w') -- Write contents local result, err = f:write(s) if not result then error(err) end f:close() print('\t' .. destination .. file) end end end end end -- Export return { copy_dir = copy_dir, load_templates = load_templates, load_markdowns = load_markdowns, page_links = page_links, ensure_destination = ensure_destination, write_html = write_html }
-- Luapress -- File: luapress/util.lua -- Desc: internal Luapress utilities! local os = os local io = io local print = print local pairs = pairs local error = error local table = table local string = string local lfs = require('lfs') local markdown = require('luapress.lib.markdown') local template = require('luapress.template') -- Writes a header/footer wrapped HTML file depending on the modification time local function write_html(destination, object, object_type, templates, config) -- Check modification time on post & destination files local attributes = lfs.attributes(destination) if not config.cache or not attributes or object.time > attributes.modification then local output = template:process(templates.header, templates[object_type], templates.footer) -- Write the file f, err = io.open(destination, 'w') if not f then error(err) end local result, err = f:write(output) if not result then error(err) end f:close() if config.print then print('\t' .. object.title) end end end -- Returns the destination file given our config local function ensure_destination(directory, object_type, link, config) if config.link_dirs then lfs.mkdir(directory .. '/build/' .. object_type .. '/' .. link) return 'build/' .. object_type .. '/' .. link .. '/index.html' end return 'build/' .. object_type .. '/' .. link end -- Builds link list based on the currently active page local function page_links(pages, active, config) local output = '' for k, page in pairs(pages) do if not page.hidden then if page.link == active then output = output .. '<li class="active"><a href="' .. config.url .. '/pages/' .. active .. '">' .. page.title .. '</a></li>\n' else output = output .. '<li><a href="' .. config.url .. '/pages/' .. page.link .. '">' .. page.title .. '</a></li>\n' end end end return output end -- Load markdown files in a directory local function load_markdowns(directory, config) local outs = {} for file in lfs.dir(directory) do if file:sub(-3) == '.md' then local title = file:sub(0, -4) file = directory .. '/' .. file local attributes = lfs.attributes(file) -- Work out title local link = title:gsub(' ', '_'):gsub('[^_aA-zZ0-9]', '') if not config.link_dirs then link = link .. '.html' end -- Get basic attributes local out = { link = link, title = title, content = '', time = attributes.modification } -- Now read the file local f, err = io.open(file, 'r') if not f then error(err) end local s, err = f:read('*a') if not s then error(err) end -- Set $=key's s = s:gsub('%$=url', config.url) -- Get $key=value's for k, v, c, d in s:gmatch('%$([%w]+)=(.-)\n') do out[k] = v s = s:gsub('%$[%w]+=.-\n', '') end -- Excerpt local start, _ = s:find('--MORE--') if start then -- Extract the excerpt out.excerpt = markdown(s:sub(0, start - 1)) -- Replace the --MORE-- s = s:gsub('%-%-MORE%-%-', '<a id="more">&nbsp;</a>') end out.content = markdown(s) -- Date set? if out.date then local _, _, d, m, y = out.date:find('(%d+)%/(%d+)%/(%d+)') out.time = os.time({day = d, month = m, year = y}) end -- Insert to outs table.insert(outs, out) if config.print then print('\t' .. out.title) end end end return outs end -- Loads lhtml templates in a directory local function load_templates(directory) local templates = {} for file in lfs.dir(directory) do if file:sub(-5) == 'lhtml' then local tmpl_name = file:sub(0, -7) file = directory .. '/' .. file local f, err = io.open(file, 'r') if not f then error(err) end local s, err = f:read('*a') if not s then error(err) end f:close() templates[tmpl_name] = s end end -- RSS template templates.rss = { time = 0, content = [[ <?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title><?=self:get('title') ?></title> <link><?=self:get('url') ?></link> <? for k, post in pairs(self:get('posts')) do ?> <item> <title><?=post.title ?></title> <description><?=post.excerpt ?></description> <link><?=self:get('url') ?>/posts/<?=post.link ?></link> <guid><?=self:get('url') ?>/posts/<?=post.link ?></guid> </item> <? end ?> </channel> </rss> ]]} return templates end -- Recursively duplicates a directory local function copy_dir(directory, destination) for file in lfs.dir(directory) do if file ~= '.' and file ~= '..' then local attributes = lfs.attributes(directory .. file) or {} -- Directory? if attributes.mode and attributes.mode == 'directory' then -- Ensure destination directory if not io.open(destination .. file, 'r') then lfs.mkdir(destination .. file) end copy_dir(directory .. file .. '/', destination .. file .. '/') end -- File? if attributes.mode and attributes.mode == 'file' then local dest_attributes = lfs.attributes(destination .. file) if not dest_attributes or attributes.modification > dest_attributes.modification then -- Open current file local f, err = io.open(directory .. file, 'r') if not f then error(err) end -- Read file local s, err = f:read('*a') if not s then error(err) end f:close() -- Open new file for creation local f, err = io.open(destination .. file, 'w') -- Write contents local result, err = f:write(s) if not result then error(err) end f:close() print('\t' .. destination .. file) end end end end end -- Export return { copy_dir = copy_dir, load_templates = load_templates, load_markdowns = load_markdowns, page_links = page_links, ensure_destination = ensure_destination, write_html = write_html }
Fix handling of --MORE-- (escape those -!)
Fix handling of --MORE-- (escape those -!)
Lua
mit
Fizzadar/Luapress,Fizzadar/Luapress,w-oertl/Luapress,w-oertl/Luapress
07426fe3f2f6a7bd8168226d762932cabe0543bb
src/lib/timers/ingress_drop_monitor.lua
src/lib/timers/ingress_drop_monitor.lua
module(...,package.seeall) -- Ingress packet drop monitor timer. local S = require("syscall") local counter = require("core.counter") local ffi = require("ffi") local shm = require("core.shm") -- Every 100 milliseconds. local default_interval = 1e8 local now = core.app.now local IngressDropMonitor = {} function new(args) local ret = { threshold = args.threshold or 100000, wait = args.wait or 20, action = args.action or 'flush', last_flush = 0, last_value = ffi.new('uint64_t[1]'), current_value = ffi.new('uint64_t[1]') } if args.counter then if not shm.exists("/"..S.getpid().."/"..args.counter) then ret.counter = counter.create(args.counter, 0) else ret.counter = counter.open(args.counter) end end return setmetatable(ret, {__index=IngressDropMonitor}) end function IngressDropMonitor:sample () local app_array = engine.app_array local sum = self.current_value sum[0] = 0 for i = 1, #app_array do local app = app_array[i] if app.ingress_packet_drops and not app.dead then sum[0] = sum[0] + app:ingress_packet_drops() end end if self.counter then counter.add(self.counter, sum[0]) end end local tips_url = "https://github.com/Igalia/snabb/blob/lwaftr/src/program/lwaftr/doc/README.performance.md" function IngressDropMonitor:jit_flush_if_needed () if self.current_value[0] - self.last_value[0] < self.threshold then return end if now() - self.last_flush < self.wait then return end self.last_flush = now() self.last_value[0] = self.current_value[0] --- TODO: Change last_flush, last_value and current_value fields to be counters. local msg = now()..": warning: Dropped more than "..self.threshold.." packets" if self.action == 'flush' then msg = msg.."; flushing JIT to try to recover" end msg = msg..". See "..tips_url.." for performance tuning tips." print(msg) if self.action == 'flush' then jit.flush() end end function IngressDropMonitor:timer(interval) return timer.new("ingress drop monitor", function () self:sample() self:jit_flush_if_needed() end, interval or default_interval, "repeating") end
module(...,package.seeall) -- Ingress packet drop monitor timer. local S = require("syscall") local counter = require("core.counter") local ffi = require("ffi") local shm = require("core.shm") -- Every 100 milliseconds. local default_interval = 1e8 local now = core.app.now local IngressDropMonitor = {} function new(args) local ret = { threshold = args.threshold or 100000, wait = args.wait or 20, action = args.action or 'flush', last_flush = 0, last_value = ffi.new('uint64_t[1]'), current_value = ffi.new('uint64_t[1]') } if args.counter then if not args.counter:match(".counter$") then args.counter = args.counter..".counter" end if not shm.exists("/"..S.getpid().."/"..args.counter) then ret.counter = counter.create(args.counter, 0) else ret.counter = counter.open(args.counter) end end return setmetatable(ret, {__index=IngressDropMonitor}) end function IngressDropMonitor:sample () local app_array = engine.app_array local sum = self.current_value sum[0] = 0 for i = 1, #app_array do local app = app_array[i] if app.ingress_packet_drops and not app.dead then sum[0] = sum[0] + app:ingress_packet_drops() end end if self.counter then counter.add(self.counter, sum[0]) end end local tips_url = "https://github.com/Igalia/snabb/blob/lwaftr/src/program/lwaftr/doc/README.performance.md" function IngressDropMonitor:jit_flush_if_needed () if self.current_value[0] - self.last_value[0] < self.threshold then return end if now() - self.last_flush < self.wait then return end self.last_flush = now() self.last_value[0] = self.current_value[0] --- TODO: Change last_flush, last_value and current_value fields to be counters. local msg = now()..": warning: Dropped more than "..self.threshold.." packets" if self.action == 'flush' then msg = msg.."; flushing JIT to try to recover" end msg = msg..". See "..tips_url.." for performance tuning tips." print(msg) if self.action == 'flush' then jit.flush() end end function IngressDropMonitor:timer(interval) return timer.new("ingress drop monitor", function () self:sample() self:jit_flush_if_needed() end, interval or default_interval, "repeating") end
Append .counter suffix if necessary
Append .counter suffix if necessary
Lua
apache-2.0
mixflowtech/logsensor,Igalia/snabbswitch,kbara/snabb,mixflowtech/logsensor,eugeneia/snabb,heryii/snabb,dpino/snabb,kbara/snabb,dpino/snabb,heryii/snabb,SnabbCo/snabbswitch,eugeneia/snabb,dpino/snabbswitch,kbara/snabb,dpino/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabbswitch,dpino/snabb,dpino/snabb,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabbswitch,Igalia/snabb,heryii/snabb,kbara/snabb,Igalia/snabb,dpino/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,kbara/snabb,mixflowtech/logsensor,heryii/snabb,mixflowtech/logsensor,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,heryii/snabb,Igalia/snabb,eugeneia/snabb,kbara/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,Igalia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,dpino/snabb,heryii/snabb,snabbco/snabb,eugeneia/snabb,dpino/snabbswitch,snabbco/snabb,dpino/snabb,eugeneia/snabbswitch,snabbco/snabb,dpino/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch
bcbb86cfda0a2dd1af9a225a2707962013d0e4a0
pud/view/GameCam.lua
pud/view/GameCam.lua
require 'pud.util' local Class = require 'lib.hump.class' local Camera = require 'lib.hump.camera' local vector = require 'lib.hump.vector' local Rect = require 'pud.kit.Rect' local _zoomLevels = {1, 0.5, 0.25} local GameCam = Class{name='GameCam', function(self, v, zoom) v = v or vector(0,0) self._zoom = math.max(1, math.min(#_zoomLevels, zoom or 1)) self._home = v self._cam = Camera(v, _zoomLevels[self._zoom]) end } -- destructor function GameCam:destroy() self._cam = nil self._home = nil self._zoom = nil self._target = nil self._targetSetX = nil self._targetSetY = nil for k,v in pairs(self._limits) do self._limits[k] = nil end self._bounday = nil end -- zoom in smoothly function GameCam:zoomIn() if self._zoom > 1 then self._zoom = self._zoom - 1 tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack') else self:_bumpZoom(1.1) end end -- zoom out smoothly function GameCam:zoomOut() if self._zoom < #_zoomLevels then self._zoom = self._zoom + 1 tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack') else self:_bumpZoom(0.9) end end -- bump the zoom but don't change it function GameCam:_bumpZoom(mult) tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad', tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad') end -- return zoom level function GameCam:getZoom() return self._zoom, _zoomLevels[self._zoom] end -- follow a target Rect function GameCam:followTarget(rect) assert(rect and rect.is_a and rect:is_a(Rect), 'GameCam can only follow a Rect (tried to follow %s)', tostring(rect)) self._target = rect self._targetSetX = rect.setX self._targetSetY = rect.setY rect.setX = function(theRect, x) self._targetSetX(theRect, x) local cx, cy = theRect:getCenter('floor') self:_setPos(cx, cy) self:_correctCam() end rect.setY = function(theRect, y) self._targetSetY(theRect, y) local cx, cy = theRect:getCenter('floor') self:_setPos(cx, cy) self:_correctCam() end end -- unfollow a target Rect function GameCam:unfollowTarget() if self._target then self._target.setX = self._targetSetX self._target.setY = self._targetSetY self._targetSetX = nil self._targetSetY = nil self._target = nil end end -- set position function GameCam:_setPos(x, y) if type(x) == 'table' then x, y = x.x, x.y end verify('number', x, y) self._cam.pos.x = x self._cam.pos.y = y end -- center on initial vector function GameCam:home() self:unfollowTarget() self:_setPos(self._home) self:_correctCam() end -- change home vector function GameCam:setHome(x, y) local v = x if type(x) == 'number' then v = vector(x, y) end self._home = v end -- translate along x and y function GameCam:translate(x, y) local v = x if type(x) == 'number' then v = vector(x, y) end self._cam:translate(v) self:_correctCam() end -- set x and y limits for camera function GameCam:setLimits(minX, minY, maxX, maxY) local minV, maxV = minX, minY if type(minX) == 'number' then minV = vector(minX, minY) maxV = vector(maxX, maxY) end self._limits = {min = minV, max = maxV} end -- correct the camera position if it is beyond the limits function GameCam:_correctCam() if self._cam.pos.x > self._limits.max.x then self._cam.pos.x = self._limits.max.x end if self._cam.pos.x < self._limits.min.x then self._cam.pos.x = self._limits.min.x end if self._cam.pos.y > self._limits.max.y then self._cam.pos.y = self._limits.max.y end if self._cam.pos.y < self._limits.min.y then self._cam.pos.y = self._limits.min.y end end -- camera draw callbacks function GameCam:predraw() self._cam:predraw() end function GameCam:postdraw() self._cam:postdraw() end function GameCam:draw(...) self._cam:draw(...) end -- the class return GameCam
require 'pud.util' local Class = require 'lib.hump.class' local Camera = require 'lib.hump.camera' local vector = require 'lib.hump.vector' local Rect = require 'pud.kit.Rect' local _zoomLevels = {1, 0.5, 0.25} local _isVector = function(...) local n = select('#',...) for i=1,n do local v = select(i,...) assert(vector.isvector(v), 'vector expected, got %s (%s)', tostring(v), type(v)) end return n > 0 end local GameCam = Class{name='GameCam', function(self, v, zoom) v = v or vector(0,0) if _isVector(v) then self._zoom = math.max(1, math.min(#_zoomLevels, zoom or 1)) self._home = v self._cam = Camera(v, _zoomLevels[self._zoom]) end end } -- destructor function GameCam:destroy() self._cam = nil self._home = nil self._zoom = nil self._target = nil self._targetFuncs.setX = nil self._targetFuncs.setY = nil self._targetFuncs.setCenter = nil self._targetFuncs.setPosition = nil self._targetFuncs = nil for k,v in pairs(self._limits) do self._limits[k] = nil end self._limits = nil end function GameCam:_setAnimating(b) verify('boolean', b) self._isAnimating = b end function GameCam:isAnimating() return self._isAnimating == true end -- zoom in smoothly function GameCam:zoomIn() if self._zoom > 1 and not self:isAnimating() then self._zoom = self._zoom - 1 self:_setAnimating(true) tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack', self._setAnimating, self, false) else self:_bumpZoom(1.1) end end -- zoom out smoothly function GameCam:zoomOut() if self._zoom < #_zoomLevels and not self:isAnimating() then self._zoom = self._zoom + 1 self:_setAnimating(true) tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack', self._setAnimating, self, false) else self:_bumpZoom(0.9) end end -- bump the zoom but don't change it function GameCam:_bumpZoom(mult) if not self:isAnimating() then self:_setAnimating(true) tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad', tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad', self._setAnimating, self, false) end end -- return zoom level function GameCam:getZoom() return self._zoom, _zoomLevels[self._zoom] end -- follow a target Rect function GameCam:followTarget(rect) assert(rect and rect.is_a and rect:is_a(Rect), 'GameCam can only follow a Rect (tried to follow %s)', tostring(rect)) self._target = rect self._targetFuncs = { setX = rect.setX, setY = rect.setY, setPosition = rect.setPosition, setCenter = rect.setCenter, } local function _follow(self, theRect) self._cam.pos = theRect:getCenterVector() self:_correctCam() end rect.setX = function(theRect, x) self._targetFuncs.setX(theRect, x) _follow(self, theRect) end rect.setY = function(theRect, y) self._targetFuncs.setY(theRect, y) _follow(self, theRect) end rect.setPosition = function(theRect, x, y) self._targetFuncs.setPosition(theRect, x, y) _follow(self, theRect) end rect.setCenter = function(theRect, x, y, flag) self._targetFuncs.setCenter(theRect, x, y, flag) _follow(self, theRect) end end -- unfollow a target Rect function GameCam:unfollowTarget() if self._target then self._target.setX = self._targetFuncs.setX self._target.setY = self._targetFuncs.setY self._target.setPosition = self._targetFuncs.setPosition self._target.setCenter = self._targetFuncs.setCenter self._targetFuncs.setX = nil self._targetFuncs.setY = nil self._targetFuncs.setPosition = nil self._targetFuncs.setCenter = nil self._target = nil end end -- center on initial vector function GameCam:home() self:unfollowTarget() self._cam.pos = self._home self:_correctCam() end -- change home vector function GameCam:setHome(home) if _isVector(home) then self._home = home end end -- translate along v function GameCam:translate(v) if _isVector(v) and not self:isAnimating() then local target = self._cam.pos + v if self:_shouldTranslate(v) then self:_setAnimating(true) tween(0.15, self._cam.pos, target, 'outQuint', self._setAnimating, self, false) end end end function GameCam:_shouldTranslate(v) local pos = self._cam.pos + v return not (pos.x > self._limits.max.x or pos.x < self._limits.min.x or pos.y > self._limits.max.y or pos.y < self._limits.min.y) end -- set x and y limits for camera function GameCam:setLimits(minV, maxV) if _isVector(minV, maxV) then self._limits = {min = minV, max = maxV} end end -- correct the camera position if it is beyond the limits function GameCam:_correctCam() if self._cam.pos.x > self._limits.max.x then self._cam.pos.x = self._limits.max.x end if self._cam.pos.x < self._limits.min.x then self._cam.pos.x = self._limits.min.x end if self._cam.pos.y > self._limits.max.y then self._cam.pos.y = self._limits.max.y end if self._cam.pos.y < self._limits.min.y then self._cam.pos.y = self._limits.min.y end end -- camera draw callbacks function GameCam:predraw() self._cam:predraw() end function GameCam:postdraw() self._cam:postdraw() end function GameCam:draw(...) self._cam:draw(...) end -- the class return GameCam
fix GameCam to work with vectors, animate, and check if animating
fix GameCam to work with vectors, animate, and check if animating
Lua
mit
scottcs/wyx
441cc332cb04d65c69216d7ff972c0e61adc7604
src/common/http.lua
src/common/http.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Http = newclass "Http" function Http:init(loader) self.loader = loader end function Http:get(url, headers, extra) local response, result, code = http.get(url, { headers = self:_convertHeaders(headers) }) return response end function Http:download(url, outFile, headers, showProgress) local mayWrite = true function progress(total, current) local ratio = current / total; ratio = math.min(math.max(ratio, 0), 1); local percent = math.floor(ratio * 100); if mayWrite then io.write("\rDownload progress (" .. percent .. "%/100%)") end if percent == 100.0 and mayWrite then io.write("\n") mayWrite = false end end local response, code = http.download(url, outFile, { headers = self:_convertHeaders(headers), progress = iif(showProgress, progress, nil) }) return response end function Http:downloadFromArchive(url, pattern, iszip) pattern = iif(pattern == nil and type(pattern) ~= "boolean", false, pattern) if url:contains(".zip") or iszip then return self:downloadFromZip(url, pattern) end return self:downloadFromTarGz(url, pattern) end function Http:downloadFromZipTo(url, destination, pattern) pattern = iif(pattern == nil and type(pattern) ~= "boolean", "*", pattern) destination = iif(destination == nil and type(destination) ~= "boolean", path.join(self.loader.temp, os.uuid()), destination) local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip") self:download(url, zipFile) zip.extract(zipFile, destination) if pattern and pattern ~= "*" then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromTarGzTo(url, destination, pattern) pattern = iif(pattern == nil and type(pattern) ~= "boolean", "*", pattern) local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz") self:download(url, zipFile) os.executef("tar xzf %s -C %s", zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromZip(url, pattern) pattern = iif(pattern == nil and type(pattern) ~= "boolean", false, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromZipTo(url, dest, pattern) end function Http:downloadFromTarGz(url, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromTarGzTo(url, dest, pattern) end function Http:_convertHeaders(headers) headers = iif(headers == nil, { }, headers) if not zpm.util.isArray(t) then local nheaders = {} for k, v in pairs(headers) do table.insert(nheaders, string.format("%s: %s", k, v)) end return nheaders end return headers end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Http = newclass "Http" function Http:init(loader) self.loader = loader end function Http:get(url, headers, extra) local response, result, code = http.get(url, { headers = self:_convertHeaders(headers) }) return response end function Http:download(url, outFile, headers, showProgress) local mayWrite = true function progress(total, current) local ratio = current / total; ratio = math.min(math.max(ratio, 0), 1); local percent = math.floor(ratio * 100); if mayWrite then io.write("\rDownload progress (" .. percent .. "%/100%)") end if percent == 100.0 and mayWrite then io.write("\n") mayWrite = false end end local response, code = http.download(url, outFile, { headers = self:_convertHeaders(headers), progress = iif(showProgress, progress, nil) }) return response end function Http:downloadFromArchive(url, pattern, iszip) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) if url:contains(".zip") or iszip then return self:downloadFromZip(url, pattern) end return self:downloadFromTarGz(url, pattern) end function Http:downloadFromZipTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) destination = iif(destination == nil or type(destination) == "boolean", path.join(self.loader.temp, os.uuid()), destination) local zipFile = path.join(self.loader.temp, os.uuid() .. ".zip") self:download(url, zipFile) zip.extract(zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromTarGzTo(url, destination, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", "*", pattern) local zipFile = path.join(self.loader.temp, os.uuid() .. ".tar.gz") self:download(url, zipFile) os.executef("tar xzf %s -C %s", zipFile, destination) if pattern then return os.matchfiles(path.join(destination, pattern)) else return destination end end function Http:downloadFromZip(url, pattern) pattern = iif(pattern == nil or type(pattern) == "boolean", false, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromZipTo(url, dest, pattern) end function Http:downloadFromTarGz(url, pattern) local dest = path.join(self.loader.temp, os.uuid()) zpm.assert(os.mkdir(dest), "Failed to create temporary directory '%s'!", dest) return self:downloadFromTarGzTo(url, dest, pattern) end function Http:_convertHeaders(headers) headers = iif(headers == nil, { }, headers) if not zpm.util.isArray(t) then local nheaders = {} for k, v in pairs(headers) do table.insert(nheaders, string.format("%s: %s", k, v)) end return nheaders end return headers end
Fixed pattern matching on zip
Fixed pattern matching on zip
Lua
mit
Zefiros-Software/ZPM
da58b3d8025d6f7d9145e3cbc1fd1908eca0bc86
src/program/lwaftr/quickcheck/quickcheck.lua
src/program/lwaftr/quickcheck/quickcheck.lua
module(...,package.seeall) local lib = require("core.lib") local utils = require("program.lwaftr.quickcheck.utils") local function show_usage(code) print(require("program.lwaftr.quickcheck.README_inc")) main.exit(code) end local function parse_args (args) local handlers = {} local opts = { iterations = 100, } function handlers.h() show_usage(0) end handlers["seed"] = function (arg) opts["seed"] = assert(tonumber(arg), "seed must be a number") end handlers["iterations"] = function (arg) opts["iterations"] = assert(tonumber(arg), "iterations must be a number") end args = lib.dogetopt(args, handlers, "h", { help="h", ["seed"] = 0, ["iterations"] = 0 }) if #args == 0 then show_usage(1) end if not opts.seed then local seed = math.floor(utils.gmtime() * 1e6) % 10^9 print("Using time as seed: "..seed) opts.seed = seed end local prop_name = table.remove(args, 1) return opts, prop_name, args end -- Due to limitations of Lua 5.1, finding if a command failed is convoluted. local function find_gitrev() local fd = io.popen('git rev-parse HEAD 2>/dev/null ; echo -n "$?"') local cmdout = fd:read("*all") fd:close() -- Always true in 5.1, with Lua or LuaJIT. local _, _, git_ret = cmdout:find("(%d+)$") git_ret = tonumber(git_ret) if git_ret ~= 0 then -- Probably not in a git repo. return nil else local _, _, sha1 = cmdout:find("(%x+)") return sha1 end end local function print_gitrev_if_available() local rev = find_gitrev() if rev then print(("Git revision %s"):format(rev)) end end local function initialize_property (name, args) local prop = require(name) if not prop.handle_prop_args then assert(#args == 0, "Property does not take options "..name) end return prop, prop.handle_prop_args(args) end local function random_bytes_from_math_random(count) local bytes = ffi.new(ffi.typeof('uint8_t[$]', count)) for i = 0,count-1 do bytes[i] = math.random(0, 255) end return bytes end function run (args) local opts, prop_name, prop_args = parse_args(args) local rerun_usage = function (i) print(("Rerun as: snabb lwaftr quickcheck --seed=%s --iterations=%s %s %s"): format(program_name, opts.seed, i + 1, prop_name, table.concat(prop_args, " "))) end math.randomseed(opts.seed) lib.random_bytes = random_bytes_from_math_random local prop, prop_info = initialize_property(prop_name, prop_args) for i=1,opts.iterations do -- Wrap property and its arguments in a 0-arity function for xpcall. local wrap_prop = function() return prop.property(prop_info) end local propgen_ok, expected, got = xpcall(wrap_prop, debug.traceback) if not propgen_ok then print(("Crashed generating properties on run %s."):format(i)) if prop.print_extra_information then print("Attempting to print extra information; it may be wrong.") if not pcall(prop.print_extra_information) then print("Something went wrong printing extra info.") end end print("Traceback (this is reliable):") print(expected) -- This is an error code and traceback in this case. rerun_usage(i) main.exit(1) end if not utils.equals(expected, got) then print_gitrev_if_available() print("The property was falsified.") -- If the property file has extra info available, show it. if prop.print_extra_information then prop.print_extra_information() else print('Expected:') utils.pp(expected) print('Got:') utils.pp(got) end rerun_usage(i) main.exit(1) end end print(opts.iterations.." iterations succeeded.") if prop.cleanup then prop.cleanup() end end
module(...,package.seeall) local lib = require("core.lib") local utils = require("program.lwaftr.quickcheck.utils") local function show_usage(code) print(require("program.lwaftr.quickcheck.README_inc")) main.exit(code) end local function parse_args (args) local handlers = {} local opts = { iterations = 100, } function handlers.h() show_usage(0) end handlers["seed"] = function (arg) opts["seed"] = assert(tonumber(arg), "seed must be a number") end handlers["iterations"] = function (arg) opts["iterations"] = assert(tonumber(arg), "iterations must be a number") end args = lib.dogetopt(args, handlers, "h", { help="h", ["seed"] = 0, ["iterations"] = 0 }) if #args == 0 then show_usage(1) end if not opts.seed then local seed = math.floor(utils.gmtime() * 1e6) % 10^9 print("Using time as seed: "..seed) opts.seed = seed end local prop_name = table.remove(args, 1) return opts, prop_name, args end -- Due to limitations of Lua 5.1, finding if a command failed is convoluted. local function find_gitrev() local fd = io.popen('git rev-parse HEAD 2>/dev/null ; echo -n "$?"') local cmdout = fd:read("*all") fd:close() -- Always true in 5.1, with Lua or LuaJIT. local _, _, git_ret = cmdout:find("(%d+)$") git_ret = tonumber(git_ret) if git_ret ~= 0 then -- Probably not in a git repo. return nil else local _, _, sha1 = cmdout:find("(%x+)") return sha1 end end local function print_gitrev_if_available() local rev = find_gitrev() if rev then print(("Git revision %s"):format(rev)) end end local function initialize_property (name, args) local prop = require(name) if not prop.handle_prop_args then assert(#args == 0, "Property does not take options "..name) end return prop, prop.handle_prop_args(args) end local function random_bytes_from_math_random(count) local bytes = ffi.new(ffi.typeof('uint8_t[$]', count)) for i = 0,count-1 do bytes[i] = math.random(0, 255) end return bytes end function run (args) local opts, prop_name, prop_args = parse_args(args) local rerun_usage = function (i) print(("Rerun as: snabb lwaftr quickcheck --seed=%s --iterations=%s %s %s"): format(opts.seed, i + 1, prop_name, table.concat(prop_args, " "))) end math.randomseed(opts.seed) lib.random_bytes = random_bytes_from_math_random local prop, prop_info = initialize_property(prop_name, prop_args) for i=1,opts.iterations do -- Wrap property and its arguments in a 0-arity function for xpcall. local wrap_prop = function() return prop.property(prop_info) end local propgen_ok, expected, got = xpcall(wrap_prop, debug.traceback) if not propgen_ok then print(("Crashed generating properties on run %s."):format(i)) if prop.print_extra_information then print("Attempting to print extra information; it may be wrong.") if not pcall(prop.print_extra_information) then print("Something went wrong printing extra info.") end end print("Traceback (this is reliable):") print(expected) -- This is an error code and traceback in this case. rerun_usage(i) main.exit(1) end if not utils.equals(expected, got) then print_gitrev_if_available() print("The property was falsified.") -- If the property file has extra info available, show it. if prop.print_extra_information then prop.print_extra_information() else print('Expected:') utils.pp(expected) print('Got:') utils.pp(got) end rerun_usage(i) main.exit(1) end end print(opts.iterations.." iterations succeeded.") if prop.cleanup then prop.cleanup() end end
Fix failure message for lwaftr quickcheck
Fix failure message for lwaftr quickcheck
Lua
apache-2.0
alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,dpino/snabb,Igalia/snabb,dpino/snabbswitch,heryii/snabb,dpino/snabb,Igalia/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabbswitch,eugeneia/snabb,heryii/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch,dpino/snabb,dpino/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,heryii/snabb,heryii/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb,dpino/snabb,heryii/snabb,eugeneia/snabb,heryii/snabb,Igalia/snabb,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch
d59f1f50d181608046f74c896c5e56a22a63a9a6
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, template("admin_statistics/index"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "exec", "irq", "load", "memory", "processes" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local is_index = false -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, is_index = is_index } ) end
applications/luci-statistics: fix controller (#7344)
applications/luci-statistics: fix controller (#7344) git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8082 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
f4ed73818775701fac4e179107fbac36db279ee7
mods/serverguide/init.lua
mods/serverguide/init.lua
local serverguide_Book_title="The server guide" local serverguide_Tab_Text_1=[[ Server info MinetestForFun Server (hardcore) Base server (classic) of the MinetestForFun Team ]] local serverguide_Tab_Text_2= [[ 1) No intentional try to disturb the server's stability will be tolerated. 2) Cheating (hack, modified client, ...) is forbidden on this server. Be fair-play and learn to play according to the rules. 3) On the server, PVP is authorized and theft/grief as well, to the exception of public buildings. (remember to use the areas mod to protect your buildings) 4) Please do not spam or flood. 5) Each player is responsible of his/her own account, we can't be held liable for any illegitimate use of it. 6) Try to avoid 1x1 towers and overall destroying the environment, anywhere that is. This way the server will stay as beautiful, wild and natural as possible. 7) Do not ask to be a member of the server staff. 8) Swearing, racism, hate speech and the like is strictly prohibited. ]] local serverguide_Tab_Text_3= [[ Rulers info (moderator or admins) Adminitrator : Darcidride Moderators : Cyberpangolin, crabman, Mg ]] local serverguide_Tab_Text_4=[[ Commands: - /guide : show this guide ]] local serverguide_Tab_Text_5=[[ Help info Help you self Call moderators/administrator if you have questions on the server or need specific help. ]] local serverguide_Tab_1="Server" local serverguide_Tab_2="Rules" local serverguide_Tab_3="Rulers" local serverguide_Tab_4="Commands" local serverguide_Tab_5="Help" local function serverguide_guide(user,text_to_show) local text="" if text_to_show==1 then text=serverguide_Tab_Text_1 end if text_to_show==2 then text=serverguide_Tab_Text_2 end if text_to_show==3 then text=serverguide_Tab_Text_3 end if text_to_show==4 then text=serverguide_Tab_Text_4 end if text_to_show==5 then text=serverguide_Tab_Text_5 end local form="size[8.5,9]" ..default.gui_bg..default.gui_bg_img.. "button[0,0;1.5,1;tab1;" .. serverguide_Tab_1 .. "]" .. "button[1.5,0;1.5,1;tab2;" .. serverguide_Tab_2 .. "]" .. "button[3,0;1.5,1;tab3;" .. serverguide_Tab_3 .. "]" .. "button[4.5,0;1.5,1;tab4;" .. serverguide_Tab_4 .. "]" .. "button[6,0;1.5,1;tab5;" .. serverguide_Tab_5 .. "]" .. "button_exit[7.5,0; 1,1;tab6;X]" .. "label[0,1;"..text .."]" minetest.show_formspec(user:get_player_name(), "serverguide",form) end minetest.register_on_player_receive_fields(function(player, form, pressed) if form=="serverguide" then if pressed.tab1 then serverguide_guide(player,1) end if pressed.tab2 then serverguide_guide(player,2) end if pressed.tab3 then serverguide_guide(player,3) end if pressed.tab4 then serverguide_guide(player,4) end if pressed.tab5 then serverguide_guide(player,5) end end end) minetest.register_tool("serverguide:book", { description = serverguide_Book_title, inventory_image = "default_book.png", on_use = function(itemstack, user, pointed_thing) serverguide_guide(user,1) return itemstack end, on_place = function(itemstack, placer, pointed_thing) local pos = pointed_thing.under local node = minetest.get_node_or_nil(pos) local def = node and minetest.registered_nodes[node.name] if not def or not def.buildable_to then pos = pointed_thing.above node = minetest.get_node_or_nil(pos) def = node and minetest.registered_nodes[node.name] if not def or not def.buildable_to then return itemstack end end if minetest.is_protected(pos, placer:get_player_name()) then return itemstack end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) minetest.set_node(pos, {name = "serverguide:guide",param2 = fdir,}) itemstack:take_item() return itemstack end }) minetest.register_alias("guide", "serverguide:book") minetest.register_craft({output = "serverguide:book",recipe = {{"default:stick","default:stick"},}}) minetest.register_node("serverguide:guide", { description = serverguide_Book_title, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", is_ground_content = false, drop="serverguide:book", node_box = { type = "fixed", fixed = {0.35,-0.3,0.45,-0.35,-0.5,-0.45}, }, tiles = { "default_gold_block.png^default_book.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png",}, groups = {cracky=1,oddly_breakable_by_hand=3}, sounds=default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", serverguide_Book_title) end, on_rightclick = function(pos, node, clicker) serverguide_guide(clicker,1) end }) minetest.register_on_newplayer(function(player) player:get_inventory():add_item("main", "serverguide:book") end) minetest.register_chatcommand("guide", { params = "", description = serverguide_Book_title, func = function(name, param) serverguide_guide(minetest.get_player_by_name(name),1) return true end })
local serverguide_Book_title="The server guide" local serverguide_Tab_Text_1=[[ Server info MinetestForFun Server (hardcore) Base server (classic) of the MinetestForFun Team ]] local serverguide_Tab_Text_2= [[ 1) No intentional try to disturb the server's stability will be tolerated. 2) Cheating (hack, modified client, ...) is forbidden on this server. Be fair-play and learn to play according to the rules. 3) On the server, PVP is authorized and theft/grief as well, to the exception of public buildings. (remember to use the areas mod to protect your buildings) 4) Please do not spam or flood. 5) Each player is responsible of his/her own account, we can't be held liable for any illegitimate use of it. 6) Try to avoid 1x1 towers and overall destroying the environment, anywhere that is. This way the server will stay as beautiful, wild and natural as possible. 7) Do not ask to be a member of the server staff. 8) Swearing, racism, hate speech and the like is strictly prohibited. ]] local serverguide_Tab_Text_3= [[ Rulers info (moderator or admins) Adminitrator : Darcidride Moderators : Cyberpangolin, crabman, Mg ]] local serverguide_Tab_Text_4=[[ Commands: - /guide : show this guide ]] local serverguide_Tab_Text_5=[[ Help info Help you self Call moderators/administrator if you have questions on the server or need specific help. ]] local serverguide_Tab_1="Server" local serverguide_Tab_2="Rules" local serverguide_Tab_3="Rulers" local serverguide_Tab_4="Commands" local serverguide_Tab_5="Help" local function serverguide_guide(user,text_to_show) local text="" if text_to_show==1 then text=serverguide_Tab_Text_1 end if text_to_show==2 then text=serverguide_Tab_Text_2 end if text_to_show==3 then text=serverguide_Tab_Text_3 end if text_to_show==4 then text=serverguide_Tab_Text_4 end if text_to_show==5 then text=serverguide_Tab_Text_5 end local form="size[8.5,9]" ..default.gui_bg..default.gui_bg_img.. "button[0,0;1.5,1;tab1;" .. serverguide_Tab_1 .. "]" .. "button[1.5,0;1.5,1;tab2;" .. serverguide_Tab_2 .. "]" .. "button[3,0;1.5,1;tab3;" .. serverguide_Tab_3 .. "]" .. "button[4.5,0;1.5,1;tab4;" .. serverguide_Tab_4 .. "]" .. "button[6,0;1.5,1;tab5;" .. serverguide_Tab_5 .. "]" .. "button_exit[7.5,0; 1,1;tab6;X]" .. "label[0,1;"..text .."]" minetest.show_formspec(user:get_player_name(), "serverguide",form) end minetest.register_on_player_receive_fields(function(player, form, pressed) if form=="serverguide" then if pressed.tab1 then serverguide_guide(player,1) end if pressed.tab2 then serverguide_guide(player,2) end if pressed.tab3 then serverguide_guide(player,3) end if pressed.tab4 then serverguide_guide(player,4) end if pressed.tab5 then serverguide_guide(player,5) end end end) minetest.register_tool("serverguide:book", { description = serverguide_Book_title, inventory_image = "default_book.png", on_use = function(itemstack, user, pointed_thing) if pointed_thing.type == "node" then local pos = pointed_thing.under local node = minetest.get_node_or_nil(pos) local def = node and minetest.registered_nodes[node.name] if def and def.on_punch then minetest.registered_nodes[node.name].on_punch(pos, node, user, pointed_thing) return itemstack end end serverguide_guide(user,1) return itemstack end, on_place = function(itemstack, placer, pointed_thing) local pos = pointed_thing.under local node = minetest.get_node_or_nil(pos) local def = node and minetest.registered_nodes[node.name] if not def or not def.buildable_to then pos = pointed_thing.above node = minetest.get_node_or_nil(pos) def = node and minetest.registered_nodes[node.name] if not def or not def.buildable_to then return itemstack end end if minetest.is_protected(pos, placer:get_player_name()) then return itemstack end local fdir = minetest.dir_to_facedir(placer:get_look_dir()) minetest.set_node(pos, {name = "serverguide:guide",param2 = fdir,}) itemstack:take_item() return itemstack end }) minetest.register_alias("guide", "serverguide:book") minetest.register_craft({output = "serverguide:book",recipe = {{"default:stick","default:stick"},}}) minetest.register_node("serverguide:guide", { description = serverguide_Book_title, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", is_ground_content = false, drop="serverguide:book", node_box = { type = "fixed", fixed = {0.35,-0.3,0.45,-0.35,-0.5,-0.45}, }, tiles = { "default_gold_block.png^default_book.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png", "default_gold_block.png",}, groups = {cracky=1,oddly_breakable_by_hand=3}, sounds=default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", serverguide_Book_title) end, on_rightclick = function(pos, node, clicker) serverguide_guide(clicker,1) end }) minetest.register_on_newplayer(function(player) player:get_inventory():add_item("main", "serverguide:book") end) minetest.register_chatcommand("guide", { params = "", description = serverguide_Book_title, func = function(name, param) serverguide_guide(minetest.get_player_by_name(name),1) return true end })
fix use node.on_punch when node have pointed_thing (bug book guide and warps cristal)
fix use node.on_punch when node have pointed_thing (bug book guide and warps cristal)
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
5e2c3602d7b7371e30ac2dd1acf9753a7d0d0150
otouto/plugins/filterer.lua
otouto/plugins/filterer.lua
local bindings = require('otouto.bindings') local autils = require('otouto.administration') local rot13 = require('otouto.rot13') local P = {} function P:init() P.triggers = {''} P.internal = true end function P:action(msg, group, user) if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end for i = 1, #group.filter do if msg.text_lower:match(group.filter[i]) then bindings.deleteMessage{ message_id = msg.message_id, chat_id = msg.chat.id } autils.log(self, { chat_id = msg.chat.id, target = msg.from.id, action = 'Message deleted', source = P.name, reason = utilities.html_escape(rot13.cipher(group.filter[i])) }) return end end return true end P.edit_action = P.action return P
local bindings = require('otouto.bindings') local autils = require('otouto.administration') local utilities = require('otouto.utilities') local rot13 = require('otouto.rot13') local P = {} function P:init() P.triggers = {''} P.internal = true end function P:action(msg, group, user) if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end for i = 1, #group.filter do if msg.text_lower:match(group.filter[i]) then bindings.deleteMessage{ message_id = msg.message_id, chat_id = msg.chat.id } autils.log(self, { chat_id = msg.chat.id, target = msg.from.id, action = 'Message deleted', source = P.name, reason = utilities.html_escape(rot13.cipher(group.filter[i])) }) return end end return true end P.edit_action = P.action return P
bugfix filterer
bugfix filterer
Lua
agpl-3.0
topkecleon/otouto
28f0e82160fc97e105dbba608948d5dbc89c2545
core/usermanager.lua
core/usermanager.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local log = require "util.logger".init("usermanager"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local config = require "core.configmanager"; local hosts = hosts; local prosody = _G.prosody; module "usermanager" local new_default_provider; prosody.events.add_handler("host-activated", function (host) local host_session = hosts[host]; host_session.events.add_handler("item-added/auth-provider", function (provider) if config.get(host, "core", "authentication") == provider.name then host_session.users = provider; end end); host_session.events.add_handler("item-removed/auth-provider", function (provider) if host_session.users == provider then host_session.users = new_default_provider(host); end end); host_session.users = new_default_provider(host); -- Start with the default usermanager provider end); local function is_cyrus(host) return config.get(host, "core", "sasl_backend") == "cyrus"; end function new_default_provider(host) local provider = { name = "default" }; function provider.test_password(username, password) if is_cyrus(host) then return nil, "Legacy auth not supported with Cyrus SASL."; end local credentials = datamanager.load(username, host, "accounts") or {}; if password == credentials.password then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) if is_cyrus(host) then return nil, "Passwords unavailable for Cyrus SASL."; end return (datamanager.load(username, host, "accounts") or {}).password; end function provider.set_password(username, password) if is_cyrus(host) then return nil, "Passwords unavailable for Cyrus SASL."; end local account = datamanager.load(username, host, "accounts"); if account then account.password = password; return datamanager.store(username, host, "accounts", account); end return nil, "Account not available."; end function provider.user_exists(username) if is_cyrus(host) then return true; end return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials end function provider.create_user(username, password) if is_cyrus(host) then return nil, "Account creation/modification not available with Cyrus SASL."; end return datamanager.store(username, host, "accounts", {password = password}); end function provider.get_supported_methods() return {["PLAIN"] = true, ["DIGEST-MD5"] = true}; -- TODO this should be taken from the config end function provider.is_admin(jid) host = host or "*"; local admins = config.get(host, "core", "admins"); if host ~= "*" and admins == config.get("*", "core", "admins") then return nil; end if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("warn", "Option 'admins' for host '%s' is not a table", host); end return nil; end return provider; end function validate_credentials(host, username, password, method) return hosts[host].users.test_password(username, password); end function get_password(username, host) return hosts[host].users.get_password(username); end function set_password(username, host, password) return hosts[host].users.set_password(username, password); end function user_exists(username, host) return hosts[host].users.user_exists(username); end function create_user(username, password, host) return hosts[host].users.create_user(username, password); end function get_supported_methods(host) return hosts[host].users.get_supported_methods(); end function is_admin(jid, host) return hosts[host].users.is_admin(jid); end return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local datamanager = require "util.datamanager"; local log = require "util.logger".init("usermanager"); local type = type; local error = error; local ipairs = ipairs; local hashes = require "util.hashes"; local jid_bare = require "util.jid".bare; local config = require "core.configmanager"; local hosts = hosts; local prosody = _G.prosody; module "usermanager" local new_default_provider; prosody.events.add_handler("host-activated", function (host) local host_session = hosts[host]; host_session.events.add_handler("item-added/auth-provider", function (provider) if config.get(host, "core", "authentication") == provider.name then host_session.users = provider; end end); host_session.events.add_handler("item-removed/auth-provider", function (provider) if host_session.users == provider then host_session.users = new_default_provider(host); end end); host_session.users = new_default_provider(host); -- Start with the default usermanager provider end); local function is_cyrus(host) return config.get(host, "core", "sasl_backend") == "cyrus"; end function new_default_provider(host) local provider = { name = "default" }; function provider.test_password(username, password) if is_cyrus(host) then return nil, "Legacy auth not supported with Cyrus SASL."; end local credentials = datamanager.load(username, host, "accounts") or {}; if password == credentials.password then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) if is_cyrus(host) then return nil, "Passwords unavailable for Cyrus SASL."; end return (datamanager.load(username, host, "accounts") or {}).password; end function provider.set_password(username, password) if is_cyrus(host) then return nil, "Passwords unavailable for Cyrus SASL."; end local account = datamanager.load(username, host, "accounts"); if account then account.password = password; return datamanager.store(username, host, "accounts", account); end return nil, "Account not available."; end function provider.user_exists(username) if is_cyrus(host) then return true; end return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials end function provider.create_user(username, password) if is_cyrus(host) then return nil, "Account creation/modification not available with Cyrus SASL."; end return datamanager.store(username, host, "accounts", {password = password}); end function provider.get_supported_methods() return {["PLAIN"] = true, ["DIGEST-MD5"] = true}; -- TODO this should be taken from the config end function provider.is_admin(jid) local admins = config.get(host, "core", "admins"); if admins ~= config.get("*", "core", "admins") and type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("warn", "Option 'admins' for host '%s' is not a table", host); end return is_admin(jid); -- Test whether it's a global admin instead end return provider; end function validate_credentials(host, username, password, method) return hosts[host].users.test_password(username, password); end function get_password(username, host) return hosts[host].users.get_password(username); end function set_password(username, host, password) return hosts[host].users.set_password(username, password); end function user_exists(username, host) return hosts[host].users.user_exists(username); end function create_user(username, password, host) return hosts[host].users.create_user(username, password); end function get_supported_methods(host) return hosts[host].users.get_supported_methods(); end function is_admin(jid, host) if host and host ~= "*" then return hosts[host].users.is_admin(jid); else -- Test only whether this JID is a global admin local admins = config.get("*", "core", "admins"); if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("warn", "Option 'admins' for host '%s' is not a table", host); end return nil; end end return _M;
usermanager: Fix for is_admin to work with the new auth provider architecture
usermanager: Fix for is_admin to work with the new auth provider architecture
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
a226e4101d002e3f1ecbb6eb56699b5b60e86b0c
src/GR2XML.lua
src/GR2XML.lua
#!/usr/bin/env lua dataFile = "/Applications/World of Warcraft/WTF/Account/OPUSSF/SavedVariables/GoldRate.lua" function FileExists( name ) local f = io.open( name, "r" ) if f then io.close( f ) return true else return false end end function DoFile( filename ) local f = assert( loadfile( filename ) ) return f() end function PairsByKeys( t, f ) -- This is an awesome function I found local a = {} for n in pairs( t ) do table.insert( a, n ) end table.sort( a, f ) local i = 0 local iter = function() i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function Rate( realmIn, factionIn ) -- returns rate/second (slope), seconds till threshold -- this uses the least squares method to define the following equation for the data set. -- y = mx + b -- Step 0 - find the maxInitialTS to filter data maxInitialTS = 0 for name, pdata in pairs( GoldRate_data[realmIn][factionIn].toons ) do maxInitialTS = math.max( maxInitialTS, pdata.firstTS ) end -- Step 1 - Calculate the mean for both the x (timestamp) and y (gold) values local count, tsSum, goldSum = 0, 0, 0 for ts, gold in pairs(GoldRate_data[realmIn][factionIn].consolidated) do if ts >= maxInitialTS then -- only compute if the data fits the TS range --tsSum = tsSum + (ts - GoldRate.maxInitialTS) tsSum = tsSum + ts goldSum = goldSum + gold count = count + 1 end end if count > 1 then local tsAve = tsSum / count local goldAve = goldSum / count -- Step 2 -- m (slope) = sum( (Xi - Xave) * (Yi - Yave) ) -- -------------------------------- -- sum( (Xi - Xave)^2 ) local xySum, x2Sum = 0, 0 for ts, gold in pairs(GoldRate_data[realmIn][factionIn].consolidated) do -- yes, 2nd loop through data if ts >= maxInitialTS then -- only compute if the data fits the TS range --xySum = xySum + ((ts - GoldRate.maxInitialTS) - tsAve) * (gold - goldAve) --x2Sum = x2Sum + math.pow((ts - GoldRate.maxInitialTS) - tsAve, 2) xySum = xySum + (ts - tsAve) * (gold - goldAve) x2Sum = x2Sum + math.pow(ts - tsAve, 2) end end local m = xySum / x2Sum -- Step 3 -- Calculate the y-intercept. b = Yave - ( m * xAve ) --local b = (tsAve + GoldRate.maxInitialTS) - ( m * goldAve ) local b = goldAve - ( m * tsAve ) -- Final Step -- Use the data to solve for TS at Gold Value -- x = ( y - b ) / m local targetTS = GoldRate_data[realmIn][factionIn].goal and (( GoldRate_data[realmIn][factionIn].goal - b ) / m ) or 0 return m, targetTS end return 0, 0 end if FileExists( dataFile ) then DoFile( dataFile ) if GoldRate_data then strOut = "<?xml version='1.0' encoding='utf-8' ?>\n" strOut = strOut .. "<goldRate>\n" strOut = strOut .. "<graphAgeDays>"..GoldRate_options.graphAgeDays.."</graphAgeDays>" for realm, rdata in pairs( GoldRate_data ) do maxInitialTS = 0 for faction, fdata in pairs( rdata ) do m, targetTS = Rate(realm, faction) strOut = strOut .. string.format( '<rf realm="%s" faction="%s">\n', realm, faction ) if fdata.goal then strOut = strOut .. string.format( "\t<goal>%i</goal>\n", fdata.goal ) end for name, pdata in pairs( fdata.toons ) do maxInitialTS = math.max( maxInitialTS, pdata.firstTS) end if fdata.consolidated then for ts, val in PairsByKeys( fdata.consolidated ) do if ts >= maxInitialTS and ts >= (os.time() - (GoldRate_options.graphAgeDays * 86400)) then strOut = strOut .. string.format( '\t<value ts="%i">%i</value>\n', ts, val ) end end end --[[ if GoldRate_data[realm][faction].goal then strOut = strOut .. string.format("%s,%s,%s,%i,%i,target\n", realm, faction, os.date( "%x %X", targetTS), targetTS, GoldRate_data[realm][faction].goal ) end ]] strOut = strOut .. "</rf>\n" end end strOut = strOut .. "</goldRate>\n" print(strOut) end end
#!/usr/bin/env lua dataFile = "/Applications/World of Warcraft/WTF/Account/OPUSSF/SavedVariables/GoldRate.lua" function FileExists( name ) local f = io.open( name, "r" ) if f then io.close( f ) return true else return false end end function DoFile( filename ) local f = assert( loadfile( filename ) ) return f() end function PairsByKeys( t, f ) -- This is an awesome function I found local a = {} for n in pairs( t ) do table.insert( a, n ) end table.sort( a, f ) local i = 0 local iter = function() i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function Rate( realmIn, factionIn ) -- returns rate/second (slope), seconds till threshold -- this uses the least squares method to define the following equation for the data set. -- y = mx + b -- Step 0 - find the maxInitialTS to filter data maxInitialTS = 0 for name, pdata in pairs( GoldRate_data[realmIn][factionIn].toons ) do maxInitialTS = math.max( maxInitialTS, pdata.firstTS ) end -- Step 1 - Calculate the mean for both the x (timestamp) and y (gold) values local count, tsSum, goldSum = 0, 0, 0 for ts, gold in pairs(GoldRate_data[realmIn][factionIn].consolidated) do if ts >= maxInitialTS then -- only compute if the data fits the TS range --tsSum = tsSum + (ts - GoldRate.maxInitialTS) tsSum = tsSum + ts goldSum = goldSum + gold count = count + 1 end end if count > 1 then local tsAve = tsSum / count local goldAve = goldSum / count -- Step 2 -- m (slope) = sum( (Xi - Xave) * (Yi - Yave) ) -- -------------------------------- -- sum( (Xi - Xave)^2 ) local xySum, x2Sum = 0, 0 for ts, gold in pairs(GoldRate_data[realmIn][factionIn].consolidated) do -- yes, 2nd loop through data if ts >= maxInitialTS then -- only compute if the data fits the TS range --xySum = xySum + ((ts - GoldRate.maxInitialTS) - tsAve) * (gold - goldAve) --x2Sum = x2Sum + math.pow((ts - GoldRate.maxInitialTS) - tsAve, 2) xySum = xySum + (ts - tsAve) * (gold - goldAve) x2Sum = x2Sum + math.pow(ts - tsAve, 2) end end local m = xySum / x2Sum -- Step 3 -- Calculate the y-intercept. b = Yave - ( m * xAve ) --local b = (tsAve + GoldRate.maxInitialTS) - ( m * goldAve ) local b = goldAve - ( m * tsAve ) -- Final Step -- Use the data to solve for TS at Gold Value -- x = ( y - b ) / m local targetTS = GoldRate_data[realmIn][factionIn].goal and (( GoldRate_data[realmIn][factionIn].goal - b ) / m ) or 0 return m, targetTS end end if FileExists( dataFile ) then DoFile( dataFile ) if GoldRate_data then strOut = "<?xml version='1.0' encoding='utf-8' ?>\n" strOut = strOut .. "<goldRate>\n" strOut = strOut .. "<graphAgeDays>"..GoldRate_options.graphAgeDays.."</graphAgeDays>" for realm, rdata in pairs( GoldRate_data ) do maxInitialTS = 0 for faction, fdata in pairs( rdata ) do m, targetTS = Rate(realm, faction) strOut = strOut .. string.format( '<rf realm="%s" faction="%s">\n', realm, faction ) if fdata.goal and targetTS then strOut = strOut .. string.format( '\t<goal ts="%i">%i</goal>\n', targetTS, fdata.goal ) end for name, pdata in pairs( fdata.toons ) do maxInitialTS = math.max( maxInitialTS, pdata.firstTS) end if fdata.consolidated then for ts, val in PairsByKeys( fdata.consolidated ) do if ts >= maxInitialTS and ts >= (os.time() - (GoldRate_options.graphAgeDays * 86400)) then strOut = strOut .. string.format( '\t<value ts="%i">%i</value>\n', ts, val ) end end end --[[ if GoldRate_data[realm][faction].goal then strOut = strOut .. string.format("%s,%s,%s,%i,%i,target\n", realm, faction, os.date( "%x %X", targetTS), targetTS, GoldRate_data[realm][faction].goal ) end ]] strOut = strOut .. "</rf>\n" end end strOut = strOut .. "</goldRate>\n" print(strOut) end end
Bug fix for XML geneartion
Bug fix for XML geneartion
Lua
mit
opussf/GoldRate,opussf/GoldRate
702e6051ef1b8a8a638a785df1879f50e0b8c157
triggerfield/base/donation.lua
triggerfield/base/donation.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local character = require("base.character") local common = require("base.common") local money = require("base.money") local townTreasure = require("base.townTreasure") local M = {} function M.donate(Item,User,FactionName,LeaderName,Treasury) -- This function donates 10% of the worth of an item to the faction ItemStats=world:getItemStats(Item); -- get the item stats if ItemStats.Worth == 0 then -- worthless item -> inform common.InformNLS(User,"[Spende] Dieser Gegenstand ist wertlos.","[Donation] This item is worthless."); -- Feedback! donated=false; -- no donation elseif Item.id == 97 or Item.id == 799 then --Bags and baskets cannot be donated as the content of containers cannot be evaluated. common.InformNLS(User,"[Spende] Taschen und Krbe knnen nicht gespendet werden.","[Donation] Bags and baskets cannot be donated."); -- Feedback! donated=false; -- no donation else -- item with worth if Item.id == 61 or Item.id == 3076 or Item.id == 3077 then -- coins payToFaction = Item.number*ItemStats.Worth; -- 100% of the worth are added for coins else payToFaction = Item.number*ItemStats.Worth*0.1; -- 10% of the worth are added for items end townTreasure.ChangeTownTreasure(FactionName,payToFaction) gstring,estring=money.MoneyToString(payToFaction); --converting money to a string common.InformNLS(User,"[Spende] Du spendest Gegenstnde im Gegenwert von"..gstring.." in die Schatzkammer von "..FactionName..". "..LeaderName.." wird zufrieden sein.","[Donation] You donate items valued at"..estring.." to the treasury of "..FactionName..". "..LeaderName.." will be pleased."); -- Feedback! log(string.format("[Donation] %s donated %u %s (%u). Faction wealth of %s increased by %d copper to %d copper.", character.LogText(User), Item.number, world:getItemName(Item.id,Player.english), Item.id, FactionName, payToFaction, townTreasure.GetTownTreasure(FactionName))); world:gfx(46,Item.pos); -- nice GFX world:erase(Item,Item.number); -- delete the item donated=true; -- donation worked end return donated; -- returning whether the donation worked or not 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/>. ]] local character = require("base.character") local common = require("base.common") local money = require("base.money") local townTreasure = require("base.townTreasure") local M = {} function M.donate(Item, User, FactionName, LeaderName, Treasury) -- This function donates 10% of the worth of an item to the faction local donated local ItemStats = world:getItemStats(Item) if ItemStats.Worth == 0 then -- worthless item -> inform common.InformNLS(User, "[Spende] Dieser Gegenstand ist wertlos.", "[Donation] This item is worthless.") -- Feedback! donated = false -- no donation elseif Item.id == 97 or Item.id == 799 then --Bags and baskets cannot be donated as the content of containers cannot be evaluated. common.InformNLS(User, "[Spende] Taschen und Krbe knnen nicht gespendet werden.", "[Donation] Bags and baskets cannot be donated.") -- Feedback! donated = false -- no donation else -- item with worth local payToFaction if Item.id == 61 or Item.id == 3076 or Item.id == 3077 then -- coins payToFaction = Item.number * ItemStats.Worth -- 100% of the worth are added for coins else payToFaction = Item.number * ItemStats.Worth * 0.1 -- 10% of the worth are added for items end townTreasure.ChangeTownTreasure(FactionName, payToFaction) local gstring, estring = money.MoneyToString(payToFaction) --converting money to a string common.InformNLS(User, "[Spende] Du spendest Gegenstnde im Gegenwert von"..gstring.." in die Schatzkammer von "..FactionName..". "..LeaderName.." wird zufrieden sein.", "[Donation] You donate items valued at"..estring.." to the treasury of "..FactionName..". "..LeaderName.." will be pleased.") -- Feedback! log(string.format("[Donation] %s donated %u %s (%u). Faction wealth of %s increased by %d copper to %d copper.", character.LogText(User), Item.number, world:getItemName(Item.id,Player.english), Item.id, FactionName, payToFaction, townTreasure.GetTownTreasure(FactionName))) world:gfx(46, Item.pos) -- nice GFX world:erase(Item, Item.number) -- delete the item donated = true -- donation worked end return donated -- returning whether the donation worked or not end return M
style fixes
style fixes
Lua
agpl-3.0
LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
c59d84aadc45f4fd93860f2fb1b483936dc9f1bc
AceLocale-3.0/AceLocale-3.0.lua
AceLocale-3.0/AceLocale-3.0.lua
--- **AceLocale-3.0** manages localization in addons, allowing for multiple locale to be registered with fallback to the base locale for untranslated strings. -- @class file -- @name AceLocale-3.0 -- @release $Id$ local MAJOR,MINOR = "AceLocale-3.0", 2 local AceLocale, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceLocale then return end -- no upgrade needed -- Lua APIs local assert, tostring, error = assert, tostring, error local setmetatable, rawset, rawget = setmetatable, rawset, rawget -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GAME_LOCALE, geterrorhandler local gameLocale = GetLocale() if gameLocale == "enGB" then gameLocale = "enUS" end AceLocale.apps = AceLocale.apps or {} -- array of ["AppName"]=localetableref AceLocale.appnames = AceLocale.appnames or {} -- array of [localetableref]="AppName" -- This metatable is used on all tables returned from GetLocale local readmeta = { __index = function(self, key) -- requesting totally unknown entries: fire off a nonbreaking error and return key rawset(self, key, key) -- only need to see the warning once, really geterrorhandler()(MAJOR..": "..tostring(AceLocale.appnames[self])..": Missing entry for '"..tostring(key).."'") return key end } -- This metatable is used on all tables returned from GetLocale if the silent flag is true, it does not issue a warning on unknown keys local readmetasilent = { __index = function(self, key) -- requesting totally unknown entries: return key rawset(self, key, key) -- only need to invoke this function once return key end } -- Remember the locale table being registered right now (it gets set by :NewLocale()) -- NOTE: Do never try to register 2 locale tables at once and mix their definition. local registering -- local assert false function local assertfalse = function() assert(false) end -- This metatable proxy is used when registering nondefault locales local writeproxy = setmetatable({}, { __newindex = function(self, key, value) rawset(registering, key, value == true and key or value) -- assigning values: replace 'true' with key string end, __index = assertfalse }) -- This metatable proxy is used when registering the default locale. -- It refuses to overwrite existing values -- Reason 1: Allows loading locales in any order -- Reason 2: If 2 modules have the same string, but only the first one to be -- loaded has a translation for the current locale, the translation -- doesn't get overwritten. -- local writedefaultproxy = setmetatable({}, { __newindex = function(self, key, value) if not rawget(registering, key) then rawset(registering, key, value == true and key or value) end end, __index = assertfalse }) --- Register a new locale (or extend an existing one) for the specified application. -- :NewLocale will return a table you can fill your locale into, or nil if the locale isn't needed for the players -- game locale. -- @paramsig application, locale[, isDefault[, silent]] -- @param application Unique name of addon / module -- @param locale Name of the locale to register, e.g. "enUS", "deDE", etc. -- @param isDefault If this is the default locale being registered (your addon is written in this language, generally enUS) -- @param silent If true, the locale will not issue warnings for missing keys. Can only be set on the default locale. -- @usage -- -- enUS.lua -- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "enUS", true) -- L["string1"] = true -- -- -- deDE.lua -- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "deDE") -- if not L then return end -- L["string1"] = "Zeichenkette1" -- @return Locale Table to add localizations to, or nil if the current locale is not required. function AceLocale:NewLocale(application, locale, isDefault, silent) if silent and not isDefault then error("Usage: NewLocale(application, locale[, isDefault[, silent]]): 'silent' can only be specified for the default locale", 2) end -- GAME_LOCALE allows translators to test translations of addons without having that wow client installed -- Ammo: I still think this is a bad idea, for instance an addon that checks for some ingame string will fail, just because some other addon -- gives the user the illusion that they can run in a different locale? Ditch this whole thing or allow a setting per 'application'. I'm of the -- opinion to remove this. local gameLocale = GAME_LOCALE or gameLocale if locale ~= gameLocale and not isDefault then return -- nop, we don't need these translations end local app = AceLocale.apps[application] if not app then app = setmetatable({}, silent and readmetasilent or readmeta) AceLocale.apps[application] = app AceLocale.appnames[app] = application end registering = app -- remember globally for writeproxy and writedefaultproxy if isDefault then return writedefaultproxy end return writeproxy end --- Returns localizations for the current locale (or default locale if translations are missing). -- Errors if nothing is registered (spank developer, not just a missing translation) -- @param application Unique name of addon / module -- @param silent If true, the locale is optional, silently return nil if it's not found (defaults to false, optional) -- @return The locale table for the current language. function AceLocale:GetLocale(application, silent) if not silent and not AceLocale.apps[application] then error("Usage: GetLocale(application[, silent]): 'application' - No locales registered for '"..tostring(application).."'", 2) end return AceLocale.apps[application] end
--- **AceLocale-3.0** manages localization in addons, allowing for multiple locale to be registered with fallback to the base locale for untranslated strings. -- @class file -- @name AceLocale-3.0 -- @release $Id$ local MAJOR,MINOR = "AceLocale-3.0", 3 local AceLocale, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceLocale then return end -- no upgrade needed -- Lua APIs local assert, tostring, error = assert, tostring, error local setmetatable, rawset, rawget = setmetatable, rawset, rawget -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GAME_LOCALE, geterrorhandler local gameLocale = GetLocale() if gameLocale == "enGB" then gameLocale = "enUS" end AceLocale.apps = AceLocale.apps or {} -- array of ["AppName"]=localetableref AceLocale.appnames = AceLocale.appnames or {} -- array of [localetableref]="AppName" -- This metatable is used on all tables returned from GetLocale local readmeta = { __index = function(self, key) -- requesting totally unknown entries: fire off a nonbreaking error and return key rawset(self, key, key) -- only need to see the warning once, really geterrorhandler()(MAJOR..": "..tostring(AceLocale.appnames[self])..": Missing entry for '"..tostring(key).."'") return key end } -- This metatable is used on all tables returned from GetLocale if the silent flag is true, it does not issue a warning on unknown keys local readmetasilent = { __index = function(self, key) -- requesting totally unknown entries: return key rawset(self, key, key) -- only need to invoke this function once return key end } -- Remember the locale table being registered right now (it gets set by :NewLocale()) -- NOTE: Do never try to register 2 locale tables at once and mix their definition. local registering -- local assert false function local assertfalse = function() assert(false) end -- This metatable proxy is used when registering nondefault locales local writeproxy = setmetatable({}, { __newindex = function(self, key, value) rawset(registering, key, value == true and key or value) -- assigning values: replace 'true' with key string end, __index = assertfalse }) -- This metatable proxy is used when registering the default locale. -- It refuses to overwrite existing values -- Reason 1: Allows loading locales in any order -- Reason 2: If 2 modules have the same string, but only the first one to be -- loaded has a translation for the current locale, the translation -- doesn't get overwritten. -- local writedefaultproxy = setmetatable({}, { __newindex = function(self, key, value) if not rawget(registering, key) then rawset(registering, key, value == true and key or value) end end, __index = assertfalse }) --- Register a new locale (or extend an existing one) for the specified application. -- :NewLocale will return a table you can fill your locale into, or nil if the locale isn't needed for the players -- game locale. -- @paramsig application, locale[, isDefault[, silent]] -- @param application Unique name of addon / module -- @param locale Name of the locale to register, e.g. "enUS", "deDE", etc. -- @param isDefault If this is the default locale being registered (your addon is written in this language, generally enUS) -- @param silent If true, the locale will not issue warnings for missing keys. Must be set on the first locale registered. If set to "raw", nils will be returned for unknown keys (no metatable used). -- @usage -- -- enUS.lua -- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "enUS", true) -- L["string1"] = true -- -- -- deDE.lua -- local L = LibStub("AceLocale-3.0"):NewLocale("TestLocale", "deDE") -- if not L then return end -- L["string1"] = "Zeichenkette1" -- @return Locale Table to add localizations to, or nil if the current locale is not required. function AceLocale:NewLocale(application, locale, isDefault, silent) -- GAME_LOCALE allows translators to test translations of addons without having that wow client installed local gameLocale = GAME_LOCALE or gameLocale local app = AceLocale.apps[application] if silent and app then error("Usage: NewLocale(application, locale[, isDefault[, silent]]): 'silent' must be specified for the first locale registered", 2) end if not app then if silent=="raw" then app = {} else app = setmetatable({}, silent and readmetasilent or readmeta) end AceLocale.apps[application] = app AceLocale.appnames[app] = application end if locale ~= gameLocale and not isDefault then return -- nop, we don't need these translations end registering = app -- remember globally for writeproxy and writedefaultproxy if isDefault then return writedefaultproxy end return writeproxy end --- Returns localizations for the current locale (or default locale if translations are missing). -- Errors if nothing is registered (spank developer, not just a missing translation) -- @param application Unique name of addon / module -- @param silent If true, the locale is optional, silently return nil if it's not found (defaults to false, optional) -- @return The locale table for the current language. function AceLocale:GetLocale(application, silent) if not silent and not AceLocale.apps[application] then error("Usage: GetLocale(application[, silent]): 'application' - No locales registered for '"..tostring(application).."'", 2) end return AceLocale.apps[application] end
- Fix erronous assumption that the default locale is always the first to be registered for the :NewLocale() "silent" flag. The flag must now be set on the FIRST locale to be registered. - The :NewLocale() "silent" flag may now be set to the string "raw", meaning nils are returned for unknown translations.
- Fix erronous assumption that the default locale is always the first to be registered for the :NewLocale() "silent" flag. The flag must now be set on the FIRST locale to be registered. - The :NewLocale() "silent" flag may now be set to the string "raw", meaning nils are returned for unknown translations. git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@1000 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
bbad1720c3e309a5fe85c5eca451b3182a5ca950
hammerspoon/hammerspoon.symlink/init.lua
hammerspoon/hammerspoon.symlink/init.lua
-- Load Extensions require("luarocks.loader") local application = require "hs.application" local window = require "hs.window" local hotkey = require "hs.hotkey" local keycodes = require "hs.keycodes" local fnutils = require "hs.fnutils" local alert = require "hs.alert" local screen = require "hs.screen" local grid = require "hs.grid" local hints = require "hs.hints" local timer = require "hs.timer" local appfinder = require "hs.appfinder" local applescript = require "hs.applescript" local eventtap = require "hs.eventtap" -- local popclick = require "hs.noises" local popclick = require "thume.popclick" local tabs = require "tabs" local definitions = nil local hyper = nil local hyper2 = nil local gridset = function(frame) return function() local win = window.focusedWindow() if win then grid.set(win, frame, win:screen()) else alert.show("No focused window.") end end end auxWin = nil function saveFocus() auxWin = window.focusedWindow() alert.show("Window '" .. auxWin:title() .. "' saved.") end function focusSaved() if auxWin then auxWin:focus() end end local hotkeys = {} function createHotkeys() for key, fun in pairs(definitions) do local mod = hyper if string.len(key) == 2 and string.sub(key,2,2) == "c" then mod = {"cmd"} elseif string.len(key) == 2 and string.sub(key,2,2) == "l" then mod = {"ctrl"} end local hk = hotkey.new(mod, string.sub(key,1,1), fun) table.insert(hotkeys, hk) hk:enable() end end function rebindHotkeys() for i, hk in ipairs(hotkeys) do hk:disable() end hotkeys = {} createHotkeys() alert.show("Rebound Hotkeys") end function applyPlace(win, place) local scrs = screen.allScreens() local scr = scrs[place[1]] grid.set(win, place[2], scr) end function applyLayout(layout) return function() for appName, place in pairs(layout) do local app = appfinder.appFromName(appName) if app then for i, win in ipairs(app:allWindows()) do applyPlace(win, place) end end end end end listener = nil popclickListening = false local scrollDownTimer = nil function popclickHandler(evNum) -- alert.show(tostring(evNum)) if evNum == 1 then scrollDownTimer:start() elseif evNum == 2 then scrollDownTimer:stop() elseif evNum == 3 then if application.frontmostApplication():name() == "ReadKit" then eventtap.keyStroke({}, "j") else eventtap.scrollWheel({0,250},{}, "pixel") end end end function popclickPlayPause() if not popclickListening then listener:start() alert.show("listening") else listener:stop() alert.show("stopped listening") end popclickListening = not popclickListening end local function wrap(fn) return function(...) if fn then local ok, err = xpcall(fn, debug.traceback, ...) if not ok then hs.showerror(err) end end end end function popclickInit() popclickListening = false -- local fn = wrap(popclickHandler) local fn = popclickHandler listener = popclick.new(fn) scrollDownTimer = timer.new(0.02, function() eventtap.scrollWheel({0,-10},{}, "pixel") end) end function init() createHotkeys() popclickInit() -- keycodes.inputSourceChanged(rebindHotkeys) tabs.enableForApp("Emacs") -- tabs.enableForApp("Atom") tabs.enableForApp("Sublime Text") alert.show("Hammerspoon, at your service.") end -- Actual config ================================= hyper = {"cmd", "alt", "ctrl","shift"} hyper2 = {"ctrl"} hs.window.animationDuration = 0; -- hints.style = "vimperator" -- Set grid size. grid.GRIDWIDTH = 6 grid.GRIDHEIGHT = 8 grid.MARGINX = 0 grid.MARGINY = 0 local gw = grid.GRIDWIDTH local gh = grid.GRIDHEIGHT local gomiddle = {x = 1, y = 1, w = 4, h = 6} local goleft = {x = 0, y = 0, w = gw/2, h = gh} local goright = {x = gw/2, y = 0, w = gw/2, h = gh} local gobig = {x = 0, y = 0, w = gw, h = gh} local fullApps = { "Safari","Aurora","Nightly","Xcode","Qt Creator","Google Chrome","Papers 3.4.2", "Google Chrome Canary", "Eclipse", "Coda 2", "iTunes", "Emacs", "Firefox", "Sublime Text" } local layout2 = { Airmail = {1, gomiddle}, Spotify = {1, gomiddle}, Calendar = {1, gomiddle}, Messenger = {1, gomiddle}, Messages = {1, gomiddle}, Dash = {1, gomiddle}, iTerm = {2, goright}, MacRanger = {2, goleft}, ["Path Finder"] = {2, goleft}, Mail = {2, goright}, } fnutils.each(fullApps, function(app) layout2[app] = {1, gobig} end) local layout2fn = applyLayout(layout2) screen.watcher.new(function() if #(screen.allScreens()) > 1 then timer.doAfter(3, function() layout2fn() end) end end):start() definitions = { [";"] = saveFocus, a = focusSaved, h = gridset(gomiddle), t = gridset(goleft), n = grid.maximizeWindow, s = gridset(goright), g = layout2fn, d = grid.pushWindowNextScreen, -- r = hs.reload, q = function() appfinder.appFromName("Hammerspoon"):kill() end, l = popclickPlayPause, k = function() hints.windowHints(appfinder.appFromName("Sublime Text"):allWindows()) end, j = function() hints.windowHints(window.focusedWindow():application():allWindows()) end, -- rl = function() hyper, hyper2 = hyper2,hyper; rebindHotkeys() end, ec = function() hints.windowHints(nil) end } -- launch and focus applications fnutils.each({ { key = "o", app = "Path Finder" }, { key = "e", app = "Google Chrome" }, { key = "u", app = "Sublime Text" }, { key = "i", app = "iTerm2" }, { key = "x", app = "Xcode" }, { key = "m", app = "Mail" }, { key = "p", app = "Messenger" }, }, function(object) definitions[object.key] = function() local app = appfinder.appFromName(object.app) if app then app:activate() end end end) for i=1,6 do definitions[tostring(i)] = function() local app = application.frontmostApplication() tabs.focusTab(app,i) end end init()
-- Load Extensions require("luarocks.loader") local application = require "hs.application" local window = require "hs.window" local hotkey = require "hs.hotkey" local keycodes = require "hs.keycodes" local fnutils = require "hs.fnutils" local alert = require "hs.alert" local screen = require "hs.screen" local grid = require "hs.grid" local hints = require "hs.hints" local timer = require "hs.timer" local appfinder = require "hs.appfinder" local applescript = require "hs.applescript" local eventtap = require "hs.eventtap" local popclick = require "hs.noises" -- local popclick = require "thume.popclick" local tabs = require "tabs" local definitions = nil local hyper = nil local hyper2 = nil local gridset = function(frame) return function() local win = window.focusedWindow() if win then grid.set(win, frame, win:screen()) else alert.show("No focused window.") end end end auxWin = nil function saveFocus() auxWin = window.focusedWindow() alert.show("Window '" .. auxWin:title() .. "' saved.") end function focusSaved() if auxWin then auxWin:focus() end end local hotkeys = {} function createHotkeys() for key, fun in pairs(definitions) do local mod = hyper if string.len(key) == 2 and string.sub(key,2,2) == "c" then mod = {"cmd"} elseif string.len(key) == 2 and string.sub(key,2,2) == "l" then mod = {"ctrl"} end local hk = hotkey.new(mod, string.sub(key,1,1), fun) table.insert(hotkeys, hk) hk:enable() end end function rebindHotkeys() for i, hk in ipairs(hotkeys) do hk:disable() end hotkeys = {} createHotkeys() alert.show("Rebound Hotkeys") end function applyPlace(win, place) local scrs = screen.allScreens() local scr = scrs[place[1]] grid.set(win, place[2], scr) end function applyLayout(layout) return function() for appName, place in pairs(layout) do local app = appfinder.appFromName(appName) if app then for i, win in ipairs(app:allWindows()) do applyPlace(win, place) end end end end end listener = nil popclickListening = false local scrollDownTimer = nil function popclickHandler(evNum) -- alert.show(tostring(evNum)) if evNum == 1 then scrollDownTimer = timer.doEvery(0.02, function() eventtap.scrollWheel({0,-10},{}, "pixel") end) elseif evNum == 2 then if scrollDownTimer then scrollDownTimer:stop() scrollDownTimer = nil end elseif evNum == 3 then if application.frontmostApplication():name() == "ReadKit" then eventtap.keyStroke({}, "j") else eventtap.scrollWheel({0,250},{}, "pixel") end end end function popclickPlayPause() if not popclickListening then listener:start() alert.show("listening") else listener:stop() alert.show("stopped listening") end popclickListening = not popclickListening end local function wrap(fn) return function(...) if fn then local ok, err = xpcall(fn, debug.traceback, ...) if not ok then hs.showerror(err) end end end end function popclickInit() popclickListening = false -- local fn = wrap(popclickHandler) local fn = popclickHandler listener = popclick.new(fn) end function init() createHotkeys() popclickInit() -- keycodes.inputSourceChanged(rebindHotkeys) -- tabs.enableForApp("Emacs") -- tabs.enableForApp("Atom") tabs.enableForApp("Sublime Text") alert.show("Hammerspoon, at your service.") end -- Actual config ================================= hyper = {"cmd", "alt", "ctrl","shift"} hyper2 = {"ctrl"} hs.window.animationDuration = 0; -- hints.style = "vimperator" -- Set grid size. grid.GRIDWIDTH = 6 grid.GRIDHEIGHT = 8 grid.MARGINX = 0 grid.MARGINY = 0 local gw = grid.GRIDWIDTH local gh = grid.GRIDHEIGHT local gomiddle = {x = 1, y = 1, w = 4, h = 6} local goleft = {x = 0, y = 0, w = gw/2, h = gh} local goright = {x = gw/2, y = 0, w = gw/2, h = gh} local gobig = {x = 0, y = 0, w = gw, h = gh} local fullApps = { "Safari","Aurora","Nightly","Xcode","Qt Creator","Google Chrome","Papers 3.4.2", "Google Chrome Canary", "Eclipse", "Coda 2", "iTunes", "Emacs", "Firefox", "Sublime Text" } local layout2 = { Airmail = {1, gomiddle}, Spotify = {1, gomiddle}, Calendar = {1, gomiddle}, Messenger = {1, gomiddle}, Messages = {1, gomiddle}, Dash = {1, gomiddle}, iTerm = {2, goright}, MacRanger = {2, goleft}, ["Path Finder"] = {2, goleft}, Mail = {2, goright}, } fnutils.each(fullApps, function(app) layout2[app] = {1, gobig} end) local layout2fn = applyLayout(layout2) screen.watcher.new(function() if #(screen.allScreens()) > 1 then timer.doAfter(3, function() layout2fn() end) end end):start() definitions = { [";"] = saveFocus, a = focusSaved, h = gridset(gomiddle), t = gridset(goleft), n = grid.maximizeWindow, s = gridset(goright), g = layout2fn, d = grid.pushWindowNextScreen, -- r = hs.reload, q = function() appfinder.appFromName("Hammerspoon"):kill() end, l = popclickPlayPause, k = function() hints.windowHints(appfinder.appFromName("Sublime Text"):allWindows()) end, j = function() hints.windowHints(window.focusedWindow():application():allWindows()) end, -- rl = function() hyper, hyper2 = hyper2,hyper; rebindHotkeys() end, ec = function() hints.windowHints(nil) end } -- launch and focus applications fnutils.each({ { key = "o", app = "Path Finder" }, { key = "e", app = "Google Chrome" }, { key = "u", app = "Sublime Text" }, { key = "i", app = "iTerm2" }, { key = "x", app = "Xcode" }, { key = "m", app = "Mail" }, { key = "p", app = "Messenger" }, }, function(object) definitions[object.key] = function() local app = appfinder.appFromName(object.app) if app then app:activate() end end end) for i=1,6 do definitions[tostring(i)] = function() local app = application.frontmostApplication() tabs.focusTab(app,i) end end init()
fix tss scrolling
fix tss scrolling
Lua
mit
trishume/dotfiles,trishume/dotfiles,trishume/dotfiles,trishume/dotfiles
36a48f283a68c3f95cab2e4250fb09155a64d406
tests/build.lua
tests/build.lua
-- main entry function main(argv) -- generic? os.exec("$(xmake) m -b") os.exec("$(xmake) f -c") os.exec("$(xmake)") if os.host() ~= "windows" then os.exec("sudo $(xmake) install") os.exec("sudo $(xmake) uninstall") end os.exec("$(xmake) p") os.exec("$(xmake) c") os.exec("$(xmake) f -m release") os.exec("$(xmake) -r -a -v --backtrace") if os.host() ~= "windows" then os.exec("sudo $(xmake) install --all -v --backtrace") os.exec("sudo $(xmake) uninstall -v --backtrace") end os.exec("$(xmake) f --mode=debug --verbose --backtrace") os.exec("$(xmake) --rebuild --all --verbose --backtrace") if os.host() ~= "windows" then os.exec("$(xmake) install -o /tmp -a --verbose --backtrace") os.exec("$(xmake) uninstall --installdir=/tmp --verbose --backtrace") end os.exec("$(xmake) p --verbose --backtrace") os.exec("$(xmake) c --verbose --backtrace") os.exec("$(xmake) m -e buildtest") os.exec("$(xmake) m -l") os.exec("$(xmake) f --cc=gcc --cxx=g++") os.exec("$(xmake) m buildtest") os.exec("$(xmake) f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace") os.exec("$(xmake) m buildtest") os.exec("$(xmake) m -d buildtest") -- test iphoneos? if argv and argv.iphoneos then if os.host() == "macosx" then os.exec("$(xmake) m package -p iphoneos") end end end
-- main entry function main(argv) -- generic? os.exec("$(xmake) m -b") os.exec("$(xmake) f -c") os.exec("$(xmake)") if os.host() ~= "windows" then os.exec("$(xmake) install -o /tmp -a --verbose --backtrace") os.exec("$(xmake) uninstall --installdir=/tmp --verbose --backtrace") end os.exec("$(xmake) p") os.exec("$(xmake) c") os.exec("$(xmake) f -m release") os.exec("$(xmake) -r -a -v --backtrace") os.exec("$(xmake) f --mode=debug --verbose --backtrace") os.exec("$(xmake) --rebuild --all --verbose --backtrace") os.exec("$(xmake) p --verbose --backtrace") os.exec("$(xmake) c --verbose --backtrace") os.exec("$(xmake) m -e buildtest") os.exec("$(xmake) m -l") os.exec("$(xmake) f --cc=gcc --cxx=g++") os.exec("$(xmake) m buildtest") if os.host() ~= "windows" then os.exec("sudo $(xmake) install") os.exec("sudo $(xmake) uninstall") end os.exec("$(xmake) f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace") os.exec("$(xmake) m buildtest") if os.host() ~= "windows" then os.exec("sudo $(xmake) install --all -v --backtrace") os.exec("sudo $(xmake) uninstall -v --backtrace") end os.exec("$(xmake) m -d buildtest") -- test iphoneos? if argv and argv.iphoneos then if os.host() == "macosx" then os.exec("$(xmake) m package -p iphoneos") end end end
fix tests
fix tests
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
eaa204eae962a881213db3837b7ee0c3c960e39d
kong/cmd/config.lua
kong/cmd/config.lua
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local pl_path = require "pl.path" local pl_file = require "pl.file" local kong_global = require "kong.global" local declarative = require "kong.db.declarative" local conf_loader = require "kong.conf_loader" local kong_yml = require "kong.templates.kong_yml" local INIT_FILE = "kong.yml" local accepted_formats = { yaml = true, json = true, lua = true, } local function db_export(filename, conf) if pl_file.access_time(filename) then error(filename .. " already exists. Will not overwrite it.") end _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db local fd, err = io.open(filename, "w") if not fd then return nil, err end local ok, err = declarative.export_from_db(fd) if not ok then error(err) end fd:close() os.exit(0) end local function generate_init() if pl_file.access_time(INIT_FILE) then error(INIT_FILE .. " already exists in the current directory.\n" .. "Will not overwrite it.") end pl_file.write(INIT_FILE, kong_yml) end local function execute(args) if args.command == "init" then generate_init() os.exit(0) end log.disable() -- retrieve default prefix or use given one local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) log.enable() if pl_path.exists(conf.kong_env) then -- load <PREFIX>/kong.conf containing running node's config conf = assert(conf_loader(conf.kong_env)) end args.command = args.command:gsub("%-", "_") if args.command == "db_import" and conf.database == "off" then error("'kong config db_import' only works with a database.\n" .. "When using database=off, reload your declarative configuration\n" .. "using the /config endpoint.") end if args.command == "db_export" and conf.database == "off" then error("'kong config db_export' only works with a database.") end package.path = conf.lua_package_path .. ";" .. package.path local dc, err = declarative.new_config(conf) if not dc then error(err) end if args.command == "db_export" then return db_export(args[1] or "kong.yml", conf) end if args.command == "db_import" or args.command == "parse" then local filename = args[1] if not filename then error("expected a declarative configuration file; see `kong config --help`") end local dc_table, err, _, vers = dc:parse_file(filename, accepted_formats) if not dc_table then error("Failed parsing:\n" .. err) end if args.command == "db_import" then log("parse successful, beginning import") _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db local ok, err = declarative.load_into_db(dc_table) if not ok then error("Failed importing:\n" .. err) end log("import successful") -- send anonymous report if reporting is not disabled if conf.anonymous_reports then local kong_reports = require "kong.reports" kong_reports.configure_ping(conf) kong_reports.toggle(true) local report = { decl_fmt_version = vers } kong_reports.send("config-db-import", report) end else -- parse log("parse successful") end os.exit(0) end error("unknown command '" .. args.command .. "'") end local lapp = [[ Usage: kong config COMMAND [OPTIONS] Use declarative configuration files with Kong. The available commands are: init Generate an example config file to get you started. db_import <file> Import a declarative config file into the Kong database. db_export <file> Export the Kong database into a declarative config file. parse <file> Parse a declarative config file (check its syntax) but do not load it into Kong. Options: -c,--conf (optional string) Configuration file. -p,--prefix (optional string) Override prefix directory. ]] return { lapp = lapp, execute = execute, sub_commands = { init = true, db_import = true, db_export = true, parse = true, }, }
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local pl_path = require "pl.path" local pl_file = require "pl.file" local kong_global = require "kong.global" local declarative = require "kong.db.declarative" local conf_loader = require "kong.conf_loader" local kong_yml = require "kong.templates.kong_yml" local INIT_FILE = "kong.yml" local accepted_formats = { yaml = true, json = true, lua = true, } local function db_export(filename, conf) if pl_file.access_time(filename) then error(filename .. " already exists. Will not overwrite it.") end local fd, err = io.open(filename, "w") if not fd then return nil, err end local ok, err = declarative.export_from_db(fd) if not ok then error(err) end fd:close() os.exit(0) end local function generate_init() if pl_file.access_time(INIT_FILE) then error(INIT_FILE .. " already exists in the current directory.\n" .. "Will not overwrite it.") end pl_file.write(INIT_FILE, kong_yml) end local function execute(args) if args.command == "init" then generate_init() os.exit(0) end log.disable() -- retrieve default prefix or use given one local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) log.enable() if pl_path.exists(conf.kong_env) then -- load <PREFIX>/kong.conf containing running node's config conf = assert(conf_loader(conf.kong_env)) end args.command = args.command:gsub("%-", "_") if args.command == "db_import" and conf.database == "off" then error("'kong config db_import' only works with a database.\n" .. "When using database=off, reload your declarative configuration\n" .. "using the /config endpoint.") end if args.command == "db_export" and conf.database == "off" then error("'kong config db_export' only works with a database.") end package.path = conf.lua_package_path .. ";" .. package.path local dc, err = declarative.new_config(conf) if not dc then error(err) end _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db if args.command == "db_export" then return db_export(args[1] or "kong.yml", conf) end if args.command == "db_import" or args.command == "parse" then local filename = args[1] if not filename then error("expected a declarative configuration file; see `kong config --help`") end local dc_table, err, _, vers = dc:parse_file(filename, accepted_formats) if not dc_table then error("Failed parsing:\n" .. err) end if args.command == "db_import" then log("parse successful, beginning import") local ok, err = declarative.load_into_db(dc_table) if not ok then error("Failed importing:\n" .. err) end log("import successful") -- send anonymous report if reporting is not disabled if conf.anonymous_reports then local kong_reports = require "kong.reports" kong_reports.configure_ping(conf) kong_reports.toggle(true) local report = { decl_fmt_version = vers } kong_reports.send("config-db-import", report) end else -- parse log("parse successful") end os.exit(0) end error("unknown command '" .. args.command .. "'") end local lapp = [[ Usage: kong config COMMAND [OPTIONS] Use declarative configuration files with Kong. The available commands are: init Generate an example config file to get you started. db_import <file> Import a declarative config file into the Kong database. db_export <file> Export the Kong database into a declarative config file. parse <file> Parse a declarative config file (check its syntax) but do not load it into Kong. Options: -c,--conf (optional string) Configuration file. -p,--prefix (optional string) Override prefix directory. ]] return { lapp = lapp, execute = execute, sub_commands = { init = true, db_import = true, db_export = true, parse = true, }, }
fix(cmd) create globals before config subcommands (#5230)
fix(cmd) create globals before config subcommands (#5230) Initialize the kong global and database before running any config subcommand. Remove an existing, now superfluous initialization specific to db_export. db_import and parse invoke parse_file, which runs entity checks. Entity checks can require database access, and the rbac_user Enterprise entity does currently. If the kong global is not present and/or kong.db is not initialized, db_import and parse will fail.
Lua
apache-2.0
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
136eb28fad5c4fa843ca5e832e4e08d81469beaa
tasks/dm1.lua
tasks/dm1.lua
local M = {} local toribio = require 'toribio' local sched = require 'lumen.sched' local log = require 'lumen.log' local selector = require 'lumen.tasks.selector' local encoder_lib = require ('lumen.lib.dkjson') local encode_f = encoder_lib.encode local decode_f = encoder_lib.decode local assert, tonumber, io_open, tostring = assert, tonumber, io.open, tostring local cos, sin, tan, abs = math.cos, math.sin, math.tan, math.abs local p, d = 0.182, 0.190 --dimensions local d_p = d/p local sig_drive_control = {} local sigs_drive = { [0] = sig_drive_control } local function read_pote(filepot) local fdpot = assert(io_open(filepot, 'rb')) local data, err = fdpot:read('*l') fdpot:close() return data, err end M.init = function(conf) for i, chassis in ipairs(conf.motors) do log('DM1', 'INFO', 'Initializing chassis %i', i) local sig_angle = {} sigs_drive[i] = {} if i>1 then local ipot=i-1 local filepot = conf.pots[ipot].file or conf.pot.file or '/sys/devices/ocp.3/helper.15/AIN1' log('DM1', 'INFO', 'Using %s as potentiometer input', filepot) local pot_calibration = assert(conf.pots[ipot].calibration or conf.pot.calibration, 'Missing calibration for '..filepot ) log('DM1', 'INFO', 'Calibrating potentiometer as %s -> %s, %s -> %s, %s -> %s', tostring(pot_calibration[1][1]), tostring(pot_calibration[1][2]), tostring(pot_calibration[2][1]), tostring(pot_calibration[2][2]), tostring(pot_calibration[3][1]), tostring(pot_calibration[3][2])) local calibrator = require 'tasks.dm1.calibrator'(pot_calibration) --task to poll the pot sched.run(function() local last_pot = -1000000 local rate, threshold = conf.pot.rate, conf.pot.threshold while true do local pot_reading = tonumber( assert(read_pote(filepot)) ) if abs(pot_reading-last_pot) > threshold then last_pot = pot_reading sched.signal(sig_angle, calibrator(tonumber(pot_reading))) end sched.sleep(rate) end end):set_as_attached() end sched.run(function() log('DM1', 'INFO', 'Motors: left %s, right %s', chassis.left, chassis.right) local motor_left = toribio.wait_for_device(chassis.left) local motor_right = toribio.wait_for_device(chassis.right) motor_left.set.rotation_mode('wheel') motor_right.set.rotation_mode('wheel') local sig_drive_in = sigs_drive[i-1] local sig_drive_out = sigs_drive[i] local pangle, fmodule, fangle = 0, 0, 0 sched.sigrun( {sig_drive_in, sig_angle, buff_mode='keep_last'}, function(sig,par1,par2) if sig==sig_drive_in then fmodule, fangle = par1, par2 elseif sig==sig_angle then pangle = par1 end log('DM1', 'DEBUG', 'Drive: module %s, angle %s, pot %s', tostring(fmodule), tostring(fangle), tostring(pangle)) local fx = fmodule * cos(fangle+pangle) local fy = fmodule * sin(fangle+pangle) local out_r = fx - d_p*fy local out_l = fx + d_p*fy log('DM1', 'DEBUG', 'Out: left %s, right %s', tostring(out_l), tostring(out_r)) motor_left.set.moving_speed(-out_r) motor_right.set.moving_speed(out_l) sched.signal(sig_drive_out, fmodule, fangle) end) log('DM1', 'INFO', 'Motors left %s and right %s ready', chassis.left, chassis.right) end) end -- HTTP RC if conf.http_server then local http_server = require "lumen.tasks.http-server" --http_server.serve_static_content_from_stream('/docs/', './docs') http_server.serve_static_content_from_ram('/', './tasks/dm1/www') http_server.set_websocket_protocol('dm1-rc-protocol', function(ws) sched.run(function() while true do local message,opcode = ws:receive() log('DM1', 'DEBUG', 'websocket traffic "%s"', tostring(message)) if not message then sched.signal(sig_drive_control, 0, 0) ws:close() return end if opcode == ws.TEXT then local decoded, index, e = decode_f(message) if decoded then if decoded.action == 'drive' then sched.signal(sig_drive_control, decoded.module, decoded.angle) end else log('DM1', 'ERROR', 'failed to decode message with length %s with error "%s"', tostring(#message), tostring(index).." "..tostring(e)) end end end end) --:set_as_attached() end) conf.http_server.ws_enable = true http_server.init(conf.http_server) end -- /HTTP RC -- UDP RC if conf.udp then local udp = selector.new_udp(nil, nil, conf.udp.ip, conf.udp.port, -1) --listen for messages sched.sigrun({udp.events.data, buff_mode='keep_last'}, function(_, msg) local fmodule, fangle if msg then fmodule, fangle = msg:match('^([^,]+),([^,]+)$') --print("!U", left, right) else fmodule, fangle = 0, 0 end sched.signal(sig_drive_control, fmodule, fangle) end) end -- /UDP RC end return M
local M = {} local toribio = require 'toribio' local sched = require 'lumen.sched' local log = require 'lumen.log' local selector = require 'lumen.tasks.selector' local encoder_lib = require ('lumen.lib.dkjson') local encode_f = encoder_lib.encode local decode_f = encoder_lib.decode local assert, tonumber, io_open, tostring = assert, tonumber, io.open, tostring local cos, sin, tan, abs = math.cos, math.sin, math.tan, math.abs local p, d = 0.182, 0.190 --dimensions local d_p = d/p local sig_drive_control = {} local sigs_drive = { [0] = sig_drive_control } local function read_pote(filepot) local fdpot = assert(io_open(filepot, 'rb')) local data, err = fdpot:read('*l') fdpot:close() return data, err end M.init = function(conf) for i, chassis in ipairs(conf.motors) do log('DM1', 'INFO', 'Initializing chassis %i', i) local sig_angle = {} sigs_drive[i] = {} if i>1 then local ipot=i-1 local filepot = conf.pots[ipot].file or conf.pot.file or '/sys/devices/ocp.3/helper.15/AIN1' log('DM1', 'INFO', 'Using %s as potentiometer input', filepot) local pot_calibration = assert(conf.pots[ipot].calibration or conf.pot.calibration, 'Missing calibration for '..filepot ) log('DM1', 'INFO', 'Calibrating potentiometer as %s -> %s, %s -> %s, %s -> %s', tostring(pot_calibration[1][1]), tostring(pot_calibration[1][2]), tostring(pot_calibration[2][1]), tostring(pot_calibration[2][2]), tostring(pot_calibration[3][1]), tostring(pot_calibration[3][2])) local calibrator = require 'tasks.dm1.calibrator'(pot_calibration) --task to poll the pot sched.run(function() local last_pot = -1000000 local rate, threshold = conf.pot.rate, conf.pot.threshold while true do local pot_reading = tonumber( assert(read_pote(filepot)) ) if abs(pot_reading-last_pot) > threshold then last_pot = pot_reading sched.signal(sig_angle, calibrator(tonumber(pot_reading))) end sched.sleep(rate) end end)--:set_as_attached() end sched.run(function() log('DM1', 'INFO', 'Motors: left %s, right %s', chassis.left, chassis.right) local motor_left = toribio.wait_for_device(chassis.left) local motor_right = toribio.wait_for_device(chassis.right) motor_left.set.rotation_mode('wheel') motor_right.set.rotation_mode('wheel') local sig_drive_in = sigs_drive[i-1] local sig_drive_out = sigs_drive[i] local pangle, fmodule, fangle = 0, 0, 0 sched.sigrun( {sig_drive_in, sig_angle, buff_mode='keep_last'}, function(sig,par1,par2) if sig==sig_drive_in then fmodule, fangle = par1, par2 elseif sig==sig_angle then pangle = par1 end --log('DM1', 'DEBUG', 'Drive %s: module %s, angle %s, pot %s', -- tostring(i), tostring(fmodule), tostring(fangle), tostring(pangle)) local fx = fmodule * cos(fangle+pangle) local fy = fmodule * sin(fangle+pangle) local out_r = fx - d_p*fy local out_l = fx + d_p*fy --log('DM1', 'DEBUG', 'Out %s: left %s, right %s', -- tostring(i), tostring(out_l), tostring(out_r)) motor_left.set.moving_speed(-out_r) motor_right.set.moving_speed(out_l) sched.signal(sig_drive_out, fmodule, -fangle) end) log('DM1', 'INFO', 'Motors left %s and right %s ready', chassis.left, chassis.right) end) end -- HTTP RC --[[ sched.run(function() sched.sleep(3) sched.signal(sig_drive_control, 20, 0) end) --]] if conf.http_server then local http_server = require "lumen.tasks.http-server" --http_server.serve_static_content_from_stream('/docs/', './docs') http_server.serve_static_content_from_ram('/', './tasks/dm1/www') http_server.set_websocket_protocol('dm1-rc-protocol', function(ws) sched.run(function() while true do local message,opcode = ws:receive() --log('DM1', 'DEBUG', 'websocket traffic "%s"', tostring(message)) if not message then sched.signal(sig_drive_control, 0, 0) ws:close() return end if opcode == ws.TEXT then local decoded, index, e = decode_f(message) if decoded then if decoded.action == 'drive' then sched.signal(sig_drive_control, decoded.module, decoded.angle) end else log('DM1', 'ERROR', 'failed to decode message with length %s with error "%s"', tostring(#message), tostring(index).." "..tostring(e)) end end end end) --:set_as_attached() end) conf.http_server.ws_enable = true http_server.init(conf.http_server) end -- /HTTP RC -- UDP RC if conf.udp then local udp = selector.new_udp(nil, nil, conf.udp.ip, conf.udp.port, -1) --listen for messages sched.sigrun({udp.events.data, buff_mode='keep_last'}, function(_, msg) local fmodule, fangle if msg then fmodule, fangle = msg:match('^([^,]+),([^,]+)$') --print("!U", left, right) else fmodule, fangle = 0, 0 end sched.signal(sig_drive_control, fmodule, fangle) end) end -- /UDP RC end return M
fix angle passing
fix angle passing
Lua
mit
xopxe/Toribio,xopxe/Toribio,xopxe/Toribio
22bccd94000e9caae0c295544fbc88a1ed052891
src/base/detoken.lua
src/base/detoken.lua
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, e) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then print("load error:", err) return nil, err end -- give the function access to the project objects setfenv(func, e) -- run it and get the result local success, result = pcall(func) if not success then err = result result = nil else err = nil end -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = false if result ~= nil then isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then err = nil result = varMap[token] if type(result) == "function" then success, result = pcall(result, e) if not success then return nil, result end end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if result ~= nil and isAbs and field.paths then result = "\0" .. result end return result, err end function expandvalue(value, e) if type(value) ~= "string" then return value end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), e) if err then error(err .. " in token: " .. token, 0) end if not result then error("Token returned nil, it may not exist: " .. token, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value, e) if type(value) == "table" then local res_table = {} for k, v in pairs(value) do if tonumber(k) ~= nil then res_table[k] = recurse(v, e) else local nk = recurse(k, e); res_table[nk] = recurse(v, e) end end return res_table else return expandvalue(value, e) end end return recurse(value, environ) end
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, e) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, "load error: " .. err end -- give the function access to the project objects setfenv(func, e) -- run it and get the result local success, result = pcall(func) if not success then err = result result = nil else err = nil end -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = false if result ~= nil then isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then err = nil result = varMap[token] if type(result) == "function" then success, result = pcall(result, e) if not success then return nil, result end end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if result ~= nil and isAbs and field.paths then result = "\0" .. result end return result, err end function expandvalue(value, e) if type(value) ~= "string" then return value end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), e) if err then error(err .. " in token: " .. token, 0) end if not result then error("Token returned nil, it may not exist: " .. token, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value, e) if type(value) == "table" then local res_table = {} for k, v in pairs(value) do if tonumber(k) ~= nil then res_table[k] = recurse(v, e) else local nk = recurse(k, e); res_table[nk] = recurse(v, e) end end return res_table else return expandvalue(value, e) end end return recurse(value, environ) end
fix error reporting in detoken.lua
fix error reporting in detoken.lua
Lua
bsd-3-clause
aleksijuvani/premake-core,xriss/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,soundsrc/premake-core,tvandijck/premake-core,LORgames/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,noresources/premake-core,martin-traverse/premake-core,premake/premake-core,starkos/premake-core,aleksijuvani/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,dcourtois/premake-core,tvandijck/premake-core,resetnow/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,starkos/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,noresources/premake-core,noresources/premake-core,mendsley/premake-core,starkos/premake-core,noresources/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,dcourtois/premake-core,resetnow/premake-core,aleksijuvani/premake-core,resetnow/premake-core,premake/premake-core,mandersan/premake-core,dcourtois/premake-core,mandersan/premake-core,lizh06/premake-core,soundsrc/premake-core,xriss/premake-core,mandersan/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,noresources/premake-core,premake/premake-core,soundsrc/premake-core,martin-traverse/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,mendsley/premake-core,mendsley/premake-core,noresources/premake-core,tvandijck/premake-core,Blizzard/premake-core,sleepingwit/premake-core,starkos/premake-core,xriss/premake-core,TurkeyMan/premake-core,mandersan/premake-core,LORgames/premake-core,resetnow/premake-core,premake/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,Blizzard/premake-core,lizh06/premake-core,premake/premake-core,premake/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,sleepingwit/premake-core,mandersan/premake-core,xriss/premake-core,aleksijuvani/premake-core,starkos/premake-core,Blizzard/premake-core,dcourtois/premake-core,LORgames/premake-core,starkos/premake-core,martin-traverse/premake-core,LORgames/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,lizh06/premake-core,dcourtois/premake-core,noresources/premake-core,mendsley/premake-core,Blizzard/premake-core,LORgames/premake-core,bravnsgaard/premake-core,resetnow/premake-core,martin-traverse/premake-core,starkos/premake-core,jstewart-amd/premake-core,xriss/premake-core,premake/premake-core
d985b5b2b000368bf656a78a5f3a008322ceeade
deployer/deployer_oodl.lua
deployer/deployer_oodl.lua
package.path = package.path .. ';./include/?.lua' require "rttlib" --require "rfsm_rtt" require "rttros" --require "kdlpp" --require "kdlutils" --require "complete" --require "readline" require 'inifile' require "definitions" -- Lua deployer if deployer_type == LUA_DEPLOYER then tc = rtt.getTC() depl = tc:getPeer("Deployer") -- Ops deployer elseif deployer_type == OPS_DEPLOYER then tc=rtt.getTC() tcName=tc:getName() if tcName=="lua" then depl=tc:getPeer("deployer") elseif tcName=="Deployer" then depl = tc end depl:loadComponent("Supervisor", "OCL::LuaComponent") if tcName == "lua" then depl:aliasPeer("Supervisor", "deployer", "Deployer") elseif tcName == "Deployer" then depl:addPeer("Supervisor", "Deployer") end end -- Import component depl:import("fbsched") --depl:import("kdl_typekit") depl:import("rtt_roscomm") depl:import("rtt_ros") depl:import("rtt_sensor_msgs") depl:import("rtt_std_msgs") depl:import("rtt_geometry_msgs") depl:import("rtt_nav_msgs") depl:import("rtt_motion_control_msgs") if is_ros_enabled == true then depl:import("rtt_rosnode") end depl:import(string.lower(robot_name).."_sim") depl:import(string.lower(robot_name).."_oodl") depl:import(string.lower(robot_name).."_kinematics") depl:import(string.lower(robot_name).."_republisher") depl:import(string.lower(robot_name).."_cmddemux") depl:import("cmd_queue") depl:import("cartesian_motion_control") -- OLD DEPLOYER -- -- Loading component depl:loadComponent("controlloop_scheduler", "FBSched") depl:loadComponent("Robot_OODL", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."OODL") depl:loadComponent("Robot_SIM", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."SIM") depl:loadComponent("Cmd_QUEUE", "Cmd_queue") depl:loadComponent("Robot_KINE", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."Kinematics") depl:loadComponent("Robot_CTRL_CARTESIAN", "MotionControl::CartesianControllerPos") depl:loadComponent("Robot_STATE_PUBLISHER", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."StateRepublisher") depl:loadComponent("Robot_CMDDEMUX", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."CmdDemux") -- Getting peers of components controlloop_scheduler = depl:getPeer("controlloop_scheduler") robot_sim = depl:getPeer("Robot_SIM") robot_oodl = depl:getPeer("Robot_OODL") cmd_queue = depl:getPeer("Cmd_QUEUE") robot_kine = depl:getPeer("Robot_KINE") robot_ctrl_cartesian = depl:getPeer("Robot_CTRL_CARTESIAN") robot_repub = depl:getPeer("Robot_STATE_PUBLISHER") robot_cmddemux = depl:getPeer("Robot_CMDDEMUX") -- Using fbsched for activity depl:setActivity("controlloop_scheduler",0.002,99,rtt.globals.ORO_SCHED_OTHER) depl:setMasterSlaveActivity("controlloop_scheduler","Robot_SIM") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_OODL") depl:setMasterSlaveActivity("controlloop_scheduler","Cmd_QUEUE") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_KINE") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_CTRL_CARTESIAN") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_STATE_PUBLISHER") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_CMDDEMUX") -- Creating connections policy cp = rtt.Variable('ConnPolicy') cp.type = rtt.globals.DATA -- type data -- Launching scheduler print("Starting control loop") controlloop_scheduler:configure() controlloop_scheduler:start() require("procedures/"..procedure) if communication_type == REMOTE then local socket = require "socket" local udp = socket.udp() udp:settimeout(0) udp:setsockname(socket_address, socket_port) local world = {} -- the empty world-state local data, msg_or_ip, port_or_nil local entity, cmd, parms print "[REMOTE] Server loop started" while running do data, msg_or_ip, port_or_nil = udp:receivefrom() if data ~= nil then print(data) -- Experimental!------------------------------------------------- if data == "ROBOT_STATE" then r_state = rtt.Variable("sensor_msgs.JointState") fs, r_state = robot_repub:getPort("arm_state_in"):read() local count = 1 local string = "JOINT_STATE" for i=1,5 do string = string..";"..r_state.position[i] end fs, r_state = robot_repub:getPort("base_state_in"):read() for i=1,4 do string = string..";"..r_state.position[i] end udp:sendto(string, msg_or_ip, socket_port) ------------------------------------------------------------------ else local status, err = pcall(function() loadstring(hash_remote_command[data])() end) if status then udp:sendto(data.." - ok.", msg_or_ip, socket_port) --print("[REMOTE] Reply sent "..msg_or_ip.." - "..socket_port) else print("[DEPLOYER] "..err) udp:sendto(data.." - failed.", msg_or_ip, socket_port) --print("[REMOTE] Failed call sent") end end end end elseif communication_type == LOCAL then while running do text = io.read("*l") if text == "move_up" then move(0,0,0.2) end end end
package.path = package.path .. ';./include/?.lua' package.path = package.path .. ';./procedures/?.lua' require "rttlib" --require "rfsm_rtt" require "rttros" --require "kdlpp" --require "kdlutils" --require "complete" --require "readline" require 'inifile' require "definitions" -- Lua deployer if deployer_type == LUA_DEPLOYER then tc = rtt.getTC() depl = tc:getPeer("Deployer") -- Ops deployer elseif deployer_type == OPS_DEPLOYER then tc=rtt.getTC() tcName=tc:getName() if tcName=="lua" then depl=tc:getPeer("deployer") elseif tcName=="Deployer" then depl = tc end depl:loadComponent("Supervisor", "OCL::LuaComponent") if tcName == "lua" then depl:aliasPeer("Supervisor", "deployer", "Deployer") elseif tcName == "Deployer" then depl:addPeer("Supervisor", "Deployer") end end -- Import component depl:import("fbsched") --depl:import("kdl_typekit") depl:import("rtt_roscomm") depl:import("rtt_ros") depl:import("rtt_sensor_msgs") depl:import("rtt_std_msgs") depl:import("rtt_geometry_msgs") depl:import("rtt_nav_msgs") depl:import("rtt_motion_control_msgs") if is_ros_enabled == true then depl:import("rtt_rosnode") end depl:import(string.lower(robot_name).."_sim") depl:import(string.lower(robot_name).."_oodl") depl:import(string.lower(robot_name).."_kinematics") depl:import(string.lower(robot_name).."_republisher") depl:import(string.lower(robot_name).."_cmddemux") depl:import("cmd_queue") depl:import("cartesian_motion_control") -- OLD DEPLOYER -- -- Loading component depl:loadComponent("controlloop_scheduler", "FBSched") depl:loadComponent("Robot_OODL", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."OODL") depl:loadComponent("Robot_SIM", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."SIM") depl:loadComponent("Cmd_QUEUE", "Cmd_queue") depl:loadComponent("Robot_KINE", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."Kinematics") depl:loadComponent("Robot_CTRL_CARTESIAN", "MotionControl::CartesianControllerPos") depl:loadComponent("Robot_STATE_PUBLISHER", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."StateRepublisher") depl:loadComponent("Robot_CMDDEMUX", firstToUpper(robot_name).."::"..firstToUpper(robot_name).."CmdDemux") -- Getting peers of components controlloop_scheduler = depl:getPeer("controlloop_scheduler") robot_sim = depl:getPeer("Robot_SIM") robot_oodl = depl:getPeer("Robot_OODL") cmd_queue = depl:getPeer("Cmd_QUEUE") robot_kine = depl:getPeer("Robot_KINE") robot_ctrl_cartesian = depl:getPeer("Robot_CTRL_CARTESIAN") robot_repub = depl:getPeer("Robot_STATE_PUBLISHER") robot_cmddemux = depl:getPeer("Robot_CMDDEMUX") -- Using fbsched for activity depl:setActivity("controlloop_scheduler",0.002,99,rtt.globals.ORO_SCHED_OTHER) depl:setMasterSlaveActivity("controlloop_scheduler","Robot_SIM") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_OODL") depl:setMasterSlaveActivity("controlloop_scheduler","Cmd_QUEUE") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_KINE") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_CTRL_CARTESIAN") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_STATE_PUBLISHER") depl:setMasterSlaveActivity("controlloop_scheduler","Robot_CMDDEMUX") -- Creating connections policy cp = rtt.Variable('ConnPolicy') cp.type = rtt.globals.DATA -- type data -- Launching scheduler print("Starting control loop") controlloop_scheduler:configure() controlloop_scheduler:start() require(""..procedure) if communication_type == REMOTE then local socket = require "socket" local udp = socket.udp() udp:settimeout(0) udp:setsockname(socket_address, socket_port) local world = {} -- the empty world-state local data, msg_or_ip, port_or_nil local entity, cmd, parms print "[REMOTE] Server loop started" while running do data, msg_or_ip, port_or_nil = udp:receivefrom() if data ~= nil then print(data) -- Experimental!------------------------------------------------- if data == "ROBOT_STATE" then r_state = rtt.Variable("sensor_msgs.JointState") fs, r_state = robot_repub:getPort("arm_state_in"):read() local count = 1 local string = "JOINT_STATE" for i=1,5 do string = string..";"..r_state.position[i] end fs, r_state = robot_repub:getPort("base_state_in"):read() for i=1,4 do string = string..";"..r_state.position[i] end udp:sendto(string, msg_or_ip, socket_port) ------------------------------------------------------------------ else local status, err = pcall(function() loadstring(hash_remote_command[data])() end) if status then udp:sendto(data.." - ok.", msg_or_ip, socket_port) --print("[REMOTE] Reply sent "..msg_or_ip.." - "..socket_port) else print("[DEPLOYER] "..err) udp:sendto(data.." - failed.", msg_or_ip, socket_port) --print("[REMOTE] Failed call sent") end end end end elseif communication_type == LOCAL then while running do text = io.read("*l") if text == "move_up" then move(0,0,0.2) end end end
fix issue #9
fix issue #9
Lua
mit
hjeldin/HILAS,hjeldin/HILAS,hjeldin/HILAS,hjeldin/HILAS
cf8dfd819d60fb1b5e938a76a6253a02e20db124
lua/ui.lua
lua/ui.lua
-- ui ui = {} function ui.choose(options, title, selected, hook, titlecolor, selectedoptcolor, optioncolor, font_custom) local font_to_use = font_custom or font or vita2d.load_font() local selectedoptcolor = selectedcolor or colors.red local optioncolor = optioncolor or colors.white local titlecolor = titlecolor or colors.blue local hooks = hooks or {} local old_pad = input.peek() local selected = selected or 1 local num = 18 while true do local pad = input.peek() vita2d.start_drawing() vita2d.clear_screen() local p = 0 local min = (selected <= num and 1 or selected - num + 1) local max = math.min(#options, (selected <= num and num or selected)) if title then font_to_use:draw_text(0, 0, titlecolor, 30, title) p = 1 end for i=min, max do font_to_use:draw_text(0, p * 30, i == selected and selectedoptcolor or optioncolor, 30, options[i]) p = p + 1 end vita2d.end_drawing() vita2d.swap_buffers() if hook then abort, res = hook(options[selected], old_pad, pad) if abort then return res, abort end end if old_pad:up() and not pad:up() and selected > 1 then selected = selected - 1 elseif old_pad:down() and not pad:down() and selected < #options then selected = selected + 1 elseif old_pad:cross() and not pad:cross() then return options[selected], false elseif old_pad:circle() and not pad:circle() then return nil end old_pad = pad end end function ui.view_image(tex, font_custom) local font_to_use = font_custom or font or vita2d.load_font() local old_pad = input.peek() local white = false local ratio = math.min(960 / tex:width(), 544 / tex:height()) while true do local pad = input.peek() vita2d.start_drawing() vita2d.clear_screen() tex:draw_scale((960 - tex:width()*ratio)/2 , (540 - tex:height()*ratio)/2, ratio, ratio) font_to_use:draw_text(0, 0, white and colors.black or colors.white, 30, tostring(tex:width()) .. "x" .. tostring(tex:height())) vita2d.end_drawing() vita2d.swap_buffers() if old_pad:circle() and not pad:circle() then break end if old_pad:cross() and not pad:cross() then break end if old_pad:triangle() and not pad:triangle() then white = not white vita2d.set_clear_color(white and colors.white or colors.black) end old_pad = pad end vita2d.set_clear_color(colors.black) end function ui.choose_file(startdir, title, hook) local startdir = string.gsub(startdir or "/", "/$", "") local path = {""} if startdir then local leftover = string.gsub(startdir, "..-/", function(e) local t = string.gsub(e, "^/(.+)/$", "%1") table.insert(path, t) return "" end) if leftover then table.insert(path, leftover) end end while true do local t = physfs.list(table.concat(path, "/") .. "/") if not string.find(table.concat(path, "/") .. "/", "^/$") then table.insert(t, 1, "..") end res, abort = ui.choose(t, title or table.concat(path, "/").."/", nil, function(res, old_pad, pad) if hook then return hook(res, old_pad, pad, table.concat(path, "/") .. "/" .. res) end end) if abort then return res end if res == ".." or res == nil then if #path > 1 then table.remove(path) end else if physfs.is_dir(table.concat(path, "/") .. "/" .. res) then table.insert(path, res) else return (table.concat(path, "/") .. "/" .. res), table.concat(path, "/") end end end end
-- ui ui = {} function ui.choose(options, title, selected, hook, titlecolor, selectedoptcolor, optioncolor, font_custom) local font_to_use = font_custom or font or vita2d.load_font() local selectedoptcolor = selectedcolor or colors.red local optioncolor = optioncolor or colors.white local titlecolor = titlecolor or colors.blue local hooks = hooks or {} local old_pad = input.peek() local selected = selected or 1 local num = 18 if title then num = 17 end while true do local pad = input.peek() vita2d.start_drawing() vita2d.clear_screen() local p = 0 local min = (selected <= num and 1 or selected - num + 1) local max = math.min(#options, (selected <= num and num or selected)) if title then font_to_use:draw_text(0, 0, titlecolor, 30, title) p = 1 end for i=min, max do font_to_use:draw_text(0, p * 30, i == selected and selectedoptcolor or optioncolor, 30, options[i]) p = p + 1 end vita2d.end_drawing() vita2d.swap_buffers() if hook then abort, res = hook(options[selected], old_pad, pad) if abort then return res, abort end end if old_pad:up() and not pad:up() and selected > 1 then selected = selected - 1 elseif old_pad:down() and not pad:down() and selected < #options then selected = selected + 1 elseif old_pad:cross() and not pad:cross() then return options[selected], false elseif old_pad:circle() and not pad:circle() then return nil end old_pad = pad end end function ui.view_image(tex, font_custom) local font_to_use = font_custom or font or vita2d.load_font() local old_pad = input.peek() local white = false local ratio = math.min(960 / tex:width(), 544 / tex:height()) while true do local pad = input.peek() vita2d.start_drawing() vita2d.clear_screen() tex:draw_scale((960 - tex:width()*ratio)/2 , (540 - tex:height()*ratio)/2, ratio, ratio) font_to_use:draw_text(0, 0, white and colors.black or colors.white, 30, tostring(tex:width()) .. "x" .. tostring(tex:height())) vita2d.end_drawing() vita2d.swap_buffers() if old_pad:circle() and not pad:circle() then break end if old_pad:cross() and not pad:cross() then break end if old_pad:triangle() and not pad:triangle() then white = not white vita2d.set_clear_color(white and colors.white or colors.black) end old_pad = pad end vita2d.set_clear_color(colors.black) end function ui.choose_file(startdir, title, hook) local startdir = string.gsub(startdir or "/", "/$", "") local path = {""} if startdir then local leftover = string.gsub(startdir, "..-/", function(e) local t = string.gsub(e, "^/(.+)/$", "%1") table.insert(path, t) return "" end) if leftover then table.insert(path, leftover) end end while true do local t = physfs.list(table.concat(path, "/") .. "/") if not string.find(table.concat(path, "/") .. "/", "^/$") then table.insert(t, 1, "..") end res, abort = ui.choose(t, title or table.concat(path, "/").."/", nil, function(res, old_pad, pad) if hook then return hook(res, old_pad, pad, table.concat(path, "/") .. "/" .. res) end end) if abort then return res end if res == ".." or res == nil then if #path > 1 then table.remove(path) end else if physfs.is_dir(table.concat(path, "/") .. "/" .. res) then table.insert(path, res) else return (table.concat(path, "/") .. "/" .. res), table.concat(path, "/") end end end end
Fixed scrolling.
Fixed scrolling.
Lua
mit
Stary2001/vita-lua,Stary2001/vita-lua
d8462e874c909d2812c7ce7f3aee5669601552d5
lib/pkg/glib.lua
lib/pkg/glib.lua
return { source = { type = 'dist', location = 'http://ftp.gnome.org/pub/GNOME/sources/glib/2.48/glib-2.48.2.tar.xz', sha256sum = 'f25e751589cb1a58826eac24fbd4186cda4518af772806b666a3f91f66e6d3f4' }, build = { type = 'GNU', options = { '--disable-mem-pools', '--disable-rebuilds', '--disable-selinux', '--disable-fam', '--disable-xattr', '--disable-libelf', '--disable-gtk-doc-html', '--disable-man', '--disable-dtrace', '--disable-systemtap', '--disable-coverage', '--disable-Bsymbolic', '--disable-znodelete' }, libs = { 'glib-2.0', 'gthread-2.0', 'gobject-2.0', 'gmodule-2.0', 'gio-2.0' }, autoreconf = true }, requires = { 'libffi', 'zlib' } }
return { source = { type = 'dist', location = 'http://ftp.gnome.org/pub/GNOME/sources/glib/2.48/glib-2.48.2.tar.xz', sha256sum = 'f25e751589cb1a58826eac24fbd4186cda4518af772806b666a3f91f66e6d3f4' }, build = { type = 'GNU', options = { '--disable-maintainer-mode', '--enable-debug=no', '--disable-gc-friendly', '--disable-mem-pools', '--disable-rebuilds', '--disable-installed-tests', '--disable-always-build-tests', '--enable-largefile', '--disable-static', '--enable-shared', '--disable-selinux', '--disable-fam', '--disable-xattr', '--disable-libelf', '--disable-gtk-doc', '--disable-gtk-doc-html', '--disable-gtk-doc-pdf', '--disable-man', '--disable-dtrace', '--disable-systemtap', '--disable-coverage', '--disable-Bsymbolic', '--disable-znodelete', '--with-pcre=internal', }, libs = { 'glib-2.0', 'gthread-2.0', 'gobject-2.0', 'gmodule-2.0', 'gio-2.0' }, autoreconf = true }, requires = { 'libffi', 'zlib' } }
Explicitly set more options to fix glib build on target
Explicitly set more options to fix glib build on target
Lua
mit
bazurbat/jagen
aedd84881b18e3044a4606edb5df2c2d82616ea4
test/vinyl/large.lua
test/vinyl/large.lua
fiber = require('fiber') digest = require('digest') local function prepare() local s1 = box.schema.space.create('large_s1', { engine = 'vinyl', if_not_exists = true }) s1:create_index('pk', {if_not_exists = true}) end local function large_test(iter_limit, time_limit) iter_limit = iter_limit or 500 time_limit = time_limit or 5 local i = 0 local t1 = fiber.time() local data = digest.urandom(2 * 1024 * 1024) while i < iter_limit and fiber.time() - t1 < time_limit do local space = box.space.large_s1 space:replace({i, data}) i = i + 1 end end local function check_test() for _, tuple in box.space.large_s1:pairs() do if 2 * 1024 * 1024 ~= tuple[2]:len() then error('Large tuple has incorect length') end end end local function teardown() box.space.large_s1:drop() end return { prepare = prepare; large = large_test, check = check_test; teardown = teardown; }
fiber = require('fiber') digest = require('digest') local function prepare() local s1 = box.schema.space.create('large_s1', { engine = 'vinyl', if_not_exists = true }) s1:create_index('pk', {if_not_exists = true}) end local function large_test(iter_limit, time_limit) iter_limit = iter_limit or 500 time_limit = time_limit or 5 local i = 0 local t1 = fiber.time() local data = digest.urandom(2 * 1024 * 1024) while i < iter_limit and fiber.time() - t1 < time_limit do local space = box.space.large_s1 space:replace({i, data}) i = i + 1 if i % 100 == 0 then collectgarbage('collect') end end end local function check_test() local i = 0 for _, tuple in box.space.large_s1:pairs() do if 2 * 1024 * 1024 ~= tuple[2]:len() then error('Large tuple has incorect length') end if i % 100 == 0 then collectgarbage('collect') end i = i + 1 end end local function teardown() box.space.large_s1:drop() end return { prepare = prepare; large = large_test, check = check_test; teardown = teardown; }
vinyl: fix vinyl/large.test.lua
vinyl: fix vinyl/large.test.lua Add periodic collectgarbage() to loops.
Lua
bsd-2-clause
mejedi/tarantool,rtsisyk/tarantool,rtsisyk/tarantool,mejedi/tarantool,mejedi/tarantool,rtsisyk/tarantool,rtsisyk/tarantool,mejedi/tarantool
426f30d459331554c6d1f99c9544ddbce4a6ec52
MMOCoreORB/bin/scripts/mobile/naboo/motley_kaadu.lua
MMOCoreORB/bin/scripts/mobile/naboo/motley_kaadu.lua
motley_kaadu = Creature:new { objectName = "@mob/creature_names:kaadu_motley", socialGroup = "kaadu", pvpFaction = "", faction = "", level = 8, chanceHit = 0.27, damageMin = 70, damageMax = 75, baseXp = 187, baseHAM = 405, baseHAMmax = 495, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "meat_avian", meatAmount = 120, hideType = "hide_leathery", hideAmount = 75, boneType = "bone_avian", boneAmount = 65, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = HERD, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/kaadu_hue.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(motley_kaadu, "motley_kaadu")
motley_kaadu = Creature:new { objectName = "@mob/creature_names:kaadu_motley", socialGroup = "kaadu", pvpFaction = "", faction = "", level = 8, chanceHit = 0.27, damageMin = 70, damageMax = 75, baseXp = 187, baseHAM = 405, baseHAMmax = 495, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "meat_avian", meatAmount = 120, hideType = "hide_leathery", hideAmount = 75, boneType = "bone_avian", boneAmount = 65, milk = 0, tamingChance = 0.25, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = HERD, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/kaadu_hue.iff"}, controlDeviceTemplate = "object/intangible/pet/kaadu_hue.iff", lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(motley_kaadu, "motley_kaadu")
[Fixed] motley kaadu to be tamable
[Fixed] motley kaadu to be tamable Change-Id: Ie17e391e6ca5aa0549e38b0250de11606aa2893c
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
679de0aa41c0660db3ce1535b26fb101b037c09f
build/Tests.lua
build/Tests.lua
-- Tests/examples helpers function SetupExampleProject() kind "ConsoleApp" language "C#" debugdir "." files { "**.cs", "./*.lua" } links { "CppSharp.AST", "CppSharp.Generator" } SetupManagedProject() SetupParser() end function SetupTestProject(name, extraFiles) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name, nil, extraFiles) SetupTestProjectsCLI(name, extraFiles) end function SetupTestCSharp(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name) end function SetupTestCLI(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCLI(name) end function SetupManagedTestProject() kind "SharedLib" language "C#" flags { "Unsafe" } SetupManagedProject() end function SetupTestGeneratorProject(name, depends) project(name .. ".Gen") SetupManagedTestProject() kind "ConsoleApp" files { name .. ".cs" } dependson { name .. ".Native" } linktable = { "System.Core", "CppSharp.AST", "CppSharp.Generator", "CppSharp.Generator.Tests", } if depends ~= nil then table.insert(linktable, depends .. ".Gen") end links(linktable) SetupParser() end function SetupTestGeneratorBuildEvent(name) if string.starts(action, "vs") then local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe") prebuildcommands { exePath } else local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe") prebuildcommands { "mono --debug " .. exePath } end end function SetupTestNativeProject(name, depends) if string.starts(action, "vs") and not os.is_windows() then return end project(name .. ".Native") SetupNativeProject() kind "SharedLib" language "C++" flags { common_flags } files { "**.h", "**.cpp" } if depends ~= nil then links { depends .. ".Native" } end end function LinkNUnit() libdirs { depsdir .. "/NUnit", depsdir .. "/NSubstitute" } links { "nunit.framework", "NSubstitute" } end function SetupTestProjectsCSharp(name, depends, extraFiles) project(name .. ".CSharp") SetupManagedTestProject() dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cs"), } if extraFiles ~= nil then for _, file in pairs(extraFiles) do files { path.join(gendir, name, file .. ".cs") } end end linktable = { "CppSharp.Runtime" } if depends ~= nil then table.insert(linktable, depends .. ".CSharp") end links(linktable) project(name .. ".Tests.CSharp") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CSharp", "CppSharp.Generator.Tests" } dependson { name .. ".Native" } LinkNUnit() links { "CppSharp.Runtime" } end function SetupTestProjectsCLI(name, extraFiles) if not os.is_windows() then return end project(name .. ".CLI") SetupNativeProject() kind "SharedLib" language "C++" flags { "Managed" } dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cpp"), path.join(gendir, name, name .. ".h") } if extraFiles ~= nil then for _, file in pairs(extraFiles) do files { path.join(gendir, name, file .. ".cpp") } files { path.join(gendir, name, file .. ".h") } end end includedirs { path.join(testsdir, name), incdir } links { name .. ".Native" } project(name .. ".Tests.CLI") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CLI", "CppSharp.Generator.Tests" } dependson { name .. ".Native" } LinkNUnit() end function IncludeExamples() --print("Searching for examples...") IncludeDir(examplesdir) end function IncludeTests() --print("Searching for tests...") IncludeDir(testsdir) end
-- Tests/examples helpers function SetupExampleProject() kind "ConsoleApp" language "C#" debugdir "." files { "**.cs", "./*.lua" } links { "CppSharp.AST", "CppSharp.Generator" } SetupManagedProject() SetupParser() end function SetupTestProject(name, extraFiles) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name, nil, extraFiles) SetupTestProjectsCLI(name, extraFiles) end function SetupTestCSharp(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCSharp(name) end function SetupTestCLI(name) SetupTestGeneratorProject(name) SetupTestNativeProject(name) SetupTestProjectsCLI(name) end function SetupManagedTestProject() kind "SharedLib" language "C#" flags { "Unsafe" } SetupManagedProject() end function SetupTestGeneratorProject(name, depends) project(name .. ".Gen") SetupManagedTestProject() kind "ConsoleApp" files { name .. ".cs" } dependson { name .. ".Native" } linktable = { "System.Core", "CppSharp.AST", "CppSharp.Generator", "CppSharp.Generator.Tests", } if depends ~= nil then table.insert(linktable, depends .. ".Gen") end links(linktable) SetupParser() end function SetupTestGeneratorBuildEvent(name) local runtimeExe = os.is("windows") and "" or "mono --debug " if string.starts(action, "vs") then local exePath = SafePath("$(TargetDir)" .. name .. ".Gen.exe") prebuildcommands { runtimeExe .. exePath } else local exePath = SafePath("%{cfg.buildtarget.directory}/" .. name .. ".Gen.exe") prebuildcommands { runtimeExe .. exePath } end end function SetupTestNativeProject(name, depends) if string.starts(action, "vs") and not os.is_windows() then return end project(name .. ".Native") SetupNativeProject() kind "SharedLib" language "C++" flags { common_flags } files { "**.h", "**.cpp" } if depends ~= nil then links { depends .. ".Native" } end end function LinkNUnit() libdirs { depsdir .. "/NUnit", depsdir .. "/NSubstitute" } links { "nunit.framework", "NSubstitute" } end function SetupTestProjectsCSharp(name, depends, extraFiles) project(name .. ".CSharp") SetupManagedTestProject() dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cs"), } if extraFiles ~= nil then for _, file in pairs(extraFiles) do files { path.join(gendir, name, file .. ".cs") } end end linktable = { "CppSharp.Runtime" } if depends ~= nil then table.insert(linktable, depends .. ".CSharp") end links(linktable) project(name .. ".Tests.CSharp") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CSharp", "CppSharp.Generator.Tests" } dependson { name .. ".Native" } LinkNUnit() links { "CppSharp.Runtime" } end function SetupTestProjectsCLI(name, extraFiles) if not os.is_windows() then return end project(name .. ".CLI") SetupNativeProject() kind "SharedLib" language "C++" flags { "Managed" } dependson { name .. ".Gen", name .. ".Native" } SetupTestGeneratorBuildEvent(name) files { path.join(gendir, name, name .. ".cpp"), path.join(gendir, name, name .. ".h") } if extraFiles ~= nil then for _, file in pairs(extraFiles) do files { path.join(gendir, name, file .. ".cpp") } files { path.join(gendir, name, file .. ".h") } end end includedirs { path.join(testsdir, name), incdir } links { name .. ".Native" } project(name .. ".Tests.CLI") SetupManagedTestProject() files { name .. ".Tests.cs" } links { name .. ".CLI", "CppSharp.Generator.Tests" } dependson { name .. ".Native" } LinkNUnit() end function IncludeExamples() --print("Searching for examples...") IncludeDir(examplesdir) end function IncludeTests() --print("Searching for tests...") IncludeDir(testsdir) end
Fixed tests generation in build using Xamarin Studio.
Fixed tests generation in build using Xamarin Studio.
Lua
mit
ddobrev/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mono/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,u255436/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mono/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp
dfa14c1255d5cab24715e00514c23e8c2473562a
lib/utils/opt.lua
lib/utils/opt.lua
local function is_set(opt, name) return opt[name]:len() > 0 end --[[ Check that option `name` is set in `opt`. Throw an error if not set. ]] local function require_option(opt, name) if not is_set(opt, name) then error("option -" .. name .. " is required") end end --[[ Make sure all options in `names` are set in `opt`. ]] local function require_options(opt, names) for i = 1, #names do require_option(opt, names[i]) end end --[[ Return options set in the file `filename`. ]] local function load_file(filename) local file = assert(io.open(filename, "r")) local opt = {} for line in file:lines() do -- Ignore empty or commented out lines. if line:len() > 0 and string.sub(line, 1, 1) ~= '#' then local field = line:split('=') assert(#field == 2, 'badly formatted config file') local key = utils.String.strip(field[1]) local val = utils.String.strip(field[2]) opt[key] = val end end file:close() return opt end --[[ Override `opt` with option values set in file `filename`. ]] local function load_config(filename, opt) local config = load_file(filename) for key, val in pairs(config) do assert(opt[key] ~= nil, 'unkown option ' .. key) opt[key] = val end return opt end local function init(opt, required_options) if opt.config:len() > 0 then opt = load_config(opt.config, opt) end require_options(opt, required_options) if opt.seed then torch.manualSeed(opt.seed) end end return { init = init }
local function is_set(opt, name) return opt[name]:len() > 0 end --[[ Check that option `name` is set in `opt`. Throw an error if not set. ]] local function require_option(opt, name) if not is_set(opt, name) then error("option -" .. name .. " is required") end end --[[ Make sure all options in `names` are set in `opt`. ]] local function require_options(opt, names) for i = 1, #names do require_option(opt, names[i]) end end --[[ Convert `val` string to its actual type (boolean, number or string). ]] local function convert(val) if val == 'true' then return true elseif val == 'false' then return false else return tonumber(val) or val end end --[[ Return options set in the file `filename`. ]] local function load_file(filename) local file = assert(io.open(filename, "r")) local opt = {} for line in file:lines() do -- Ignore empty or commented out lines. if line:len() > 0 and string.sub(line, 1, 1) ~= '#' then local field = line:split('=') assert(#field == 2, 'badly formatted config file') local key = utils.String.strip(field[1]) local val = utils.String.strip(field[2]) opt[key] = convert(val) end end file:close() return opt end --[[ Override `opt` with option values set in file `filename`. ]] local function load_config(filename, opt) local config = load_file(filename) for key, val in pairs(config) do assert(opt[key] ~= nil, 'unkown option ' .. key) opt[key] = val end return opt end local function init(opt, required_options) if opt.config:len() > 0 then opt = load_config(opt.config, opt) end require_options(opt, required_options) if opt.seed then torch.manualSeed(opt.seed) end end return { init = init }
fix config file loading
fix config file loading Convert values to their original type: boolean, number or string.
Lua
mit
monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,srush/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,cservan/OpenNMT_scores_0.2.0,da03/OpenNMT,jsenellart-systran/OpenNMT
9c352f2b6a26d077212f0a8d3cc951a2fc888ee8
bin/core/app.lua
bin/core/app.lua
-- app.lua local shotcuts = puss.import('core.shotcuts') local pages = puss.import('core.pages') local docs = puss.import('core.docs') local demos = puss.import('core.demos') local filebrowser = puss.import('core.filebrowser') local console = puss.import('core.console') local diskfs = puss.import('core.diskfs') filebrowser.setup(diskfs) docs.setup(diskfs) local run_sign = true local main_ui = _main_ui show_imgui_demos = show_imgui_demos or false show_tabs_demo = show_tabs_demo or false show_console_window = show_console_window or false show_shutcut_window = show_shutcut_window or false shotcuts.register('app/reload', 'Reload scripts', 'F12', true, false, false, false) local function main_menu() local active if not imgui.BeginMenuBar() then return end if imgui.BeginMenu('File') then if imgui.MenuItem('Add puss path FileBrowser') then filebrowser.append_folder(puss.local_to_utf8(puss._path)) end if imgui.MenuItem('Add Demo Tab') then demos.new_page() end if imgui.MenuItem('New page') then docs.new_page() end if imgui.MenuItem('Open app.lua') then docs.open(puss._path .. '/core/app.lua') end if imgui.MenuItem('Open console.lua') then docs.open(puss._path .. '/core/console.lua') end imgui.EndMenu() end if imgui.BeginMenu('Help') then active, show_imgui_demos = imgui.MenuItem('ImGUI Demos', nil, show_imgui_demos) active, show_tabs_demo = imgui.MenuItem('Tabs Demo', nil, show_tabs_demo) active, show_console_window = imgui.MenuItem('Conosle', nil, show_console_window) active, show_shutcut_window = imgui.MenuItem('Shutcut', nil, show_shutcut_window) imgui.Separator() if imgui.MenuItem('Reload', 'Ctrl+F12') then puss.reload() end imgui.Separator() if puss.debug then if imgui.MenuItem('Load Debugger') then if puss._sep=='\\' then os.execute(string.format('start /B %s\\%s --main=core.debugger --Xconsole', puss._path, puss._self)) else os.execute(string.format('%s/%s --main=core.debugger &', puss._path, puss._self)) end end if puss.debug('running') then if imgui.MenuItem('Stop debug') then puss.debug(false) end else if imgui.MenuItem('Start debug ...') then puss.debug(true) end end else if imgui.MenuItem('Reboot As Debug Mode') then puss._reboot_as_debug_level = 9 main_ui:set_should_close(true) end end imgui.EndMenu() end imgui.EndMenuBar() if shotcuts.is_pressed('app/reload') then puss.reload() end end local function left_pane() imgui.BeginChild('PussLeftPane', 0, 0, false) main_ui:protect_pcall(filebrowser.update) imgui.EndChild() end local function pages_on_drop_files(files) for path in files:gmatch('(.-)\n') do docs.open(path) end end local function main_pane() imgui.BeginChild('PussPagesPane', 0, 0, false) if imgui.IsWindowHovered(ImGuiHoveredFlags_ChildWindows) then local files = imgui.GetDropFiles() if files then pages_on_drop_files(files) end end pages.update(main_ui) imgui.EndChild() end local MAIN_WINDOW_FLAGS = ( ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoBringToFrontOnFocus ) local function show_main_window(is_init) imgui.SetNextWindowPos(0, 0) imgui.SetNextWindowSize(imgui.GetIODisplaySize()) imgui.Begin('PussMainWindow', nil, MAIN_WINDOW_FLAGS) main_menu() imgui.Columns(2) if is_init then imgui.SetColumnWidth(-1, 200) end left_pane() imgui.NextColumn() main_pane() imgui.NextColumn() imgui.Columns(1) imgui.End() end local function do_quit_update() if run_sign and main_ui:should_close() then if pages.save_all(true) then run_sign = false else imgui.OpenPopup('Quit?') main_ui:set_should_close(false) end end if imgui.BeginPopupModal('Quit?') then imgui.Text('Quit?') imgui.Separator() if imgui.Button('Save all & Quit') then if pages.save_all() then run_sign = false else imgui.CloseCurrentPopup() main_ui:set_should_close(false) end end imgui.SameLine() if imgui.Button('Quit without save') then run_sign = false end imgui.SameLine() if imgui.Button('Cancel') then imgui.CloseCurrentPopup() main_ui:set_should_close(false) end imgui.EndPopup() end end local function do_update(is_init) show_main_window(is_init) if show_imgui_demos then show_imgui_demos = imgui.ShowDemoWindow(show_imgui_demos) end if show_tabs_demo then show_tabs_demo = imgui.ShowTabsDemo('Tabs Demo', show_tabs_demo) end if show_console_window then show_console_window = console.update(show_console_window) end if show_shutcut_window then show_shutcut_window = shotcuts.update(show_shutcut_window) end do_quit_update() end __exports.init = function() main_ui = imgui.Create('Puss - Editor', 1024, 768) _main_ui = main_ui main_ui:set_error_handle(puss.logerr_handle()) main_ui(do_update, true) end __exports.uninit = function() main_ui:destroy() main_ui = nil end __exports.update = function() main_ui(do_update) return run_sign end
-- app.lua local shotcuts = puss.import('core.shotcuts') local pages = puss.import('core.pages') local docs = puss.import('core.docs') local demos = puss.import('core.demos') local filebrowser = puss.import('core.filebrowser') local console = puss.import('core.console') local diskfs = puss.import('core.diskfs') filebrowser.setup(diskfs) docs.setup(diskfs) local run_sign = true local main_ui = _main_ui show_imgui_demos = show_imgui_demos or false show_tabs_demo = show_tabs_demo or false show_console_window = show_console_window or false show_shutcut_window = show_shutcut_window or false shotcuts.register('app/reload', 'Reload scripts', 'F12', true, false, false, false) local function main_menu() local active if not imgui.BeginMenuBar() then return end if imgui.BeginMenu('File') then if imgui.MenuItem('Add puss path FileBrowser') then filebrowser.append_folder(puss.local_to_utf8(puss._path)) end if imgui.MenuItem('Add Demo Tab') then demos.new_page() end if imgui.MenuItem('New page') then docs.new_page() end if imgui.MenuItem('Open app.lua') then docs.open(puss._path .. '/core/app.lua') end if imgui.MenuItem('Open console.lua') then docs.open(puss._path .. '/core/console.lua') end imgui.EndMenu() end if imgui.BeginMenu('Help') then active, show_imgui_demos = imgui.MenuItem('ImGUI Demos', nil, show_imgui_demos) active, show_tabs_demo = imgui.MenuItem('Tabs Demo', nil, show_tabs_demo) active, show_console_window = imgui.MenuItem('Conosle', nil, show_console_window) active, show_shutcut_window = imgui.MenuItem('Shutcut', nil, show_shutcut_window) imgui.Separator() if imgui.MenuItem('Reload', 'Ctrl+F12') then puss.reload() end imgui.Separator() if puss.debug then if imgui.MenuItem('Load Debugger') then if puss._sep=='\\' then os.execute(string.format('start /B %s\\%s --main=core.debugger --Xconsole', puss._path, puss._self)) else os.execute(string.format('%s/%s --main=core.debugger &', puss._path, puss._self)) end end if puss.debug('running') then if imgui.MenuItem('Stop debug') then puss.debug(false) end else if imgui.MenuItem('Start debug ...') then puss.debug(true) end end else if imgui.MenuItem('Reboot As Debug Mode') then puss._reboot_as_debug_level = 9 main_ui:set_should_close(true) end end imgui.EndMenu() end imgui.EndMenuBar() if shotcuts.is_pressed('app/reload') then puss.reload() end end local function left_pane() imgui.BeginChild('PussLeftPane', 0, 0, false) main_ui:protect_pcall(filebrowser.update) imgui.EndChild() end local function pages_on_drop_files(files) for path in files:gmatch('(.-)\n') do docs.open(path) end end local function main_pane() imgui.BeginChild('PussPagesPane', 0, 0, false) if imgui.IsWindowHovered(ImGuiHoveredFlags_ChildWindows) then local files = imgui.GetDropFiles() if files then pages_on_drop_files(files) end end pages.update(main_ui) imgui.EndChild() end local MAIN_WINDOW_FLAGS = ( ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoBringToFrontOnFocus ) local function show_main_window(is_init) imgui.SetNextWindowPos(0, 0) imgui.SetNextWindowSize(imgui.GetIODisplaySize()) imgui.Begin('PussMainWindow', nil, MAIN_WINDOW_FLAGS) main_menu() imgui.Columns(2) if is_init then imgui.SetColumnWidth(-1, 200) end left_pane() imgui.NextColumn() main_pane() imgui.NextColumn() imgui.Columns(1) imgui.End() if show_imgui_demos then show_imgui_demos = imgui.ShowDemoWindow(show_imgui_demos) end if show_tabs_demo then show_tabs_demo = imgui.ShowTabsDemo('Tabs Demo', show_tabs_demo) end if show_console_window then show_console_window = console.update(show_console_window) end if show_shutcut_window then show_shutcut_window = shotcuts.update(show_shutcut_window) end end local function do_quit_update() if run_sign and main_ui:should_close() then if pages.save_all(true) then run_sign = false else imgui.OpenPopup('Quit?') main_ui:set_should_close(false) end end if imgui.BeginPopupModal('Quit?') then imgui.Text('Quit?') imgui.Separator() if imgui.Button('Save all & Quit') then if pages.save_all() then run_sign = false else imgui.CloseCurrentPopup() main_ui:set_should_close(false) end end imgui.SameLine() if imgui.Button('Quit without save') then run_sign = false end imgui.SameLine() if imgui.Button('Cancel') then imgui.CloseCurrentPopup() main_ui:set_should_close(false) end imgui.EndPopup() end end local function do_update() main_ui:protect_pcall(show_main_window) do_quit_update() end __exports.init = function() main_ui = imgui.Create('Puss - Editor', 1024, 768) _main_ui = main_ui main_ui:set_error_handle(puss.logerr_handle()) main_ui(show_main_window, true) end __exports.uninit = function() main_ui:destroy() main_ui = nil end __exports.update = function() main_ui(do_update) return run_sign end
fix code
fix code
Lua
mit
louisliangjun/puss,louisliangjun/puss,louisliangjun/puss,louisliangjun/puss
a0fd9ce046928e1b4635b9a1f26bf218dcc5ca24
share/lua/website/sevenload.lua
share/lua/website/sevenload.lua
-- libquvi-scripts -- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com> -- -- 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 = "sevenload%.com" r.formats = "default" r.categories = C.proto_http -- TODO: Use quvi/util:handles instead r.handles = (self.page_url ~= nil and self.page_url:match(r.domain) ~= nil) 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 = "sevenload" local p = quvi.fetch(self.page_url) local c_url = p:match('configPath=(.-)"') or error("no match: config URL") local U = require 'quvi/util' c_url = U.unescape(c_url) local c = quvi.fetch(c_url, {fetch_type = 'config'}) self.title = c:match('<item id=.-<title>(.-)</title>') or error("no match: media title") self.id = c_url:match("itemId=(%w+)") or error("no match: media id") self.url = {c:match('<location seeking="yes">(.-)</') or error("no match: media URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This 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 = "sevenload%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {'/videos/'}) 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 = "sevenload" local p = quvi.fetch(self.page_url):gsub('&quot;','"') self.thumbnail_url = p:match('"og:image" content="(.-)"') or '' self.title = p:match('"og:title" content="(.-)"') or error('no match: media title') self.id = p:match('videoid":"(.-)"') or error("no match: media id") self.url = {p:match('src.+"(http://.+%.mp4)"') or error("no match: media stream URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: website/sevenload.lua: all patterns
FIX: website/sevenload.lua: all patterns * `ident': Use `handles' function of 'quvi/util' * `parse': Update media {title,id,url} patterns * `parse': Parse thumb url Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
377c2283e62ed936df6d6bd800cd67cf8c691bcf
premake5.lua
premake5.lua
-- A solution contains projects, and defines the available configurations solution "graphicsByExample" configurations { "Debug", "Release"} flags { "Unicode" , "NoPCH"} srcDirs = os.matchdirs("src/*") for i, projectName in ipairs(srcDirs) do -- A project defines one build target project (path.getname(projectName)) kind "ConsoleApp" location (projectName) language "C++" targetdir ( projectName ) configuration { "windows" } buildoptions "" linkoptions { "/NODEFAULTLIB:msvcrt" } -- https://github.com/yuriks/robotic/blob/master/premake5.lua configuration { "linux" } buildoptions "-std=c++11" --http://industriousone.com/topic/xcode4-c11-build-option toolset "gcc" configuration {} files { path.join(projectName, "**.h"), path.join(projectName, "**.cpp") } -- build all .h and .cpp files recursively excludes { "./graphics_dependencies/**" } -- don't build files in graphics_dependencies/ -- where are header files? -- tag::headers[] configuration "windows" includedirs { "./graphics_dependencies/SDL2/include", "./graphics_dependencies/glew/include", "./graphics_dependencies/glm", "./graphics_dependencies/SDL2_image/include", } configuration { "linux" } includedirs { -- should be installed as in ./graphics_dependencies/README.asciidoc } configuration {} -- end::headers[] -- what libraries need linking to -- tag::libraries[] configuration "windows" links { "SDL2", "SDL2main", "opengl32", "glew32", "SDL2_image" } configuration "linux" links { "SDL2", "SDL2main", "GL", "GLEW", "SDL2_image" } configuration {} -- end::libraries[] -- where are libraries? -- tag::librariesDirs[] configuration "windows" libdirs { "./graphics_dependencies/glew/lib/Release/Win32", "./graphics_dependencies/SDL2/lib/win32", "./graphics_dependencies/SDL2_image/lib/x86/", } configuration "linux" -- should be installed as in ./graphics_dependencies/README.asciidoc configuration {} -- end::librariesDirs[] configuration "*Debug" defines { "DEBUG" } flags { "Symbols" } optimize "Off" targetsuffix "-debug" configuration "*Release" defines { "NDEBUG" } optimize "On" targetsuffix "-release" -- copy dlls on windows -- tag::windowsDLLCopy[] if os.get() == "windows" then os.copyfile("./graphics_dependencies/glew/bin/Release/Win32/glew32.dll", path.join(projectName, "glew32.dll")) os.copyfile("./graphics_dependencies/SDL2/lib/win32/SDL2.dll", path.join(projectName, "SDL2.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/SDL2_image.dll", path.join(projectName, "SDL2_image.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libjpeg-9.dll", path.join(projectName, "libjpeg-9.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libpng16-16.dll", path.join(projectName, "libpng16-16.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libtiff-5.dll", path.join(projectName, "libtiff-5.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libwebp-4.dll", path.join(projectName, "libwebp-4.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/zlib1.dll", path.join(projectName, "zlib1.dll")) end -- end::windowsDLLCopy[] end
-- A solution contains projects, and defines the available configurations solution "graphicsByExample" configurations { "Debug", "Release"} flags { "Unicode" , "NoPCH"} srcDirs = os.matchdirs("src/*") for i, projectName in ipairs(srcDirs) do -- A project defines one build target project (path.getname(projectName)) kind "ConsoleApp" location (projectName) language "C++" targetdir ( projectName ) configuration { "windows" } buildoptions "" linkoptions { "/NODEFAULTLIB:msvcrt" } -- https://github.com/yuriks/robotic/blob/master/premake5.lua configuration { "linux" } buildoptions "-std=c++11" --http://industriousone.com/topic/xcode4-c11-build-option toolset "gcc" configuration {} files { path.join(projectName, "**.h"), path.join(projectName, "**.cpp") } -- build all .h and .cpp files recursively excludes { "./graphics_dependencies/**" } -- don't build files in graphics_dependencies/ -- where are header files? -- tag::headers[] configuration "windows" includedirs { "./graphics_dependencies/SDL2/include", "./graphics_dependencies/SDL2/include/SDL2", "./graphics_dependencies/glew/include", "./graphics_dependencies/glm", "./graphics_dependencies/SDL2_image/include", } configuration { "linux" } includedirs { -- should be installed as in ./graphics_dependencies/README.asciidoc } configuration {} -- end::headers[] -- what libraries need linking to -- tag::libraries[] configuration "windows" links { "SDL2", "SDL2main", "opengl32", "glew32", "SDL2_image" } configuration "linux" links { "SDL2", "SDL2main", "GL", "GLEW", "SDL2_image" } configuration {} -- end::libraries[] -- where are libraries? -- tag::librariesDirs[] configuration "windows" libdirs { "./graphics_dependencies/glew/lib/Release/Win32", "./graphics_dependencies/SDL2/lib/win32", "./graphics_dependencies/SDL2_image/lib/x86/", } configuration "linux" -- should be installed as in ./graphics_dependencies/README.asciidoc configuration {} -- end::librariesDirs[] configuration "*Debug" defines { "DEBUG" } flags { "Symbols" } optimize "Off" targetsuffix "-debug" configuration "*Release" defines { "NDEBUG" } optimize "On" targetsuffix "-release" -- copy dlls on windows -- tag::windowsDLLCopy[] if os.get() == "windows" then os.copyfile("./graphics_dependencies/glew/bin/Release/Win32/glew32.dll", path.join(projectName, "glew32.dll")) os.copyfile("./graphics_dependencies/SDL2/lib/win32/SDL2.dll", path.join(projectName, "SDL2.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/SDL2_image.dll", path.join(projectName, "SDL2_image.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libjpeg-9.dll", path.join(projectName, "libjpeg-9.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libpng16-16.dll", path.join(projectName, "libpng16-16.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libtiff-5.dll", path.join(projectName, "libtiff-5.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/libwebp-4.dll", path.join(projectName, "libwebp-4.dll")) os.copyfile("./graphics_dependencies/SDL2_image/lib/x86/zlib1.dll", path.join(projectName, "zlib1.dll")) end -- end::windowsDLLCopy[] end
fix windows search path issue
fix windows search path issue
Lua
mit
shearer12345/graphicsByExample
599c27799c1b52b7f3732a915f65f8f9fe249b57
tundra.lua
tundra.lua
require "tundra.native" local native = require('tundra.native') local macosx = { Env = { QT5 = native.getenv("QT5"), CCOPTS = { "-Wall", "-I.", "-DPRODBG_MAC", "-Weverything", "-Wno-c++98-compat-pedantic", "-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, CXXOPTS = { "-I.", "-DPRODBG_MAC", "-Weverything", "-Werror", "-Wno-c++98-compat-pedantic", "-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded", "-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, }, Frameworks = { "Cocoa" }, } local win64 = { Env = { QT5 = native.getenv("QT5"), GENERATE_PDB = "1", CCOPTS = { "/DPRODBG_WIN", "/FS", "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, CXXOPTS = { "/DPRODBG_WIN", "/FS", "/MT", "/I.", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", "\"/DOBJECT_DIR=$(OBJECTDIR:#)\"", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, }, } Build { Passes = { GenerateSources = { Name="Generate sources", BuildOrder = 1 }, }, Units = "units.lua", Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } }, }, 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 }, }, }
require "tundra.native" local native = require('tundra.native') local macosx = { Env = { QT5 = native.getenv("QT5"), CCOPTS = { "-Wall", "-I.", "-DPRODBG_MAC", "-Weverything", "-Wno-c++98-compat-pedantic", "-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, CXXOPTS = { "-I.", "-DPRODBG_MAC", "-Weverything", "-Werror", "-Wno-exit-time-destructors", "-Wno-c++98-compat-pedantic", "-Wno-used-but-marked-unused", "-Wno-documentation", "-Wno-missing-prototypes", "-Wno-padded", "-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, }, Frameworks = { "Cocoa" }, } local win64 = { Env = { QT5 = native.getenv("QT5"), GENERATE_PDB = "1", CCOPTS = { "/DPRODBG_WIN", "/FS", "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, CXXOPTS = { "/DPRODBG_WIN", "/FS", "/MT", "/I.", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", "\"/DOBJECT_DIR=$(OBJECTDIR:#)\"", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, }, } Build { Passes = { GenerateSources = { Name="Generate sources", BuildOrder = 1 }, }, Units = "units.lua", Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } }, }, 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 }, }, }
More warning fixes
More warning fixes
Lua
mit
kondrak/ProDBG,RobertoMalatesta/ProDBG,v3n/ProDBG,v3n/ProDBG,emoon/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,kondrak/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,kondrak/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,v3n/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,emoon/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,emoon/ProDBG
8765bf7d5deddfac2f83530f8e8e6c50f2fc2c73
BtEvaluatorLoader.lua
BtEvaluatorLoader.lua
function widget:GetInfo() return { name = "BtEvaluator loader", desc = "BtEvaluator loader and message test to this AI.", author = "JakubStasta", date = "Sep 20, 2016", license = "BY-NC-SA", layer = 0, enabled = true, -- loaded by default? version = version, } end local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) local JSON = Utils.JSON local Sentry = Utils.Sentry local Dependency = Utils.Dependency local Debug = Utils.Debug local Logger, dump, copyTable, fileTable = Debug.Logger, Debug.dump, Debug.copyTable, Debug.fileTable -- BtEvaluator interface definitions local BtEvaluator = Sentry:New() function BtEvaluator.sendMessage(messageType, messageData) local payload = "BETS " .. messageType; if(messageData)then payload = payload .. " " if(type(messageData) == "string")then payload = payload .. messageData else payload = payload .. JSON:encode(messageData) end end Logger.log("communication", payload) Spring.SendSkirmishAIMessage(Spring.GetLocalPlayerID(), payload) end function BtEvaluator.requestNodeDefinitions() BtEvaluator.sendMessage("REQUEST_NODE_DEFINITIONS") end function BtEvaluator.assignUnits() BtEvaluator.sendMessage("ASSIGN_UNITS") end function BtEvaluator.createTree(treeDefinition) BtEvaluator.sendMessage("CREATE_TREE", JSON:encode(treeDefinition.root)) end function widget:Initialize() --Spring.SendCommands("AIKill " ..Spring.GetLocalPlayerID()) BtEvaluator.sendMessage("REINITIALIZE") Spring.SendCommands("AIControl "..Spring.GetLocalPlayerID().." BtEvaluator") WG.BtEvaluator = BtEvaluator end function widget:RecvSkirmishAIMessage(aiTeam, message) Logger.log("communication", "Received message from team " .. tostring(aiTeam) .. ": " .. message) -- Dont respond to other players AI if(aiTeam ~= Spring.GetLocalPlayerID()) then return end -- Check if it starts with "BETS" if(message:len() <= 4 and message:sub(1,4):upper() ~= "BETS") then return end local messageShorter = message:sub(6) local indexOfFirstSpace = string.find(messageShorter, " ") or (message:len() + 1) local messageType = messageShorter:sub(1, indexOfFirstSpace - 1):upper() -- messages without parameter if(messageType == "LOG") then Logger.log("BtEvaluator", messageBody) return true elseif(messageType == "INITIALIZED") then Dependency.fill(Dependency.BtEvaluator) return true else local handler = ({ ["UPDATE_STATES"] = BtEvaluator.OnUpdateStates, ["NODE_DEFINITIONS"] = BtEvaluator.OnNodeDefinitions, ["COMMAND"] = BtEvaluator.OnCommand, })[messageType] if(handler)then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) return handler:Invoke(data) end end end
function widget:GetInfo() return { name = "BtEvaluator loader", desc = "BtEvaluator loader and message test to this AI.", author = "JakubStasta", date = "Sep 20, 2016", license = "BY-NC-SA", layer = 0, enabled = true, -- loaded by default? version = version, } end local Utils = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) local JSON = Utils.JSON local Sentry = Utils.Sentry local Dependency = Utils.Dependency local Debug = Utils.Debug local Logger, dump, copyTable, fileTable = Debug.Logger, Debug.dump, Debug.copyTable, Debug.fileTable -- BtEvaluator interface definitions local BtEvaluator = Sentry:New() function BtEvaluator.sendMessage(messageType, messageData) local payload = "BETS " .. messageType; if(messageData)then payload = payload .. " " if(type(messageData) == "string")then payload = payload .. messageData else payload = payload .. JSON:encode(messageData) end end Logger.log("communication", payload) Spring.SendSkirmishAIMessage(Spring.GetLocalPlayerID(), payload) end function BtEvaluator.requestNodeDefinitions() BtEvaluator.sendMessage("REQUEST_NODE_DEFINITIONS") end function BtEvaluator.assignUnits() BtEvaluator.sendMessage("ASSIGN_UNITS") end function BtEvaluator.createTree(treeDefinition) BtEvaluator.sendMessage("CREATE_TREE", JSON:encode(treeDefinition.root)) end function widget:Initialize() WG.BtEvaluator = BtEvaluator --Spring.SendCommands("AIKill " ..Spring.GetLocalPlayerID()) BtEvaluator.sendMessage("REINITIALIZE") Spring.SendCommands("AIControl "..Spring.GetLocalPlayerID().." BtEvaluator") end function widget:RecvSkirmishAIMessage(aiTeam, message) Logger.log("communication", "Received message from team " .. tostring(aiTeam) .. ": " .. message) -- Dont respond to other players AI if(aiTeam ~= Spring.GetLocalPlayerID()) then return end -- Check if it starts with "BETS" if(message:len() <= 4 and message:sub(1,4):upper() ~= "BETS") then return end local messageShorter = message:sub(6) local indexOfFirstSpace = string.find(messageShorter, " ") or (message:len() + 1) local messageType = messageShorter:sub(1, indexOfFirstSpace - 1):upper() -- messages without parameter if(messageType == "LOG") then Logger.log("BtEvaluator", messageBody) return true elseif(messageType == "INITIALIZED") then Dependency.fill(Dependency.BtEvaluator) return true else local handler = ({ ["UPDATE_STATES"] = BtEvaluator.OnUpdateStates, ["NODE_DEFINITIONS"] = BtEvaluator.OnNodeDefinitions, ["COMMAND"] = BtEvaluator.OnCommand, })[messageType] if(handler)then local messageBody = messageShorter:sub(indexOfFirstSpace + 1) local data = JSON:decode(messageBody) return handler:Invoke(data) end end end
initialization order fix
initialization order fix
Lua
mit
MartinFrancu/BETS
4b90807003ae345e2976d4b726a518fa8d70560d
lexers/bash.lua
lexers/bash.lua
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- Shell LPeg lexer. local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, '#' * l.nonnewline^0) -- Strings. local sq_str = l.delimited_range("'", nil, true) local dq_str = l.delimited_range('"', '\\', true) local ex_str = l.delimited_range('`', '\\', true) local heredoc = '<<' * P(function(input, index) local s, e, _, delimiter = input:find('(["\']?)([%a_][%w_]*)%1[\n\r\f;]+', index) if s == index and delimiter then local _, e = input:find('[\n\r\f]+'..delimiter, e) return e and e + 1 or #input + 1 end end) local string = token(l.STRING, sq_str + dq_str + ex_str + heredoc) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match({ 'if', 'then', 'elif', 'else', 'fi', 'case', 'in', 'esac', 'while', 'for', 'do', 'done', 'continue', 'local', 'return', 'select', -- Operators. '-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-k', '-p', '-r', '-s', '-t', '-u', '-w', '-x', '-O', '-G', '-L', '-S', '-N', '-nt', '-ot', '-ef', '-o', '-z', '-n', '-eq', '-ne', '-lt', '-le', '-gt', '-ge' }, '-')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local variable = token(l.VARIABLE, '$' * (S('!#?*@$') + l.digit^1 + l.word + l.delimited_range('()', nil, true, false, '\n') + l.delimited_range('[]', nil, true, false, '\n') + l.delimited_range('{}', nil, true, false, '\n') + l.delimited_range('`', nil, true, false, '\n'))) -- Operators. local operator = token(l.OPERATOR, S('=!<>+-/*^~.,:;?()[]{}')) _rules = { { 'whitespace', ws }, { 'keyword', keyword }, { 'identifier', identifier }, { 'string', string }, { 'comment', comment }, { 'number', number }, { 'variable', variable }, { 'operator', operator }, { 'any_char', l.any_char }, } _foldsymbols = { _patterns = { '[a-z]+', '[{}]', '#' }, [l.KEYWORD] = { ['if'] = 1, fi = -1, case = 1, esac = -1, ['do'] = 1, done = -1 }, [l.OPERATOR] = { ['{'] = 1, ['}'] = -1 }, [l.COMMENT] = { ['#'] = l.fold_line_comments('#') } }
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- Shell LPeg lexer. local l = lexer local token, style, color, word_match = l.token, l.style, l.color, l.word_match local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S module(...) -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, '#' * l.nonnewline^0) -- Strings. local sq_str = l.delimited_range("'", nil, true) local dq_str = l.delimited_range('"', '\\', true) local ex_str = l.delimited_range('`', '\\', true) local heredoc = '<<' * P(function(input, index) local s, e, _, delimiter = input:find('(["\']?)([%a_][%w_]*)%1[\n\r\f;]+', index) if s == index and delimiter then local _, e = input:find('[\n\r\f]+'..delimiter, e) return e and e + 1 or #input + 1 end end) local string = token(l.STRING, sq_str + dq_str + ex_str + heredoc) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match({ 'if', 'then', 'elif', 'else', 'fi', 'case', 'in', 'esac', 'while', 'for', 'do', 'done', 'continue', 'local', 'return', 'select', -- Operators. '-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-k', '-p', '-r', '-s', '-t', '-u', '-w', '-x', '-O', '-G', '-L', '-S', '-N', '-nt', '-ot', '-ef', '-o', '-z', '-n', '-eq', '-ne', '-lt', '-le', '-gt', '-ge' }, '-')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local variable = token(l.VARIABLE, '$' * (S('!#?*@$') + l.digit^1 + l.word + l.delimited_range('{}', nil, true, false, '\n'))) -- Operators. local operator = token(l.OPERATOR, S('=!<>+-/*^~.,:;?()[]{}')) _rules = { { 'whitespace', ws }, { 'keyword', keyword }, { 'identifier', identifier }, { 'string', string }, { 'comment', comment }, { 'number', number }, { 'variable', variable }, { 'operator', operator }, { 'any_char', l.any_char }, } _foldsymbols = { _patterns = { '[a-z]+', '[{}]', '#' }, [l.KEYWORD] = { ['if'] = 1, fi = -1, case = 1, esac = -1, ['do'] = 1, done = -1 }, [l.OPERATOR] = { ['{'] = 1, ['}'] = -1 }, [l.COMMENT] = { ['#'] = l.fold_line_comments('#') } }
Fixed highlighting of variables in bash; lexers/bash.lua
Fixed highlighting of variables in bash; lexers/bash.lua
Lua
mit
rgieseke/scintillua
4f0e25f8ec3e429bd59cc9132f70fa0f54d19871
script/c80600016.lua
script/c80600016.lua
--ゴーストリック・ランタン function c80600016.initial_effect(c) --sumlimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetCondition(c80600016.sumcon) c:RegisterEffect(e1) --turn set local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c80600016.target) e2:SetOperation(c80600016.operation) c:RegisterEffect(e2) --negate local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(80600016,0)) e3:SetProperty(EFFECT_FLAG_CHAIN_UNIQUE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_ATTACK_ANNOUNCE) e3:SetRange(LOCATION_HAND) e3:SetCondition(c80600016.negcon) e3:SetTarget(c80600016.negtg) e3:SetOperation(c80600016.negop) c:RegisterEffect(e3) end function c80600016.sumfilter(c) return c:IsFaceup() and c:IsSetCard(0x91) end function c80600016.sumcon(e) return not Duel.IsExistingMatchingCard(c80600016.sumfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c80600016.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(80600016)==0 end c:RegisterFlagEffect(80600016,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c80600016.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE) end end function c80600016.negcon(e,tp,eg,ep,ev,re,r,rp) local at=Duel.GetAttacker() return at:GetControler()~=tp and Duel.GetAttackTarget()==nil or at:GetControler()~=tp and Duel.GetAttackTarget():IsSetCard(0x91) and Duel.GetAttackTarget():IsFaceup() end function c80600016.negtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsCanBeSpecialSummoned(e,0,tp,false,false) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end local g=Duel.GetAttacker() Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_NEGATE,tg,1,0,0) end function c80600016.negop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then if Duel.NegateAttack() and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) end end end
--ゴーストリック・ランタン function c80600016.initial_effect(c) --sumlimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetCondition(c80600016.sumcon) c:RegisterEffect(e1) --turn set local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c80600016.target) e2:SetOperation(c80600016.operation) c:RegisterEffect(e2) --negate local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(80600016,0)) e3:SetProperty(EFFECT_FLAG_CHAIN_UNIQUE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_ATTACK_ANNOUNCE) e3:SetRange(LOCATION_HAND) e3:SetCondition(c80600016.negcon) e3:SetTarget(c80600016.negtg) e3:SetOperation(c80600016.negop) c:RegisterEffect(e3) end function c80600016.sumfilter(c) return c:IsFaceup() and c:IsSetCard(0x91) end function c80600016.sumcon(e) return not Duel.IsExistingMatchingCard(c80600016.sumfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c80600016.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(80600016)==0 end c:RegisterFlagEffect(80600016,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c80600016.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE) end end function c80600016.negcon(e,tp,eg,ep,ev,re,r,rp) local at=Duel.GetAttacker() return at:GetControler()~=tp and Duel.GetAttackTarget()==nil or at:GetControler()~=tp and Duel.GetAttackTarget():IsSetCard(0x91) and Duel.GetAttackTarget():IsFaceup() end function c80600016.negtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsCanBeSpecialSummoned(e,0,tp,false,false) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end Duel.SetOperationInfo(0,CATEGORY_NEGATE,tg,1,0,0) end function c80600016.negop(e,tp,eg,ep,ev,re,r,rp) if Duel.NegateAttack() and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEDOWN_DEFENCE) end end
fix
fix no longer targets
Lua
mit
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
3648198b088b80aafeefad7e5b519fcf2caaaee3
Hammerspoon/setup.lua
Hammerspoon/setup.lua
local modpath, prettypath, fullpath, configdir, docstringspath, hasinitfile, autoload_extensions = ... os.exit = hs._exit local function runstring(s) local fn, err = load("return " .. s) if not fn then fn, err = load(s) end if not fn then return tostring(err) end local str = "" local results = table.pack(pcall(fn)) for i = 2,results.n do if i > 2 then str = str .. "\t" end str = str .. tostring(results[i]) end return str end --- hs.configdir = "~/.hammerspoon/" --- Constant --- The user's Hammerspoon config directory. Modules may use it, assuming --- they've worked out a contract with the user about how to use it. hs.configdir = configdir --- hs.docstrings_json_file --- Constant --- This is the full path to the docs.json file shipped with Hammerspoon. --- It contains the same documentation used to generate the full Hammerspoon --- API documentation, in JSON form. --- You can load, parse and access this information using the hs.doc extension hs.docstrings_json_file = docstringspath --- hs.showerror(err) --- Function --- --- Presents an error to the user via Hammerspoon's GUI. The default --- implementation prints the error, focuses Hammerspoon, and opens --- Hammerspoon's console. --- --- Users can override this with a new function that shows errors in a --- custom way. --- --- Modules can call this in the event of an error, e.g. in callbacks --- from the user: --- --- local ok, err = xpcall(callbackfn, debug.traceback) --- if not ok then hs.showerror(err) end function hs.showerror(err) hs._notify("Hammerspoon config error") -- undecided on this line print(err) hs.focus() hs.openconsole() end --- hs.rawprint = print --- Function --- The original print function, before hammerspoon overrides it. local rawprint = print hs.rawprint = rawprint function print(...) rawprint(...) local vals = table.pack(...) for k = 1, vals.n do vals[k] = tostring(vals[k]) end local str = table.concat(vals, "\t") .. "\n" hs._logmessage(str) end print("-- Augmenting require paths") package.path=package.path..";"..modpath.."/?.lua"..";"..modpath.."/?/init.lua" package.cpath=package.cpath..";"..modpath.."/?.so" if autoload_extensions then print("-- Lazily loading extensions") hs._extensions = {} -- Discover extensions in our .app bundle local iter, dir_obj = require("hs.fs").dir(modpath.."/hs") local extension = iter(dir_obj) while extension do if (extension ~= ".") and (extension ~= "..") then hs._extensions[extension] = true end extension = iter(dir_obj) end -- Inject a lazy extension loader into the main HS table setmetatable(hs, { __index = function(t, key) if hs._extensions[key] ~= nil then print("-- Loading extension: "..key) hs[key] = require("hs."..key) return hs[key] else return nil end end }) end function help(identifier) local doc = require "hs.doc" local tree = doc.from_json_file(hs.docstrings_json_file) local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end if not hasinitfile then hs.notify.register("__noinitfile", function() os.execute("open http://www.hammerspoon.org/go/") end) hs.notify.show("Hammerspoon", "No config file found", "Click here for the Getting Started Guide", "__noinitfile") print(string.format("-- Can't find %s; create it and reload your config.", prettypath)) return runstring end print("-- Loading " .. prettypath) local fn, err = loadfile(fullpath) if not fn then hs.showerror(err) return runstring end local ok, err = xpcall(fn, debug.traceback) if not ok then hs.showerror(err) return runstring end print "-- Done." return runstring
local modpath, prettypath, fullpath, configdir, docstringspath, hasinitfile, autoload_extensions = ... os.exit = hs._exit local function runstring(s) local fn, err = load("return " .. s) if not fn then fn, err = load(s) end if not fn then return tostring(err) end local str = "" local results = table.pack(pcall(fn)) for i = 2,results.n do if i > 2 then str = str .. "\t" end str = str .. tostring(results[i]) end return str end --- hs.configdir = "~/.hammerspoon/" --- Constant --- The user's Hammerspoon config directory. Modules may use it, assuming --- they've worked out a contract with the user about how to use it. hs.configdir = configdir --- hs.docstrings_json_file --- Constant --- This is the full path to the docs.json file shipped with Hammerspoon. --- It contains the same documentation used to generate the full Hammerspoon --- API documentation, in JSON form. --- You can load, parse and access this information using the hs.doc extension hs.docstrings_json_file = docstringspath --- hs.showerror(err) --- Function --- --- Presents an error to the user via Hammerspoon's GUI. The default --- implementation prints the error, focuses Hammerspoon, and opens --- Hammerspoon's console. --- --- Users can override this with a new function that shows errors in a --- custom way. --- --- Modules can call this in the event of an error, e.g. in callbacks --- from the user: --- --- local ok, err = xpcall(callbackfn, debug.traceback) --- if not ok then hs.showerror(err) end function hs.showerror(err) hs._notify("Hammerspoon config error") -- undecided on this line print(err) hs.focus() hs.openconsole() end --- hs.rawprint = print --- Function --- The original print function, before hammerspoon overrides it. local rawprint = print hs.rawprint = rawprint function print(...) rawprint(...) local vals = table.pack(...) for k = 1, vals.n do vals[k] = tostring(vals[k]) end local str = table.concat(vals, "\t") .. "\n" hs._logmessage(str) end print("-- Augmenting require paths") package.path=configdir.."/?.lua"..";"..configdir.."/?/init.lua"..";"..package.path..";"..modpath.."/?.lua"..";"..modpath.."/?/init.lua" package.cpath=configdir.."/?.so"..";"..package.cpath..";"..modpath.."/?.so" print("-- package.path:") for part in string.gmatch(package.path, "([^;]+)") do print(" "..part) end print("-- package.cpath:") for part in string.gmatch(package.cpath, "([^;]+)") do print(" "..part) end if autoload_extensions then print("-- Lazy extension loading enabled") hs._extensions = {} -- Discover extensions in our .app bundle local iter, dir_obj = require("hs.fs").dir(modpath.."/hs") local extension = iter(dir_obj) while extension do if (extension ~= ".") and (extension ~= "..") then hs._extensions[extension] = true end extension = iter(dir_obj) end -- Inject a lazy extension loader into the main HS table setmetatable(hs, { __index = function(t, key) if hs._extensions[key] ~= nil then print("-- Loading extension: "..key) hs[key] = require("hs."..key) return hs[key] else return nil end end }) end function help(identifier) local doc = require "hs.doc" local tree = doc.from_json_file(hs.docstrings_json_file) local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end if not hasinitfile then hs.notify.register("__noinitfile", function() os.execute("open http://www.hammerspoon.org/go/") end) hs.notify.show("Hammerspoon", "No config file found", "Click here for the Getting Started Guide", "__noinitfile") print(string.format("-- Can't find %s; create it and reload your config.", prettypath)) return runstring end print("-- Loading " .. prettypath) local fn, err = loadfile(fullpath) if not fn then hs.showerror(err) return runstring end local ok, err = xpcall(fn, debug.traceback) if not ok then hs.showerror(err) return runstring end print "-- Done." return runstring
Fix up merge
Fix up merge
Lua
mit
knu/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,trishume/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,joehanchoi/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,knu/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,hypebeast/hammerspoon,ocurr/hammerspoon,dopcn/hammerspoon,joehanchoi/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,trishume/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,wsmith323/hammerspoon,bradparks/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,tmandry/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,nkgm/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,junkblocker/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,trishume/hammerspoon,knu/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,wvierber/hammerspoon,kkamdooong/hammerspoon,Hammerspoon/hammerspoon,wsmith323/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,wsmith323/hammerspoon,chrisjbray/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,kkamdooong/hammerspoon,wsmith323/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,junkblocker/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,joehanchoi/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon
3dd0e6dfa3e8d717718e1357f86cfa75edf2e719
MMOCoreORB/bin/scripts/quest/tasks/task.lua
MMOCoreORB/bin/scripts/quest/tasks/task.lua
-- Base module for all tasks. local ObjectManager = require("managers.object.object_manager") local Logger = require("utils.logger") Task = Object:new { taskName = "", taskStart = nil, taskFinish = nil, onLoggedIn = nil, onLoggedOut = nil, } local TASK_STARTED = 0xABCD -- Check if the task has been started for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:hasTaskStarted(pCreatureObject) return CreatureObject(pCreatureObject):getScreenPlayState(self.taskName) == TASK_STARTED end -- Set the task started screen play state for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:setTaskStarted(pCreatureObject) CreatureObject(pCreatureObject):setScreenPlayState(TASK_STARTED, self.taskName) end -- Set the task finished screen play state for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:setTaskFinished(pCreatureObject) CreatureObject(pCreatureObject):removeScreenPlayState(TASK_STARTED, self.taskName) end -- Call the supplied function with the argument if the function is not nil. -- An error will be issued if the function is nil. -- @param theFunction the function to call. -- @param argument the argument to use for the function. function Task:callFunctionIfNotNil(theFunction, returnIfNil, ...) if theFunction ~= nil then return theFunction(self, unpack({...})) else Logger:log("The function to call is nil in " .. Task.taskName .. ".", LT_INFO) return returnIfNil end end -- Start the task. -- @param pCreatureObject pointer to the creature object of the player who should get the task started. function Task:start(pCreatureObject, ...) if not self:hasTaskStarted(pCreatureObject) then Logger:log("Starting task " .. self.taskName, LT_INFO) if self:callFunctionIfNotNil(self.taskStart, true, pCreatureObject, unpack({...})) then Logger:log(self.taskName .. " started.", LT_INFO) self:setTaskStarted(pCreatureObject) end if self.onLoggedIn ~= nil then createObserver(LOGGEDIN, self.taskName, "onLoggedIn", pCreatureObject) end if self.onLoggedOut ~= nil then createObserver(LOGGEDOUT, self.taskName, "onLoggedOut", pCreatureObject) end else Logger:log("Task " .. self.taskName .. " is already started.", LT_INFO) end end -- Finish the task. -- @param pCreatureObject pointer to the creature object of the player who should get the task finished. function Task:finish(pCreatureObject) if self:hasTaskStarted(pCreatureObject) then Logger:log("Finishing task " .. self.taskName, LT_INFO) if self:callFunctionIfNotNil(self.taskFinish, true, pCreatureObject) == true then Logger:log(self.taskName .. " finished.", LT_INFO) self:setTaskFinished(pCreatureObject) end else Logger:log("Task " .. self.taskName .. " is not started.", LT_INFO) end end return Task
-- Base module for all tasks. local ObjectManager = require("managers.object.object_manager") local Logger = require("utils.logger") Task = Object:new { taskName = "", taskStart = nil, taskFinish = nil, onLoggedIn = nil, onLoggedOut = nil, } local TASK_STARTED = 0xABCD -- Check if the task has been started for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:hasTaskStarted(pCreatureObject) if (pCreatureObject == nil) then return false end return CreatureObject(pCreatureObject):getScreenPlayState(self.taskName) == TASK_STARTED end -- Set the task started screen play state for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:setTaskStarted(pCreatureObject) CreatureObject(pCreatureObject):setScreenPlayState(TASK_STARTED, self.taskName) end -- Set the task finished screen play state for the player. -- @param pCreatureObject pointer to the creature object of the player. function Task:setTaskFinished(pCreatureObject) CreatureObject(pCreatureObject):removeScreenPlayState(TASK_STARTED, self.taskName) end -- Call the supplied function with the argument if the function is not nil. -- An error will be issued if the function is nil. -- @param theFunction the function to call. -- @param argument the argument to use for the function. function Task:callFunctionIfNotNil(theFunction, returnIfNil, ...) if theFunction ~= nil then return theFunction(self, unpack({...})) else Logger:log("The function to call is nil in " .. Task.taskName .. ".", LT_INFO) return returnIfNil end end -- Start the task. -- @param pCreatureObject pointer to the creature object of the player who should get the task started. function Task:start(pCreatureObject, ...) if (pCreatureObject == nil) then return end if not self:hasTaskStarted(pCreatureObject) then Logger:log("Starting task " .. self.taskName, LT_INFO) if self:callFunctionIfNotNil(self.taskStart, true, pCreatureObject, unpack({...})) then Logger:log(self.taskName .. " started.", LT_INFO) self:setTaskStarted(pCreatureObject) end if self.onLoggedIn ~= nil then createObserver(LOGGEDIN, self.taskName, "onLoggedIn", pCreatureObject) end if self.onLoggedOut ~= nil then createObserver(LOGGEDOUT, self.taskName, "onLoggedOut", pCreatureObject) end else Logger:log("Task " .. self.taskName .. " is already started.", LT_INFO) end end -- Finish the task. -- @param pCreatureObject pointer to the creature object of the player who should get the task finished. function Task:finish(pCreatureObject) if (pCreatureObject == nil) then return end if self:hasTaskStarted(pCreatureObject) then Logger:log("Finishing task " .. self.taskName, LT_INFO) if self:callFunctionIfNotNil(self.taskFinish, true, pCreatureObject) == true then Logger:log(self.taskName .. " finished.", LT_INFO) self:setTaskFinished(pCreatureObject) end else Logger:log("Task " .. self.taskName .. " is not started.", LT_INFO) end end return Task
[fixed] Stability issue
[fixed] Stability issue Change-Id: I6e0cf81f627104c9790cb588343ee0be7773157c
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
bba6613f860fede6520ce9cc93ea3498668ff58e
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.fs") require("luci.ip") mp = Map("olsrd", "OLSR - Plugins") p = mp:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true p.anonymous = true ign = p:option(Flag, "ignore") ign.enabled = "1" ign.disabled = "0" ign.optional = true lib = p:option(ListValue, "library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")() local cidr if ip and mask and ip:match(":") then cidr = luci.ip.IPv6(ip, mask) elseif ip and mask then cidr = luci.ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "eth1" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_nameservice.so.0.2"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "10.247.200.4" } } } -- build plugin options with dependencies for plugin, options in pairs(knownPlParams) do for _, option in ipairs(options) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end if otype == DynamicList then field:value( default ) end field.default = default field:depends({ library = plugin }) end end end return mp
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.fs") require("luci.ip") mp = Map("olsrd", "OLSR - Plugins") p = mp:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true p.anonymous = true ign = p:option(Flag, "ignore") ign.enabled = "1" ign.disabled = "0" ign.optional = true lib = p:option(ListValue, "library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = luci.ip.IPv4(val[i]) or luci.ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s+])%s+([^%s+])")() local cidr if ip and mask and ip:match(":") then cidr = luci.ip.IPv6(ip, mask) elseif ip and mask then cidr = luci.ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "eth1" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "10.247.200.4" } } } -- build plugin options with dependencies for plugin, options in pairs(knownPlParams) do for _, option in ipairs(options) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end if otype == DynamicList then field:value( default ) end field.optional = true field.default = default field:depends({ library = plugin }) end end end return mp
* luci/app-olsr: further fixes in olsr plugins config
* luci/app-olsr: further fixes in olsr plugins config
Lua
apache-2.0
8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
6713bb355734516b3eeba35459a4a234dcc08c8f
tests/test-tls-remote.lua
tests/test-tls-remote.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. ]]-- require('helper') local fixture = require('./fixture-tls') local tls = require('tls') local options = { key = fixture.loadPEM('agent1-key'), cert = fixture.loadPEM('agent1-cert') } local server = tls.createServer(options, function(s) assert(s:address().address == s.socket:address().address) assert(s:address().port == s.socket:address().port) assert(s.remoteAddress == s.socket.remoteAddress) assert(s.remotePort == s.socket.remotePort) s:destroy() end) server:listen(fixture.commonPort, '127.0.0.1', function() assert(server:address().address == '127.0.0.1') assert(server:address().port == fixture.commonPort) local c c = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) c:on('end', function() assert(c:address().address == c.socket:address().address) assert(c:address().port == c.socket:address().port) c:destroy() server:close() end) end)
--[[ 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. ]]-- require('helper') local fixture = require('./fixture-tls') local tls = require('tls') local options = { key = fixture.loadPEM('agent1-key'), cert = fixture.loadPEM('agent1-cert') } local server = tls.createServer(options, function(s) assert(s:address().address == s.socket:address().address) assert(s:address().port == s.socket:address().port) assert(s.remoteAddress == s.socket.remoteAddress) assert(s.remotePort == s.socket.remotePort) s:done() end) server:listen(fixture.commonPort, '127.0.0.1', function() assert(server:address().address == '127.0.0.1') assert(server:address().port == fixture.commonPort) local c c = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}, function() assert(c:address().address == c.socket:address().address) assert(c:address().port == c.socket:address().port) end) c:on('end', function() server:close() end) end)
tests: test-tls-remote: fixup to match node
tests: test-tls-remote: fixup to match node fixup the logic in this test to match node's. In particular don't try to read the address after we have already destroyed.
Lua
apache-2.0
DBarney/luvit,bsn069/luvit,sousoux/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,sousoux/luvit,luvit/luvit,boundary/luvit,kaustavha/luvit,bsn069/luvit,boundary/luvit,DBarney/luvit,sousoux/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,boundary/luvit,sousoux/luvit,boundary/luvit,kaustavha/luvit,sousoux/luvit,luvit/luvit,rjeli/luvit,rjeli/luvit,boundary/luvit,rjeli/luvit,rjeli/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,DBarney/luvit,boundary/luvit
75f3fd2c61e5630992de93bc10fa300a796365d3
cookbooks/neovim/files/nvim/lua/plugins.lua
cookbooks/neovim/files/nvim/lua/plugins.lua
-- Packer.nvim bootstrapping -- see https://github.com/wbthomason/packer.nvim#bootstrapping -- TODO: Move to ~/.config/nvim/lua/init.lua local execute = vim.api.nvim_command local fn = vim.fn local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path}) execute 'packadd packer.nvim' end -- Plugins local packer = require('packer') packer.init { display = { open_fn = require('packer.util').float, }, } return packer.startup(function(use) -- lua plugins use { { 'wbthomason/packer.nvim' }, { 'neovim/nvim-lspconfig', requires = { 'nvim-lua/lsp-status.nvim', 'hrsh7th/cmp-nvim-lsp', }, config = function() require('lsp') end }, { 'hrsh7th/nvim-cmp', requires = { 'hrsh7th/cmp-buffer', 'hrsh7th/cmp-nvim-lua', 'hrsh7th/cmp-nvim-lsp', 'hrsh7th/cmp-path', }, config = function() local cmp = require('cmp') cmp.setup { sources = { { name = 'buffer' }, { name = 'nvim_lua' }, { name = 'nvim_lsp' }, { name = 'path' }, }, } end, }, { 'folke/which-key.nvim', -- TODO: Lazy loading -- cmd = { 'WhichKey' }, -- keys = { '<leader>', '<Space>' }, config = function() local wk = require('which-key') wk.setup({ triggers = { '<leader>' } }) wk.register({ G = { name = '+git', g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' }, o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' }, }, l = { name = '+lsp', r = { vim.lsp.buf.references, 'references' }, d = { '<cmd>LspTroubleToggle<CR>', 'diagnostics' }, f = { vim.lsp.buf.formatting, 'formatting' }, }, f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' }, b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' }, g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' }, p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' }, n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' }, P = { name = '+packer', u = { '<cmd>PackerUpdate<CR>', 'update' }, s = { '<cmd>PackerSync<CR>', 'sync' }, i = { '<cmd>PackerInstall<CR>', 'install' }, c = { '<cmd>PackerCompile<CR>', 'compile' }, }, }, { prefix = '<leader>' }) end }, { 'lewis6991/gitsigns.nvim', tag = 'release', requires = { 'nvim-lua/plenary.nvim' }, config = function() require('gitsigns').setup { signs = { -- default: text = '_' delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' }, }, } end }, { 'hoob3rt/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', 'nvim-lua/lsp-status.nvim', 'projekt0n/github-nvim-theme', }, config = function() local lsp_status = require('lsp-status') require('lualine').setup{ options = { theme = 'github' }, sections = { lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' }, }, } end }, { 'folke/trouble.nvim', requires = { 'kyazdani42/nvim-web-devicons' }, config = function() require('trouble').setup { auto_close = true, } end }, { 'windwp/nvim-autopairs', config = function() require('nvim-autopairs').setup() end, }, { 'nvim-telescope/telescope.nvim', cmd = { 'Telescope' }, requires = { 'nvim-lua/popup.nvim', 'nvim-lua/plenary.nvim', 'nvim-telescope/telescope-ghq.nvim', }, config = function() local telescope = require('telescope') telescope.load_extension('ghq') telescope.setup { defaults = { mappings = { i = { -- see https://github.com/nvim-telescope/telescope.nvim/issues/499 ["<C-u>"] = false, }, }, }, } end, }, { 'akinsho/nvim-bufferline.lua', requires = { 'kyazdani42/nvim-web-devicons', }, config = function() require('bufferline').setup { options = { separator_style = 'thin', diagnostics = "nvim_lsp", }, } end, }, { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate', config = function() require('nvim-treesitter.configs').setup { ensure_installed = "maintained", highlight = { enable = true, }, } end, }, { 'projekt0n/github-nvim-theme', config = function() require('github-theme').setup { transparent = true, hide_inactive_statusline = true, } end, } } -- vimscript plugins use { { 'tpope/vim-fugitive' }, { 'tpope/vim-endwise' }, { 'tpope/vim-surround' }, { 'hashivim/vim-terraform', ft = 'terraform' }, { 'tmux-plugins/vim-tmux', ft = 'tmux' }, { 'cespare/vim-toml' }, { 'dag/vim-fish' }, { 'tyru/caw.vim', keys = { '<C-k>' }, config = function() vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {}) end }, { 'scrooloose/nerdtree', cmd = { 'NERDTreeFind', 'NERDTreeToggle' }, keys = { '<F2>', '<F3>' }, setup = function() vim.g.NERDTreeChDirMode = 0 vim.g.NERDTreeShowHidden = 1 vim.g.NERDTreeWinSize = 30 end, config = function() vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true }) end }, { 'tyru/open-browser-github.vim', requires = { 'tyru/open-browser.vim', opt = true }, cmd = { 'OpenGithubFile', 'OpenGithubIssue', 'OpenGithubPullReq', 'OpenGithubProject', 'OpenGithubCommit' }, setup = function() vim.g.openbrowser_github_url_exists_check = 'ignore' end }, } end)
-- Packer.nvim bootstrapping -- see https://github.com/wbthomason/packer.nvim#bootstrapping -- TODO: Move to ~/.config/nvim/lua/init.lua local execute = vim.api.nvim_command local fn = vim.fn local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path}) execute 'packadd packer.nvim' end -- Plugins local packer = require('packer') packer.init { display = { open_fn = require('packer.util').float, }, } return packer.startup(function(use) -- lua plugins use { { 'wbthomason/packer.nvim' }, { 'neovim/nvim-lspconfig', requires = { 'nvim-lua/lsp-status.nvim', 'hrsh7th/cmp-nvim-lsp', }, config = function() require('lsp') end }, { 'hrsh7th/nvim-cmp', requires = { 'hrsh7th/cmp-buffer', 'hrsh7th/cmp-nvim-lua', 'hrsh7th/cmp-nvim-lsp', 'hrsh7th/cmp-path', }, config = function() local cmp = require('cmp') cmp.setup { sources = { { name = 'buffer' }, { name = 'nvim_lua' }, { name = 'nvim_lsp' }, { name = 'path' }, }, } end, }, { 'folke/which-key.nvim', -- TODO: Lazy loading -- cmd = { 'WhichKey' }, -- keys = { '<leader>', '<Space>' }, config = function() local wk = require('which-key') wk.setup({ triggers = { '<leader>' } }) wk.register({ G = { name = '+git', g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' }, o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' }, }, l = { name = '+lsp', r = { vim.lsp.buf.references, 'references' }, d = { '<cmd>LspTroubleToggle<CR>', 'diagnostics' }, f = { vim.lsp.buf.formatting, 'formatting' }, }, f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' }, b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' }, g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' }, p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' }, n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' }, P = { name = '+packer', u = { '<cmd>PackerUpdate<CR>', 'update' }, s = { '<cmd>PackerSync<CR>', 'sync' }, i = { '<cmd>PackerInstall<CR>', 'install' }, c = { '<cmd>PackerCompile<CR>', 'compile' }, }, }, { prefix = '<leader>' }) end }, { 'lewis6991/gitsigns.nvim', tag = 'release', requires = { 'nvim-lua/plenary.nvim' }, config = function() require('gitsigns').setup { signs = { -- default: text = '_' delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' }, }, } end }, { 'nvim-lualine/lualine.nvim', requires = { { 'kyazdani42/nvim-web-devicons', opt = true }, 'nvim-lua/lsp-status.nvim', 'projekt0n/github-nvim-theme', }, config = function() local lsp_status = require('lsp-status') require('lualine').setup{ options = { theme = 'auto' }, sections = { lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' }, }, } end }, { 'folke/trouble.nvim', requires = { 'kyazdani42/nvim-web-devicons' }, config = function() require('trouble').setup { auto_close = true, } end }, { 'windwp/nvim-autopairs', config = function() require('nvim-autopairs').setup() end, }, { 'nvim-telescope/telescope.nvim', cmd = { 'Telescope' }, requires = { 'nvim-lua/popup.nvim', 'nvim-lua/plenary.nvim', 'nvim-telescope/telescope-ghq.nvim', }, config = function() local telescope = require('telescope') telescope.load_extension('ghq') telescope.setup { defaults = { mappings = { i = { -- see https://github.com/nvim-telescope/telescope.nvim/issues/499 ["<C-u>"] = false, }, }, }, } end, }, { 'akinsho/nvim-bufferline.lua', requires = { 'kyazdani42/nvim-web-devicons', }, config = function() require('bufferline').setup { options = { separator_style = 'thin', diagnostics = "nvim_lsp", }, } end, }, { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate', config = function() require('nvim-treesitter.configs').setup { ensure_installed = "maintained", highlight = { enable = true, }, } end, }, { 'projekt0n/github-nvim-theme', config = function() require('github-theme').setup { theme_style = 'dark_default', transparent = true, } end, } } -- vimscript plugins use { { 'tpope/vim-fugitive' }, { 'tpope/vim-endwise' }, { 'tpope/vim-surround' }, { 'hashivim/vim-terraform', ft = 'terraform' }, { 'tmux-plugins/vim-tmux', ft = 'tmux' }, { 'cespare/vim-toml' }, { 'dag/vim-fish' }, { 'tyru/caw.vim', keys = { '<C-k>' }, config = function() vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {}) end }, { 'scrooloose/nerdtree', cmd = { 'NERDTreeFind', 'NERDTreeToggle' }, keys = { '<F2>', '<F3>' }, setup = function() vim.g.NERDTreeChDirMode = 0 vim.g.NERDTreeShowHidden = 1 vim.g.NERDTreeWinSize = 30 end, config = function() vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true }) end }, { 'tyru/open-browser-github.vim', requires = { 'tyru/open-browser.vim', opt = true }, cmd = { 'OpenGithubFile', 'OpenGithubIssue', 'OpenGithubPullReq', 'OpenGithubProject', 'OpenGithubCommit' }, setup = function() vim.g.openbrowser_github_url_exists_check = 'ignore' end }, } end)
Fix broken settings in latest lualine.nvim and github-nvim-theme
Fix broken settings in latest lualine.nvim and github-nvim-theme
Lua
mit
tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles
58ddaa4b1db34aa652514c2f0ef4a180f5aec846
scripts/genie.lua
scripts/genie.lua
-- -- Copyright 2010-2014 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- newoption { trigger = "with-tools", description = "Enable building tools.", } newoption { trigger = "with-shared-lib", description = "Enable building shared library.", } newoption { trigger = "with-sdl", description = "Enable SDL entry.", } newoption { trigger = "with-ovr", description = "Enable OculusVR integration.", } solution "bgfx" configurations { "Debug", "Release", } platforms { "x32", "x64", -- "Xbox360", "Native", -- for targets where bitness is not specified } language "C++" startproject "example-00-helloworld" BGFX_DIR = (path.getabsolute("..") .. "/") local BGFX_BUILD_DIR = (BGFX_DIR .. ".build/") local BGFX_THIRD_PARTY_DIR = (BGFX_DIR .. "3rdparty/") BX_DIR = (BGFX_DIR .. "../bx/") defines { "BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1" } dofile (BX_DIR .. "scripts/toolchain.lua") toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) function copyLib() end if _OPTIONS["with-sdl"] then if os.is("windows") then if not os.getenv("SDL2_DIR") then print("Set SDL2_DIR enviroment variable.") end end end function exampleProject(_name) project ("example-" .. _name) uuid (os.uuid("example-" .. _name)) kind "WindowedApp" configuration {} debugdir (BGFX_DIR .. "examples/runtime/") includedirs { BX_DIR .. "include", BGFX_DIR .. "include", BGFX_DIR .. "3rdparty", BGFX_DIR .. "examples/common", } files { BGFX_DIR .. "examples/" .. _name .. "/**.cpp", BGFX_DIR .. "examples/" .. _name .. "/**.h", } links { "bgfx", "example-common", } if _OPTIONS["with-sdl"] then defines { "ENTRY_CONFIG_USE_SDL=1" } links { "SDL2" } configuration { "x32", "windows" } libdirs { "$(SDL2_DIR)/lib/x86" } configuration { "x64", "windows" } libdirs { "$(SDL2_DIR)/lib/x64" } configuration {} end if _OPTIONS["with-ovr"] then links { "winmm", "ws2_32", } configuration { "x32" } libdirs { "$(OVR_DIR)/LibOVR/Lib/Win32/" .. _ACTION } configuration { "x64" } libdirs { "$(OVR_DIR)/LibOVR/Lib/x64/" .. _ACTION } configuration { "x32", "Debug" } links { "libovrd" } configuration { "x32", "Release" } links { "libovr" } configuration { "x64", "Debug" } links { "libovr64d" } configuration { "x64", "Release" } links { "libovr64" } configuration {} end configuration { "vs*" } linkoptions { "/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll } links { -- this is needed only for testing with GLES2/3 on Windows with VS2008 "DelayImp", } configuration { "vs201*" } linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x "/DELAYLOAD:\"libEGL.dll\"", "/DELAYLOAD:\"libGLESv2.dll\"", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "winphone8*"} removelinks { "DelayImp", "gdi32", "psapi" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } configuration { "mingw*" } links { "dxguid", } configuration { "mingw-clang" } kind "ConsoleApp" configuration { "android*" } kind "ConsoleApp" targetextension ".so" linkoptions { "-shared", } links { "EGL", "GLESv2", } configuration { "nacl*" } kind "ConsoleApp" targetextension ".nexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "pnacl" } kind "ConsoleApp" targetextension ".pexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "asmjs" } kind "ConsoleApp" targetextension ".bc" configuration { "linux-*" } links { "X11", "GL", "pthread", } configuration { "rpi" } links { "X11", "GLESv2", "EGL", "bcm_host", "vcos", "vchiq_arm", "pthread", } configuration { "osx" } files { BGFX_DIR .. "examples/common/**.mm", } links { "Cocoa.framework", "OpenGL.framework", } configuration { "xcode4" } platforms { "Universal" } files { BGFX_DIR .. "examples/common/**.mm", } links { "Cocoa.framework", "Foundation.framework", "OpenGL.framework", } configuration { "ios*" } kind "ConsoleApp" files { BGFX_DIR .. "examples/common/**.mm", } linkoptions { "-framework CoreFoundation", "-framework Foundation", "-framework OpenGLES", "-framework UIKit", "-framework QuartzCore", } configuration { "qnx*" } targetextension "" links { "EGL", "GLESv2", } configuration {} strip() end dofile "bgfx.lua" dofile "example-common.lua" bgfxProject("", "StaticLib", {}) exampleProject("00-helloworld") exampleProject("01-cubes") exampleProject("02-metaballs") exampleProject("03-raymarch") exampleProject("04-mesh") exampleProject("05-instancing") exampleProject("06-bump") exampleProject("07-callback") exampleProject("08-update") exampleProject("09-hdr") exampleProject("10-font") exampleProject("11-fontsdf") exampleProject("12-lod") exampleProject("13-stencil") exampleProject("14-shadowvolumes") exampleProject("15-shadowmaps-simple") exampleProject("16-shadowmaps") exampleProject("17-drawstress") exampleProject("18-ibl") exampleProject("19-oit") exampleProject("20-nanovg") exampleProject("21-deferred") exampleProject("22-windows") if _OPTIONS["with-shared-lib"] then bgfxProject("-shared-lib", "SharedLib", {}) end if _OPTIONS["with-tools"] then dofile "makedisttex.lua" dofile "shaderc.lua" dofile "texturec.lua" dofile "geometryc.lua" end
-- -- Copyright 2010-2014 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- newoption { trigger = "with-tools", description = "Enable building tools.", } newoption { trigger = "with-shared-lib", description = "Enable building shared library.", } newoption { trigger = "with-sdl", description = "Enable SDL entry.", } newoption { trigger = "with-ovr", description = "Enable OculusVR integration.", } solution "bgfx" configurations { "Debug", "Release", } platforms { "x32", "x64", -- "Xbox360", "Native", -- for targets where bitness is not specified } language "C++" startproject "example-00-helloworld" BGFX_DIR = (path.getabsolute("..") .. "/") local BGFX_BUILD_DIR = (BGFX_DIR .. ".build/") local BGFX_THIRD_PARTY_DIR = (BGFX_DIR .. "3rdparty/") BX_DIR = (BGFX_DIR .. "../bx/") defines { "BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1" } dofile (BX_DIR .. "scripts/toolchain.lua") toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) function copyLib() end if _OPTIONS["with-sdl"] then if os.is("windows") then if not os.getenv("SDL2_DIR") then print("Set SDL2_DIR enviroment variable.") end end end function exampleProject(_name) project ("example-" .. _name) uuid (os.uuid("example-" .. _name)) kind "WindowedApp" configuration {} debugdir (BGFX_DIR .. "examples/runtime/") includedirs { BX_DIR .. "include", BGFX_DIR .. "include", BGFX_DIR .. "3rdparty", BGFX_DIR .. "examples/common", } files { BGFX_DIR .. "examples/" .. _name .. "/**.cpp", BGFX_DIR .. "examples/" .. _name .. "/**.h", } links { "bgfx", "example-common", } if _OPTIONS["with-sdl"] then defines { "ENTRY_CONFIG_USE_SDL=1" } links { "SDL2" } configuration { "x32", "windows" } libdirs { "$(SDL2_DIR)/lib/x86" } configuration { "x64", "windows" } libdirs { "$(SDL2_DIR)/lib/x64" } configuration {} end if _OPTIONS["with-ovr"] then links { "winmm", "ws2_32", } configuration { "x32" } libdirs { "$(OVR_DIR)/LibOVR/Lib/Win32/" .. _ACTION } configuration { "x64" } libdirs { "$(OVR_DIR)/LibOVR/Lib/x64/" .. _ACTION } configuration { "x32", "Debug" } links { "libovrd" } configuration { "x32", "Release" } links { "libovr" } configuration { "x64", "Debug" } links { "libovr64d" } configuration { "x64", "Release" } links { "libovr64" } configuration {} end configuration { "vs*" } linkoptions { "/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll } links { -- this is needed only for testing with GLES2/3 on Windows with VS2008 "DelayImp", } configuration { "vs201*" } linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x "/DELAYLOAD:\"libEGL.dll\"", "/DELAYLOAD:\"libGLESv2.dll\"", } configuration { "vs20* or mingw*" } links { "gdi32", "psapi", } configuration { "winphone8*"} removelinks { "DelayImp", "gdi32", "psapi" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } -- WinRT targets need their own output directories are build files stomp over each other targetdir (BGFX_BUILD_DIR .. "arm_" .. _ACTION .. "/bin/" .. _name) objdir (BGFX_BUILD_DIR .. "arm_" .. _ACTION .. "/obj/" .. _name) configuration { "mingw*" } links { "dxguid", } configuration { "mingw-clang" } kind "ConsoleApp" configuration { "android*" } kind "ConsoleApp" targetextension ".so" linkoptions { "-shared", } links { "EGL", "GLESv2", } configuration { "nacl*" } kind "ConsoleApp" targetextension ".nexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "pnacl" } kind "ConsoleApp" targetextension ".pexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "asmjs" } kind "ConsoleApp" targetextension ".bc" configuration { "linux-*" } links { "X11", "GL", "pthread", } configuration { "rpi" } links { "X11", "GLESv2", "EGL", "bcm_host", "vcos", "vchiq_arm", "pthread", } configuration { "osx" } files { BGFX_DIR .. "examples/common/**.mm", } links { "Cocoa.framework", "OpenGL.framework", } configuration { "xcode4" } platforms { "Universal" } files { BGFX_DIR .. "examples/common/**.mm", } links { "Cocoa.framework", "Foundation.framework", "OpenGL.framework", } configuration { "ios*" } kind "ConsoleApp" files { BGFX_DIR .. "examples/common/**.mm", } linkoptions { "-framework CoreFoundation", "-framework Foundation", "-framework OpenGLES", "-framework UIKit", "-framework QuartzCore", } configuration { "qnx*" } targetextension "" links { "EGL", "GLESv2", } configuration {} strip() end dofile "bgfx.lua" dofile "example-common.lua" bgfxProject("", "StaticLib", {}) exampleProject("00-helloworld") exampleProject("01-cubes") exampleProject("02-metaballs") exampleProject("03-raymarch") exampleProject("04-mesh") exampleProject("05-instancing") exampleProject("06-bump") exampleProject("07-callback") exampleProject("08-update") exampleProject("09-hdr") exampleProject("10-font") exampleProject("11-fontsdf") exampleProject("12-lod") exampleProject("13-stencil") exampleProject("14-shadowvolumes") exampleProject("15-shadowmaps-simple") exampleProject("16-shadowmaps") exampleProject("17-drawstress") exampleProject("18-ibl") exampleProject("19-oit") exampleProject("20-nanovg") exampleProject("21-deferred") exampleProject("22-windows") if _OPTIONS["with-shared-lib"] then bgfxProject("-shared-lib", "SharedLib", {}) end if _OPTIONS["with-tools"] then dofile "makedisttex.lua" dofile "shaderc.lua" dofile "texturec.lua" dofile "geometryc.lua" end
Setting output directories for WinPhone builds to fix build errors.
Setting output directories for WinPhone builds to fix build errors.
Lua
bsd-2-clause
fluffyfreak/bgfx,darkimage/bgfx,bkaradzic/bgfx,ming4883/bgfx,Extrawurst/bgfx,0-wiz-0/bgfx,cuavas/bgfx,darkimage/bgfx,cyndis/bgfx,bkaradzic/bgfx,Synxis/bgfx,mmicko/bgfx,ocornut/bgfx,LSBOSS/bgfx,v3n/bgfx,elmindreda/bgfx,janstk/bgfx,fluffyfreak/bgfx,attilaz/bgfx,aonorin/bgfx,Vertexwahn/bgfx,Vertexwahn/bgfx,mendsley/bgfx,mmicko/bgfx,cyndis/bgfx,aonorin/bgfx,v3n/bgfx,marco-we/bgfx,ktotheoz/bgfx,ocornut/bgfx,0-wiz-0/bgfx,jdryg/bgfx,0-wiz-0/bgfx,marco-we/bgfx,fluffyfreak/bgfx,cyndis/bgfx,sergeScherbakov/bgfx,jpcy/bgfx,MikePopoloski/bgfx,septag/bgfx,mcanthony/bgfx,mendsley/bgfx,cuavas/bgfx,jpcy/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,LWJGL-CI/bgfx,sergeScherbakov/bgfx,ocornut/bgfx,jpcy/bgfx,mcanthony/bgfx,janstk/bgfx,Synxis/bgfx,fluffyfreak/bgfx,kondrak/bgfx,emoon/bgfx,mcanthony/bgfx,BlueCrystalLabs/bgfx,BlueCrystalLabs/bgfx,jdryg/bgfx,janstk/bgfx,septag/bgfx,bkaradzic/bgfx,kondrak/bgfx,v3n/bgfx,LWJGL-CI/bgfx,darkimage/bgfx,aonorin/bgfx,mmicko/bgfx,ming4883/bgfx,attilaz/bgfx,bkaradzic/bgfx,LWJGL-CI/bgfx,BlueCrystalLabs/bgfx,marco-we/bgfx,sergeScherbakov/bgfx,jpcy/bgfx,LSBOSS/bgfx,jdryg/bgfx,elmindreda/bgfx,elmindreda/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,attilaz/bgfx,ktotheoz/bgfx,LSBOSS/bgfx,mendsley/bgfx,cuavas/bgfx,ming4883/bgfx,MikePopoloski/bgfx,jdryg/bgfx,kondrak/bgfx,Synxis/bgfx,andr3wmac/bgfx,emoon/bgfx,ktotheoz/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,Vertexwahn/bgfx,emoon/bgfx,septag/bgfx
41fbdf44659385171f813576373be36556023a73
core/debug-output.lua
core/debug-output.lua
if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local lastFont local outfile local writeline = function (...) local args = table.pack(...) for i = 1, #args do outfile:write(args[i]) if i < #args then outfile:write("\t") end end outfile:write("\n") end local _deprecationCheck = function (caller) if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10") end end local function _round (input) -- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased -- towards rounding 0.5 up to 1, all other Lua interpreters are biased -- towards rounding such floating point numbers down. This hack shaves off -- just enough to fix the bias so our test suite works across interpreters. -- Note that even a true rounding function here will fail because the bias is -- inherent to the floating point type. Also note we are erroring in favor of -- the *less* common option beacuse the LuaJIT VMS are hopelessly broken -- whereas normal LUA VMs can be cooerced. if input > 0 then input = input + .00000000000001 end if input < 0 then input = input - .00000000000001 end return string.format("%.4f", input) end SILE.outputters.debug = { init = function (self) _deprecationCheck(self) outfile = io.open(SILE.outputFilename, "w+") writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) writeline("Begin page") end, newPage = function (self) _deprecationCheck(self) writeline("New page") end, finish = function (self) _deprecationCheck(self) if SILE.status.unsupported then writeline("UNSUPPORTED") end writeline("End page") writeline("Finish") outfile:close() end, cursor = function (_) SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0") end, getCursor = function (self) _deprecationCheck(self) return cursorX, cursorY end, moveTo = function (_, _, _) SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0") end, setCursor = function (self, x, y, relative) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) local oldx, oldy = self:getCursor() local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 } cursorX = offset.x + x cursorY = offset.y - y if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end end, setColor = function (self, color) _deprecationCheck(self) writeline("Set color", color.r, color.g, color.b) end, pushColor = function (self, color) _deprecationCheck(self) writeline("Push color", _round(color.r), _round(color.g), _round(color.b)) end, popColor = function (self) _deprecationCheck(self) writeline("Pop color") end, outputHbox = function (_, _, _) SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0") end, drawHbox = function (self, value, width) _deprecationCheck(self) if not value.glyphString then return end width = SU.cast("number", width) local buf if value.complex then local cluster = {} for i = 1, #value.items do local item = value.items[i] cluster[#cluster+1] = item.gid -- For the sake of terseness we're only dumping non-zero values if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end self:setCursor(item.width, 0, true) end buf = table.concat(cluster, " ") else buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width) end writeline("T", buf, "(" .. tostring(value.text) .. ")") end, setFont = function (self, options) _deprecationCheck(self) local font = SILE.font._key(options) if lastFont ~= font then writeline("Set font ", font) lastFont = font end end, drawImage = function (self, src, x, y, width, height) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height)) end, imageSize = function (_, _) SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0") end, getImageSize = function (self, src) _deprecationCheck(self) local pdf = require("justenoughlibtexpdf") local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, drawSVG = function (self, figure, _, x, y, width, height, scalefactor) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor) end, rule = function (_, _, _, _, _) SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0") end, drawRule = function (self, x, y, width, depth) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) writeline("Draw line", _round(x), _round(y), _round(width), _round(depth)) end, debugFrame = function (self, _, _) _deprecationCheck(self) end, debugHbox = function (self, _, _, _) _deprecationCheck(self) end } SILE.outputter = SILE.outputters.debug if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".debug" end
if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local lastFont local outfile local writeline = function (...) local args = table.pack(...) for i = 1, #args do outfile:write(args[i]) if i < #args then outfile:write("\t") end end outfile:write("\n") end local _deprecationCheck = function (caller) if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10") end end local function _round (input) -- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased -- towards rounding 0.5 up to 1, all other Lua interpreters are biased -- towards rounding such floating point numbers down. This hack shaves off -- just enough to fix the bias so our test suite works across interpreters. -- Note that even a true rounding function here will fail because the bias is -- inherent to the floating point type. Also note we are erroring in favor of -- the *less* common option beacuse the LuaJIT VMS are hopelessly broken -- whereas normal LUA VMs can be cooerced. if input > 0 then input = input + .00000000000001 end if input < 0 then input = input - .00000000000001 end return string.format("%.4f", input) end SILE.outputters.debug = { init = function (self) _deprecationCheck(self) outfile = io.open(SILE.outputFilename, "w+") writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) writeline("Begin page") end, newPage = function (self) _deprecationCheck(self) writeline("New page") end, finish = function (self) _deprecationCheck(self) if SILE.status.unsupported then writeline("UNSUPPORTED") end writeline("End page") writeline("Finish") outfile:close() end, cursor = function (_) SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0") end, getCursor = function (self) _deprecationCheck(self) return cursorX, cursorY end, moveTo = function (_, _, _) SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0") end, setCursor = function (self, x, y, relative) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) local oldx, oldy = self:getCursor() local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 } cursorX = offset.x + x cursorY = offset.y - y if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end end, setColor = function (self, color) _deprecationCheck(self) writeline("Set color", color.r, color.g, color.b) end, pushColor = function (self, color) _deprecationCheck(self) if color.r then writeline("Push color", _round(color.r), _round(color.g), _round(color.b)) elseif color.c then writeline("Push color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k)) elseif color.l then writeline("Push color (grayscale)", _round(color.l)) end end, popColor = function (self) _deprecationCheck(self) writeline("Pop color") end, outputHbox = function (_, _, _) SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0") end, drawHbox = function (self, value, width) _deprecationCheck(self) if not value.glyphString then return end width = SU.cast("number", width) local buf if value.complex then local cluster = {} for i = 1, #value.items do local item = value.items[i] cluster[#cluster+1] = item.gid -- For the sake of terseness we're only dumping non-zero values if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end self:setCursor(item.width, 0, true) end buf = table.concat(cluster, " ") else buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width) end writeline("T", buf, "(" .. tostring(value.text) .. ")") end, setFont = function (self, options) _deprecationCheck(self) local font = SILE.font._key(options) if lastFont ~= font then writeline("Set font ", font) lastFont = font end end, drawImage = function (self, src, x, y, width, height) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height)) end, imageSize = function (_, _) SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0") end, getImageSize = function (self, src) _deprecationCheck(self) local pdf = require("justenoughlibtexpdf") local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, drawSVG = function (self, figure, _, x, y, width, height, scalefactor) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor) end, rule = function (_, _, _, _, _) SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0") end, drawRule = function (self, x, y, width, depth) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) writeline("Draw line", _round(x), _round(y), _round(width), _round(depth)) end, debugFrame = function (self, _, _) _deprecationCheck(self) end, debugHbox = function (self, _, _, _) _deprecationCheck(self) end } SILE.outputter = SILE.outputters.debug if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".debug" end
fix(outputter): Non-RGB colors shall work with the debug outputter (#1469)
fix(outputter): Non-RGB colors shall work with the debug outputter (#1469)
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
7f72f06cf4d6f29afe15509041b055cceff1f813
test/testrsa.lua
test/testrsa.lua
local skynet = require "skynet" local crypt = require "skynet.crypt" local src = "hello world !" local privpem = [[-----BEGIN PRIVATE KEY----- MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANMfFz1aPEuvl/AN 0lVNXoMGoRrUPfmHtKtUfpaM7vxPXtYzHsBzu6KLOBDeOjXO9YD43vLIRpZwO0r4 kWLMYGSZMxSQba7itQ5H6kDc2dm7UQqsJ34wupejGADd2iEOBappvXH7LEaGhjvs W1ZOZi1r5or0HXqRNkWIGvU8YYWpAgMBAAECgYA+wMcPnXq+pHrtB661XEHzgEzy xJOHUCcLphnadhmzNYRi9t71JXFoZylLGkMDK3kd1NuwHoecv89gAXJ1g3pC4mW+ D9xZluFre2qlYs+nn0nE1cNJ+ogqkjQ76XuV/9IuZSSPCxRJ6W4EaR3rQi/ORK/o KOKucP4kFTJTMQrwYQJBAO6xYGrfiRSQkQKj0dR2at29t5gRJ5FU6XzVsy1WAN3G goSqOVBYCAL2IF8jHbt5dvX1QKzAKX44vBSmCs6/B5sCQQDibe68z4WKFOYGbg75 ZKmmJuCzDCTRaZu4ThpqFVJlwdw1JeFOX3r+4qpwfNDOSOinzL7BmO+sHBBmBUJG jLYLAkEA7ZFFcZmCiiFI8uOx2FD0FDbbIFMSmqd0rHbVmu3aduE4zmnOGZVEhA4M MiR1Vz6RlEPBVy77HVHCgJqybwvauQJBAJQ9WKFwU4MVL4tiHpeUGaVXqqBOAQTA 2VwOdiihkPJhuuNoy1reE84vY1qFvMZw4TCKURC6KZ9KOEoygzNhCAUCQQDsOp9u EL2lf9pph/xpdMlIk4s1f6cJ19YTOq/F9Bdk6Ilok23yuuynDnV31LLG1wEscn/n jyiiuJjC1pbr+LLV -----END PRIVATE KEY-----]] local pubpem = [[-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTHxc9WjxLr5fwDdJVTV6DBqEa 1D35h7SrVH6WjO78T17WMx7Ac7uiizgQ3jo1zvWA+N7yyEaWcDtK+JFizGBkmTMU kG2u4rUOR+pA3NnZu1EKrCd+MLqXoxgA3dohDgWqab1x+yxGhoY77FtWTmYta+aK 9B16kTZFiBr1PGGFqQIDAQAB -----END PUBLIC KEY-----]] skynet.start(function() local bs = crypt.rsaprisign(src, privpem) local sign = crypt.base64encode(bs) print("----- RSA SIGN TEST -----") print(sign) local dbs = crypt.base64decode(sign) local ok = crypt.rsapubverify(src, dbs, pubpem) assert(ok) print("----- RSA SIGN TEST OK -----\n") print("----- RSA CRYPT TEST -----") bs = crypt.rsapubenc(src, pubpem) local dst = crypt.base64encode(bs) print(dst) dbs = crypt.base64decode(dst) local dsrc = crypt.rsapridec(dbs, privpem) print(dsrc) assert(dsrc == src) bs = crypt.rsaprienc(src, privpem) dst = crypt.base64encode(bs) print("\n"..dst) dbs = crypt.base64decode(dst) dsrc = crypt.rsapubdec(dbs, pubpem) print(dsrc) assert(dsrc == src) print("----- RSA CRYPT TEST OK -----\n") skynet.exit() end)
local skynet = require "skynet" local crypt = require "skynet.crypt" local src = "hello world !" local privpem_pkcs8 = [[-----BEGIN PRIVATE KEY----- MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANMfFz1aPEuvl/AN 0lVNXoMGoRrUPfmHtKtUfpaM7vxPXtYzHsBzu6KLOBDeOjXO9YD43vLIRpZwO0r4 kWLMYGSZMxSQba7itQ5H6kDc2dm7UQqsJ34wupejGADd2iEOBappvXH7LEaGhjvs W1ZOZi1r5or0HXqRNkWIGvU8YYWpAgMBAAECgYA+wMcPnXq+pHrtB661XEHzgEzy xJOHUCcLphnadhmzNYRi9t71JXFoZylLGkMDK3kd1NuwHoecv89gAXJ1g3pC4mW+ D9xZluFre2qlYs+nn0nE1cNJ+ogqkjQ76XuV/9IuZSSPCxRJ6W4EaR3rQi/ORK/o KOKucP4kFTJTMQrwYQJBAO6xYGrfiRSQkQKj0dR2at29t5gRJ5FU6XzVsy1WAN3G goSqOVBYCAL2IF8jHbt5dvX1QKzAKX44vBSmCs6/B5sCQQDibe68z4WKFOYGbg75 ZKmmJuCzDCTRaZu4ThpqFVJlwdw1JeFOX3r+4qpwfNDOSOinzL7BmO+sHBBmBUJG jLYLAkEA7ZFFcZmCiiFI8uOx2FD0FDbbIFMSmqd0rHbVmu3aduE4zmnOGZVEhA4M MiR1Vz6RlEPBVy77HVHCgJqybwvauQJBAJQ9WKFwU4MVL4tiHpeUGaVXqqBOAQTA 2VwOdiihkPJhuuNoy1reE84vY1qFvMZw4TCKURC6KZ9KOEoygzNhCAUCQQDsOp9u EL2lf9pph/xpdMlIk4s1f6cJ19YTOq/F9Bdk6Ilok23yuuynDnV31LLG1wEscn/n jyiiuJjC1pbr+LLV -----END PRIVATE KEY-----]] local pubpem_pkcs8 = [[-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTHxc9WjxLr5fwDdJVTV6DBqEa 1D35h7SrVH6WjO78T17WMx7Ac7uiizgQ3jo1zvWA+N7yyEaWcDtK+JFizGBkmTMU kG2u4rUOR+pA3NnZu1EKrCd+MLqXoxgA3dohDgWqab1x+yxGhoY77FtWTmYta+aK 9B16kTZFiBr1PGGFqQIDAQAB -----END PUBLIC KEY-----]] local privpem_pkcs1 = [[-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCqCeoCQ2Hgv/WVO2V4aAD8l9O5DWOVJXChgSpXWNMTqGU/vr1b JHFeIZgsvuRDpGKRoOzkA7tc7MueVETMdIAVdTI8kFS/QneDr3F56j61zv3tpQtU 0NRqcQTxXir8Nc7cEyZQuvzpFSowXqfk92819oskJKo4m+59vCge7r7JfwIDAQAB AoGAEHezVRLHiOeuVgyRkC6qYcwmchaM3WXp2YpT2m+8yXuWiqzjU89ct1wTi8nU +4QRE799EbwWyjIYqjXJD+/8c28BXnLJhxils7qNJtEeE/cJ6qim+VmsLx4xTGEu jxe+fVfqS4dLbChZbo8ijBdhF7UQPAeqS4tMm7ZRmawzXSkCQQDiVpRLkL8/dVh0 Dd1DONBCHvnyg4VbqU661LxhqYpWKSgy7SAxi2+GgQb/ZFfHI4BNyq1RHt7rqZYw 6xjgDo2tAkEAwFKLLnY9opP2D8ClzCJzKIZPWolXzQjfhKQvPVMrriJKd32UBGIh MdQUqGzs0tWbrYN5sbDkky6jvtAfRi/BWwJAU7VNlzzrXl7Z3eIayPfEHhAyxLxb n/DYC0UOftgjL4Z9NYh5dZlqH8asfdvwktfQZfTlcLEIJQRNZb4tLwBy6QJAakTy HUE+u3gQrhGgS5T5lvnoHTno5yWxBIUIiVVMvJK8HRypzmY+u17Z71sI3VMlC5Kr itEY7G8IEebEcS7wIwJAZlK4D+K1wxSOeUvEnEGGt62oPVr/27CBwA9ePON48Rpx 90lSNcIaEUDTYnNZuz+NTN6ptCJruMkjiW0G30NAWQ== -----END RSA PRIVATE KEY----- ]] local pubpem_pkcs1 = [[-----BEGIN RSA PUBLIC KEY----- MIGJAoGBAKoJ6gJDYeC/9ZU7ZXhoAPyX07kNY5UlcKGBKldY0xOoZT++vVskcV4h mCy+5EOkYpGg7OQDu1zsy55URMx0gBV1MjyQVL9Cd4OvcXnqPrXO/e2lC1TQ1Gpx BPFeKvw1ztwTJlC6/OkVKjBep+T3bzX2iyQkqjib7n28KB7uvsl/AgMBAAE= -----END RSA PUBLIC KEY-----]] skynet.start(function() local bs = crypt.rsaprisign(src, privpem_pkcs8) local sign = crypt.base64encode(bs) print("----- RSA SIGN TEST -----") print(sign) local dbs = crypt.base64decode(sign) assert(crypt.rsapubverify(src, dbs, pubpem_pkcs8)) print("----- RSA SIGN TEST OK -----\n") print("----- RSA CRYPT TEST -----") bs = crypt.rsapubenc(src, pubpem_pkcs1) local dst = crypt.base64encode(bs) print(dst) dbs = crypt.base64decode(dst) local dsrc = crypt.rsapridec(dbs, privpem_pkcs1) print(dsrc) assert(dsrc == src) print("----- RSA CRYPT TEST OK -----\n") skynet.exit() end)
fix example testrsa.lua
fix example testrsa.lua
Lua
mit
korialuo/skynet,korialuo/skynet,korialuo/skynet
9115c3d51a44e35368dfec430fb292c70c2a3a53
base/townTreasure.lua
base/townTreasure.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/>. ]] -- This scripts contains functions to work with the town treasury require("base.common") module("base.townTreasure", package.seeall) -- get the treasure of a town -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetTownTreasure(town) local foundTreasure, currentTreasure = ScriptVars:find("Treasure"..town) if not foundTreasure then return 0; end local treasureNumber = tonumber(currentTreasure); if (treasureNumber > 3000000) then log(string.format("[WARN][Town Treasure] The treasure of %s exceeded 3 million copper coins. Something is wrong. Capping.", town)); return 3000000; end return treasureNumber; end -- get the itemID of a gem for each town. --@town The corresponding town as string: "Cadomyr"|"Runewick"|"Galmair" --@gemNr The number (1 or 2) of the gem function GetTownGem(town,gemNr) if town=="Cadomyr" then end end --Runewick: Emerald and Ruby --Cadomyr: Topaz and Amethyst --Galmair: Bluestond and Blackstone -- get the amount of taxes collected to determine the amount of gems to pay out -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetPaymentAmount(town) local foundTreasure, currentTreasure = ScriptVars:find("OldTreasure"..town) if not foundTreasure then currentTreasure = 0 end return tonumber(currentTreasure) end -- get the amount of taxespayers last month to determine the amount of gems to pay out -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetTaxpayerNumber(town) local foundPayers, currentNoPayer = ScriptVars:find("OldPayers"..town) if not foundPayers then return 0; end return tonumber(currentNoPayer); end -- change treasure of a town -- @town Town which treasure we want to change -- @amount Amount of money. Positive number = increase treasure; negative number = decrease treasure function ChangeTownTreasure(town,amount) local currentTreasure = GetTownTreasure(town) local newTreasure = currentTreasure + amount ScriptVars:set("Treasure"..town, newTreasure) ScriptVars:save() end -- increases the number of taxpayers for this month by 1. -- @town Town function IncreaseTaxpayerNumber(town) local foundPayers, currentNoPayer = ScriptVars:find("Payers"..town) if foundPayers then --debug("found payers: "..currentNoPayer) ScriptVars:set("Payers"..town, currentNoPayer+1) else ScriptVars:set("Payers"..town, 1) --debug("found payers: 1") end ScriptVars:save() end -- New month starts: -- * Collected taxes are now stored as "old" taxes (overwrite!) -- * Actual taxes are reset to 0 -- * Total number of taxpayers are stored as "old" Payers (overwrite!) -- * Actual number of taxpayers is set to 0 --@town Town --@timeStmp Timestamp of the new month function NewMonthSwitch(town,timeStmp) --debug("NewMonthSwitch with "..town.." and "..timeStmp); local currentTreasure = GetTownTreasure(town); log(string.format("[tax switch] %s's treasure was reset. Old treasure was %d copper coins", town, currentTreasure)) --debug("found treasure"..currentTreasure); ScriptVars:set("OldTreasure"..town, currentTreasure) ScriptVars:set("SwitchedToPayment"..town, timeStmp) ScriptVars:set("Treasure"..town, 0) local foundPayers, currentPayers = ScriptVars:find("Payers"..town) if foundPayers then --debug("found treasure"..currentTreasure); ScriptVars:set("OldPayers"..town, currentPayers) ScriptVars:set("Payers"..town, 0) else ScriptVars:set("OldPayers"..town, 0) ScriptVars:set("Payers"..town, 0) end ScriptVars:save() end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- This scripts contains functions to work with the town treasury require("base.common") module("base.townTreasure", package.seeall) -- get the treasure of a town -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetTownTreasure(town) local foundTreasure, currentTreasure = ScriptVars:find("Treasure"..town) if not foundTreasure then return 0; end local treasureNumber = tonumber(currentTreasure); if (treasureNumber == nil) then debug(string.format("Script variable was found and resolved to %s, but failed to convert to a number!", (currentTreasure == nil) and "nil" or currentTreasure)); return 0; end if (treasureNumber > 3000000) then log(string.format("[WARN][Town Treasure] The treasure of %s exceeded 3 million copper coins. Something is wrong. Capping.", town)); return 3000000; end return treasureNumber; end -- get the itemID of a gem for each town. --@town The corresponding town as string: "Cadomyr"|"Runewick"|"Galmair" --@gemNr The number (1 or 2) of the gem function GetTownGem(town,gemNr) if town=="Cadomyr" then end end --Runewick: Emerald and Ruby --Cadomyr: Topaz and Amethyst --Galmair: Bluestond and Blackstone -- get the amount of taxes collected to determine the amount of gems to pay out -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetPaymentAmount(town) local foundTreasure, currentTreasure = ScriptVars:find("OldTreasure"..town) if not foundTreasure then currentTreasure = 0 end return tonumber(currentTreasure) end -- get the amount of taxespayers last month to determine the amount of gems to pay out -- @town Town which treasure we want to get as a string: "Cadomyr"|"Runewick"|"Galmair" function GetTaxpayerNumber(town) local foundPayers, currentNoPayer = ScriptVars:find("OldPayers"..town) if not foundPayers then return 0; end return tonumber(currentNoPayer); end -- change treasure of a town -- @town Town which treasure we want to change -- @amount Amount of money. Positive number = increase treasure; negative number = decrease treasure function ChangeTownTreasure(town,amount) local currentTreasure = GetTownTreasure(town) local newTreasure = currentTreasure + amount ScriptVars:set("Treasure"..town, newTreasure) ScriptVars:save() end -- increases the number of taxpayers for this month by 1. -- @town Town function IncreaseTaxpayerNumber(town) local foundPayers, currentNoPayer = ScriptVars:find("Payers"..town) if foundPayers then --debug("found payers: "..currentNoPayer) ScriptVars:set("Payers"..town, currentNoPayer+1) else ScriptVars:set("Payers"..town, 1) --debug("found payers: 1") end ScriptVars:save() end -- New month starts: -- * Collected taxes are now stored as "old" taxes (overwrite!) -- * Actual taxes are reset to 0 -- * Total number of taxpayers are stored as "old" Payers (overwrite!) -- * Actual number of taxpayers is set to 0 --@town Town --@timeStmp Timestamp of the new month function NewMonthSwitch(town,timeStmp) --debug("NewMonthSwitch with "..town.." and "..timeStmp); local currentTreasure = GetTownTreasure(town); log(string.format("[tax switch] %s's treasure was reset. Old treasure was %d copper coins", town, currentTreasure)) --debug("found treasure"..currentTreasure); ScriptVars:set("OldTreasure"..town, currentTreasure) ScriptVars:set("SwitchedToPayment"..town, timeStmp) ScriptVars:set("Treasure"..town, 0) local foundPayers, currentPayers = ScriptVars:find("Payers"..town) if foundPayers then --debug("found treasure"..currentTreasure); ScriptVars:set("OldPayers"..town, currentPayers) ScriptVars:set("Payers"..town, 0) else ScriptVars:set("OldPayers"..town, 0) ScriptVars:set("Payers"..town, 0) end ScriptVars:save() end
[Hotfix] Added check for valid value from script variables
[Hotfix] Added check for valid value from script variables
Lua
agpl-3.0
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
af372fcb9310b58e38c548006d9829dfc3eec43f
lua/MainGlue.lua
lua/MainGlue.lua
local html_escape={["<"]="&lt;",[">"]="&gt;",["&"]="&amp;"} local uri_escape=function(a) return ("%%%02x"):format(a:byte()) end local uri_unescape=function(a) return string.char(tonumber(a,16)) end escape={ html=function(str) return (str:gsub("[<>&]",html_escape)) end, url=function(str) return (str:gsub("[^a-zA-Z0-9_.~-]",uri_escape)) end, shell=function(str) return (str:gsub("[%s`~!#$&*()|\\'\";<>?{}[%]^]","\\%1")) end } unescape={ url=function(str) return (str:gsub("+"," "):gsub("%%(%x%x)",uri_unescape)) end } -- tag metatable local tagmeth={ render=function(self) local content if self.content then content={} for i,v in ipairs(self.content) do if type(v)=="string" then content[i]=v elseif type(v)=="number" then content[i]=tostring(v) else content[i]=v:render() end end end local options if self.options and next(self.options) then options={} for k,v in pairs(self.options) do if type(k)=="number" then table.insert(options,tostring(v)) else table.insert(options,k.."=\""..tostring(v):gsub("\"","&quot;").."\"") end end end if self.fclose then if content then return table.concat(content).."</"..self.name..">" end return "</"..self.name..">" elseif self.fopen then local result if options then result="<"..self.name.." "..table.concat(options," ")..">" else result="<"..self.name..">" end if content then return result..table.concat(content) end return result else local result if options then result="<"..self.name.." "..table.concat(options," ") else result="<"..self.name end if content then return result..">"..table.concat(content).."</"..self.name..">" end return result.." />" end end, add_content=function(self,...) if not self.content then self.content={} end for i=1,select('#',...) do local value=select(i,...) if type(value)=="string" then if #value~=0 then table.insert(self.content,escape.html(value)) end else table.insert(self.content,value) end end return self end, force_content=function(self,...) if not self.content then self.content={} end for i=1,select('#',...) do local value=select(i,...) if type(value)=="string" then if #value~=0 then table.insert(self.content,value) end else table.insert(self.content,value) end end return self end, add_options=function(self,tbl) if not self.options then self.options={} end for k,v in pairs(tbl) do if type(k)=="number" then table.insert(self.options,v) else self.options[k]=v end end return self end, clear_content=function(self) self.content=nil return self end, clear_options=function(self) self.options=nil return self end, set_content=function(self,...) self:clear_content() return self:add_content(...) end, set_options=function(self,tbl) self:clear_options() return self:add_options(tbl) end, force_open=function(self) self.fopen=true return self end, force_close=function(self) self.fclose=true return true end } local tagmt={ __index=function(self,k) if type(k)=="table" then return self:add_options(k) else return tagmeth[k] end end, __call=tagmeth.add_content } function tag(name) return setmetatable({name=name},tagmt) end -- Specific Tags and Aliases function link(url, opt) if opt then return tag"a"[{href=url, unpack(opt)}] else return tag"a"[{href=url}] end end script = tag"script" function css(args) local a = {type="text/css"} if type(args) == "table" then for k,v in pairs(args) do a[k] = v end end return tag"style"[a] end function doctype() return tag"!DOCTYPE"[{"html"}]:force_open() end -- Return function function content(data, code, ctype) local code = code or 200 local ctype = ctype or "text/html" local content = "" if type(data) == "string" then content = data elseif type(data) == "table" and data.render ~= nil then content = data:render() else content = tostring(data) end context.Data(code, ctype, convert.stringtocharslice(content)) end function form(name) if name ~= nil then local f = _formfunc(tostring(name)) if f == "" then return nil end return f end end function queryvar(name) if name ~= nil then local f = _queryfunc(tostring(name)) if f == "" then return nil end return f end end
local html_escape={["<"]="&lt;",[">"]="&gt;",["&"]="&amp;"} local uri_escape=function(a) return ("%%%02x"):format(a:byte()) end local uri_unescape=function(a) return string.char(tonumber(a,16)) end escape={ html=function(str) return (str:gsub("[<>&]",html_escape)) end, url=function(str) return (str:gsub("[^a-zA-Z0-9_.~-]",uri_escape)) end, shell=function(str) return (str:gsub("[%s`~!#$&*()|\\'\";<>?{}[%]^]","\\%1")) end } unescape={ url=function(str) return (str:gsub("+"," "):gsub("%%(%x%x)",uri_unescape)) end } -- tag metatable local tagmeth={ render=function(self) local content if self.content then content={} for i,v in ipairs(self.content) do if type(v)=="string" then content[i]=v elseif type(v)=="number" then content[i]=tostring(v) else content[i]=v:render() end end end local options if self.options and next(self.options) then options={} for k,v in pairs(self.options) do if type(k)=="number" then table.insert(options,tostring(v)) else table.insert(options,k.."=\""..tostring(v):gsub("\"","&quot;").."\"") end end end if self.fclose then if content then return table.concat(content).."</"..self.name..">" end return "</"..self.name..">" elseif self.fopen then local result if options then result="<"..self.name.." "..table.concat(options," ")..">" else result="<"..self.name..">" end if content then return result..table.concat(content) end return result else local result if options then result="<"..self.name.." "..table.concat(options," ") else result="<"..self.name end if content then return result..">"..table.concat(content).."</"..self.name..">" end return result.." />" end end, add_content=function(self,...) if not self.content then self.content={} end for i=1,select('#',...) do local value=select(i,...) if type(value)=="string" then if #value~=0 then table.insert(self.content,escape.html(value)) end else table.insert(self.content,value) end end return self end, force_content=function(self,...) if not self.content then self.content={} end for i=1,select('#',...) do local value=select(i,...) if type(value)=="string" then if #value~=0 then table.insert(self.content,value) end else table.insert(self.content,value) end end return self end, add_options=function(self,tbl) if not self.options then self.options={} end for k,v in pairs(tbl) do if type(k)=="number" then table.insert(self.options,v) else self.options[k]=v end end return self end, clear_content=function(self) self.content=nil return self end, clear_options=function(self) self.options=nil return self end, set_content=function(self,...) self:clear_content() return self:add_content(...) end, set_options=function(self,tbl) self:clear_options() return self:add_options(tbl) end, force_open=function(self) self.fopen=true return self end, force_close=function(self) self.fclose=true return true end } local tagmt={ __index=function(self,k) if type(k)=="table" then return self:add_options(k) else return tagmeth[k] end end, __call=tagmeth.add_content } function tag(name) return setmetatable({name=name},tagmt) end -- Specific Tags and Aliases function link(url, opt) if opt then return tag"a"[{href=url, unpack(opt)}] else return tag"a"[{href=url}] end end function script(...) return tag"script"(...) end function css(args) local a = {type="text/css"} if type(args) == "table" then for k,v in pairs(args) do a[k] = v end end return tag"style"[a] end function doctype() return tag"!DOCTYPE"[{"html"}]:force_open() end -- Return function function content(data, code, ctype) local code = code or 200 local ctype = ctype or "text/html" local content = "" if type(data) == "string" then content = data elseif type(data) == "table" and data.render ~= nil then content = data:render() else content = tostring(data) end context.Data(code, ctype, convert.stringtocharslice(content)) end function form(name) if name ~= nil then local f = _formfunc(tostring(name)) if f == "" then return nil end return f end end function queryvar(name) if name ~= nil then local f = _queryfunc(tostring(name)) if f == "" then return nil end return f end end
Fixes.
Fixes.
Lua
mit
vifino/carbon,vifino/carbon,carbonsrv/carbon,carbonsrv/carbon,carbonsrv/carbon,vifino/carbon
dadd485e6fda8c85bb4c5301653dad7a98886a53
util/datamanager.lua
util/datamanager.lua
local format = string.format; local setmetatable, type = setmetatable, type; local pairs = pairs; local char = string.char; local loadfile, setfenv, pcall = loadfile, setfenv, pcall; local log = log; local io_open = io.open; module "datamanager" ---- utils ----- local encode, decode; local log = function (type, msg) return log(type, "datamanager", msg); end do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end)); end end local function basicSerialize (o) if type(o) == "number" or type(o) == "boolean" then return tostring(o) else -- assume it is a string return string.format("%q", tostring(o)) end end local function simplesave (f, o) if type(o) == "number" then f:write(o) elseif type(o) == "string" then f:write(format("%q", o)) elseif type(o) == "table" then f:write("{\n") for k,v in pairs(o) do f:write(" [", basicSerialize(k), "] = ") simplesave(f, v) f:write(",\n") end f:write("}\n") else error("cannot serialize a " .. type(o)) end end ------- API ------------- function getpath(username, host, datastore) if username then return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username)); elseif host then return format("data/%s/%s.dat", encode(host), datastore); else return format("data/%s.dat", datastore); end end function load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore)); if not data then log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end setfenv(data, {}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end return ret; end function store(username, host, datastore, data) local f, msg = io_open(getpath(username, host, datastore), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..username.."@"..host); return nil; end f:write("return "); simplesave(f, data); f:close(); return true; end
local format = string.format; local setmetatable, type = setmetatable, type; local pairs = pairs; local char = string.char; local loadfile, setfenv, pcall = loadfile, setfenv, pcall; local log = log; local io_open = io.open; local tostring = tostring; module "datamanager" ---- utils ----- local encode, decode; local log = function (type, msg) return log(type, "datamanager", msg); end do local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end)); end end local function basicSerialize (o) if type(o) == "number" or type(o) == "boolean" then return tostring(o) else -- assume it is a string return format("%q", tostring(o)) end end local function simplesave (f, o) if type(o) == "number" then f:write(o) elseif type(o) == "string" then f:write(format("%q", o)) elseif type(o) == "table" then f:write("{\n") for k,v in pairs(o) do f:write(" [", basicSerialize(k), "] = ") simplesave(f, v) f:write(",\n") end f:write("}\n") else error("cannot serialize a " .. type(o)) end end ------- API ------------- function getpath(username, host, datastore) if username then return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username)); elseif host then return format("data/%s/%s.dat", encode(host), datastore); else return format("data/%s.dat", datastore); end end function load(username, host, datastore) local data, ret = loadfile(getpath(username, host, datastore)); if not data then log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end setfenv(data, {}); local success, ret = pcall(data); if not success then log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..username.."@"..host); return nil; end return ret; end function store(username, host, datastore, data) local f, msg = io_open(getpath(username, host, datastore), "w+"); if not f then log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..username.."@"..host); return nil; end f:write("return "); simplesave(f, data); f:close(); return true; end
Minor fix
Minor fix
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
0cb7c978aec8d2d485dae96518fb8ff42b4eb303
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) str = str:gsub("&", "&amp;") for k,v in pairs({ ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", ["Ä"] = "&Auml;", ["ä"] = "&auml;", ["Ö"] = "&Ouml;", ["ö"] = "&ouml;", ["Ü"] = "&Uuml;", ["ü"] = "&uuml;" }) do str = str:gsub(k,v) end return str 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=name, time=time, popped=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 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) 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) str = str:gsub("&", "&amp;") for k,v in pairs({ ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", ["Ä"] = "&Auml;", ["ä"] = "&auml;", ["Ö"] = "&Ouml;", ["ö"] = "&ouml;", ["Ü"] = "&Uuml;", ["ü"] = "&uuml;" }) do str = str:gsub(k,v) end return str 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=urldecode(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 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 missing urldecoding for getting highscore
Fixed missing urldecoding for getting highscore
Lua
mit
max1220/balloons,max1220/balloons,max1220/balloons
fd0af8274f2a868e959c6c62a41347ecea005b1a
src/tools/msc.lua
src/tools/msc.lua
-- -- msc.lua -- Interface for the MS C/C++ compiler. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- premake.tools.msc = {} local msc = premake.tools.msc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- function msc.getcppflags(cfg) return {} end -- -- Returns list of C compiler flags for a configuration. -- msc.cflags = { flags = { SEH = "/EHa /EHsc", Symbols = "/Z7", }, optimize = { Off = "/Od", Speed = "/O2", } } function msc.getcflags(cfg) local flags = config.mapFlags(cfg, msc.cflags) local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD") if config.isDebugBuild(cfg) then runtime = runtime .. "d" end table.insert(flags, runtime) return flags end -- -- Returns list of C++ compiler flags for a configuration. -- msc.cxxflags = { } function msc.getcxxflags(cfg) return table.translate(cfg.flags, msc.cxxflags) end msc.ldflags = { Symbols = "/DEBUG", } -- -- Decorate defines for the MSVC command line. -- function msc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function msc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, "/FI" .. premake.quoted(fn)) end) return result end -- -- Decorate include file search paths for the MSVC command line. -- function msc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of linker flags for a specific configuration. -- msc.ldflags = { Symbols = "/DEBUG", } function msc.getldflags(cfg) local flags = table.translate(cfg.flags, msc.ldflags) if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then table.insert(flags, "/MANIFEST") end if config.isOptimizedBuild(cfg) then table.insert(flags, "/OPT:REF /OPT:ICF") end for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do table.insert(flags, '/LIBPATH:"' .. libdir .. '"') end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function msc.getlinks(cfg) local links = config.getlinks(cfg, "system", "fullpath") return links end -- -- Returns makefile-specific configuration rules. -- function msc.getmakesettings(cfg) return nil end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- function msc.gettoolname(cfg, tool) return nil end
-- -- msc.lua -- Interface for the MS C/C++ compiler. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- premake.tools.msc = {} local msc = premake.tools.msc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- function msc.getcppflags(cfg) return {} end -- -- Returns list of C compiler flags for a configuration. -- msc.cflags = { flags = { SEH = "/EHa", Symbols = "/Z7", }, optimize = { Off = "/Od", Speed = "/O2", } } function msc.getcflags(cfg) local flags = config.mapFlags(cfg, msc.cflags) local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD") if config.isDebugBuild(cfg) then runtime = runtime .. "d" end table.insert(flags, runtime) if not cfg.flags.SEH then table.insert(flags, "/EHsc") end return flags end -- -- Returns list of C++ compiler flags for a configuration. -- msc.cxxflags = { } function msc.getcxxflags(cfg) return table.translate(cfg.flags, msc.cxxflags) end msc.ldflags = { Symbols = "/DEBUG", } -- -- Decorate defines for the MSVC command line. -- function msc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function msc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, "/FI" .. premake.quoted(fn)) end) return result end -- -- Decorate include file search paths for the MSVC command line. -- function msc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of linker flags for a specific configuration. -- msc.ldflags = { Symbols = "/DEBUG", } function msc.getldflags(cfg) local flags = table.translate(cfg.flags, msc.ldflags) if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then table.insert(flags, "/MANIFEST") end if config.isOptimizedBuild(cfg) then table.insert(flags, "/OPT:REF /OPT:ICF") end for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do table.insert(flags, '/LIBPATH:"' .. libdir .. '"') end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function msc.getlinks(cfg) local links = config.getlinks(cfg, "system", "fullpath") return links end -- -- Returns makefile-specific configuration rules. -- function msc.getmakesettings(cfg) return nil end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- function msc.gettoolname(cfg, tool) return nil end
Fix broken MSC exception handling flag
Fix broken MSC exception handling flag --HG-- extra : rebase_source : d03ec2013c90802ac61d85cbdbefaf3e126059df
Lua
bsd-3-clause
annulen/premake,Lusito/premake,Lusito/premake,annulen/premake,Lusito/premake,Lusito/premake,warrenseine/premake,warrenseine/premake,annulen/premake,warrenseine/premake,annulen/premake
5cf4a0cbb153a8ff1c69acea9d7bd9d5f5b6969e
ssbase/gamemode/sv_profiles.lua
ssbase/gamemode/sv_profiles.lua
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"} local update_filter = {"id", "steamId", "rank", "avatarUrl"} SS.Profiles = {} -- Check if the player has a valid avatar url stored in the database, if not fetch it. function PLAYER_META:CheckAvatar() if self.profile and (!self.profile.avatarUrl or string.Trim(self.profile.avatarUrl) == "" or string.sub(self.profile.avatarURL, string.len(self.profile.avatarURL)-9, string.len(self.profile.avatarURL)) == "_full.jpg") then http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64, function(body) if self and self:IsValid() then body = util.JSONToTable(body) DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatarfull.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'") self:ChatPrint("AVATAR DEBUG: "..body.response.players[1].avatarfull) end end, function(error) Error("[AVATAR FETCH FAILED] ".. error) end ) end end function PLAYER_META:CreateProfile() if(self:IsBot()) then return end local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "") local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')" DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end) end function PLAYER_META:ProfileLoad() if(self:IsBot()) then return end MsgN("[PROFILE] Loading ", self) local steamid = self:SteamID() SS.Profiles[steamid] = {} self:ChatPrint("Loading your profile") if DB_DEVS then self:ProfileLoaded() return end timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end) DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'", function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end, function() if self and self:IsValid() then self.ProfileFailed = true self:ChatPrint("We failed to load your profile, trying again in 60 seconds.") timer.Simple(60, function() if self and self:IsValid() then self:ProfileLoad() end end ) end end) end function PLAYER_META:ProfileLoaded(res) local steamid = self:SteamID() if res and res[1] then if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end self.profile = res[1] MsgN("[PROFILE] Loaded ", self) self:SetRank(self.profile.rank) self:SetMoney(self.profile.money) self:SetExp(self.profile.exp) self:SetStoreItems(self.profile.store) self:SetEquipped(self.profile.equipped) self:NetworkOwnedItem() if !self:HasMoney(0) then self:SetMoney(0) self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!") end self:ChatPrint("Your profile has been loaded") elseif res and !res[1] then self:ChatPrint("No profile detected, creating one for you.") self:CreateProfile() return else self.profile = {} self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() self:SetRank(DB_DEVS and 100 or 0) self:SetMoney(100) self:SetExp(1) self:SetStoreItems("") self:SetEquipped("") self:ChatPrint("We had problems loading your profile and have created a temporary one for you.") end self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil self.playtimeStart = os.time() self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() SS.Profiles[self:SteamID()] = self.profile self:CheckAvatar() timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function() if self and self:IsValid() then self.profile.lastLoginTimestamp = os.time() self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart) self.playtimeStart = os.time() self:ProfileSave() else timer.Destroy(steamid.."_ProfileUpdate") end end ) hook.Run("PlayerSetModel", self) self:SetNetworkedBool("ss_profileloaded", true) end /* Sync Profile with database */ function PLAYER_META:ProfileSave() if(self:IsBot()) then return end local profile = SS.Profiles[self:SteamID()] profile.money = self.money profile.exp = self.exp profile.playtime = profile.playtime+(os.time()-self.playtimeStart) profile.store = util.TableToJSON(self.storeItems) profile.equipped = util.TableToJSON(self.storeEquipped) self.playtimeStart = os.time() local Query = "UPDATE users SET " local first = true for k,v in pairs(profile) do if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these. if first then Query = Query..k.."='"..v.."'" first = false else Query = Query..", "..k.."='"..v.."'" end end Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'" DB_Query(Query) end function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this if(self:IsBot()) then return end if !SERVER then return end DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" ) end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetStoreItems(data) if (!data or data == "" or data == "[]") then self.storeItems = {} else self.storeItems = util.JSONToTable(data) end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetEquipped(data) if (!data or data == "" or data == "[]") then self.storeEquipped = {} for i = 1, SS.STORE.SLOT.MAXIMUM do self.storeEquipped[i] = {} end else self.storeEquipped = util.JSONToTable(data) end end
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money", "store", "equipped", "avatarUrl"} local update_filter = {"id", "steamId", "rank", "avatarUrl"} SS.Profiles = {} -- Check if the player has a valid avatar url stored in the database, if not fetch it. function PLAYER_META:CheckAvatar() if self.profile and (!self.profile.avatarUrl or string.Trim(self.profile.avatarUrl) == "" or string.sub(self.profile.avatarURL, string.len(self.profile.avatarURL)-9, string.len(self.profile.avatarURL)) == "_full.jpg") then http.Fetch("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=9D7A9B8269C1C1B1B7B21E659904DDEF&steamids="..self.profile.steamId64, function(body) if self and self:IsValid() then body = util.JSONToTable(body) DB_Query("UPDATE users SET avatarUrl='"..body.response.players[1].avatar.."' WHERE steamId='"..string.sub(self:SteamID(), 7).."'") end end, function(error) Error("[AVATAR FETCH FAILED] ".. error) end ) end end function PLAYER_META:CreateProfile() if(self:IsBot()) then return end local ip = string.Replace(game.IsDedicated() and self:IPAddress() or "127.0.0.1", ".", "") local query = "INSERT INTO users (steamid64, steamid, name, registerIp, lastLoginIP, registerTimestamp, lastLoginTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..ip.."','"..ip.."','"..tostring(os.time()).."','"..tostring(os.time()).."')" DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end) end function PLAYER_META:ProfileLoad() if(self:IsBot()) then return end MsgN("[PROFILE] Loading ", self) local steamid = self:SteamID() SS.Profiles[steamid] = {} self:ChatPrint("Loading your profile") if DB_DEVS then self:ProfileLoaded() return end timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end) DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'", function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end, function() if self and self:IsValid() then self.ProfileFailed = true self:ChatPrint("We failed to load your profile, trying again in 60 seconds.") timer.Simple(60, function() if self and self:IsValid() then self:ProfileLoad() end end ) end end) end function PLAYER_META:ProfileLoaded(res) local steamid = self:SteamID() if res and res[1] then if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end self.profile = res[1] MsgN("[PROFILE] Loaded ", self) self:SetRank(self.profile.rank) self:SetMoney(self.profile.money) self:SetExp(self.profile.exp) self:SetStoreItems(self.profile.store) self:SetEquipped(self.profile.equipped) self:NetworkOwnedItem() if !self:HasMoney(0) then self:SetMoney(0) self:ChatPrint("Oops! You have negative money, we set that to 0 for you. Please tell a developer how this happened!") end self:ChatPrint("Your profile has been loaded") elseif res and !res[1] then self:ChatPrint("No profile detected, creating one for you.") self:CreateProfile() return else self.profile = {} self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() self:SetRank(DB_DEVS and 100 or 0) self:SetMoney(100) self:SetExp(1) self:SetStoreItems("") self:SetEquipped("") self:ChatPrint("We had problems loading your profile and have created a temporary one for you.") end self.profile.playtime = self.profile.playtime or 0 -- Make sure it isn't nil self.playtimeStart = os.time() self.profile.lastLoginIp = self:IPAddress() self.profile.lastLoginTimestamp = os.time() SS.Profiles[self:SteamID()] = self.profile self:CheckAvatar() timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function() if self and self:IsValid() then self.profile.lastLoginTimestamp = os.time() self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart) self.playtimeStart = os.time() self:ProfileSave() else timer.Destroy(steamid.."_ProfileUpdate") end end ) hook.Run("PlayerSetModel", self) self:SetNetworkedBool("ss_profileloaded", true) end /* Sync Profile with database */ function PLAYER_META:ProfileSave() if(self:IsBot()) then return end local profile = SS.Profiles[self:SteamID()] profile.money = self.money profile.exp = self.exp profile.playtime = profile.playtime+(os.time()-self.playtimeStart) profile.store = util.TableToJSON(self.storeItems) profile.equipped = util.TableToJSON(self.storeEquipped) self.playtimeStart = os.time() local Query = "UPDATE users SET " local first = true for k,v in pairs(profile) do if table.HasValue(update_filter, k) then continue end -- We don't want to automatically update these. if first then Query = Query..k.."='"..v.."'" first = false else Query = Query..", "..k.."='"..v.."'" end end Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'" DB_Query(Query) end function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this if(self:IsBot()) then return end if !SERVER then return end DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" ) end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetStoreItems(data) if (!data or data == "" or data == "[]") then self.storeItems = {} else self.storeItems = util.JSONToTable(data) end end -------------------------------------------------- -- -------------------------------------------------- function PLAYER_META:SetEquipped(data) if (!data or data == "" or data == "[]") then self.storeEquipped = {} for i = 1, SS.STORE.SLOT.MAXIMUM do self.storeEquipped[i] = {} end else self.storeEquipped = util.JSONToTable(data) end end
Last fix, hopefully.
Last fix, hopefully.
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
2ff9a83addedbda01ef7f8ec055d8bf56c5cab80
LuaRecipe_to_JL.lua
LuaRecipe_to_JL.lua
recipfns = { "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\ammo.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\capsule.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\equipment.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\fluid-recipe.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\furnace-recipe.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\inserter.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\module.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\recipe.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\turret.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\demo-recipe.lua", "C:\\Users\\mwheath\\Documents\\Factorio\\prototypes\\recipe\\demo-furnace-recipe.lua" } JuMPfn = "recipe_protos.jl" rfid = io.open(JuMPfn, "w+") function getrecips(fn) fid = io.open(fn) loader = function() txt = fid:read() print(txt) if txt == "data:extend(" then txt = "return " elseif txt == ")" then txt = nil elseif txt == "})" then txt = "}" elseif txt == "" then txt = loader() end print(txt) return txt end f = load(loader) fid:close() return f() end function printIngs(dir, igs) if igs["type"] == "fluid" or igs["type"] == "item" then k = igs["name"] a = igs["amount"] else k = igs[1] a = igs[2] end rfid:write(dir .. " \"" .. k .. "\" " .. tostring(a) .. "\n") end function writeRecips() for fn = 1,#recipfns do recips = getrecips(recipfns[fn]) if recips == nil then rfid:write("nil from " .. recipfns[fn] .. "\n") else for r = 1,#recips do if recips[r]["type"] == "recipe" then t = recips[r]["energy_required"] if t == nil then t = 0.5 end if recips[r]["name"] == "basic-oil-processing" then f = "OilBasic" elseif recips[r]["name"] == "advanced-oil-processing" then f = "OilAdvanced" elseif recips[r]["category"] == "chemistry" then f = "ChemPlant" elseif recips[r]["category"] == "smelting" then f = "Smelter" else f = "Assembler" end rfid:write("recipe = Recipe{" .. f .. "}(\"" .. recips[r]["name"] .. "\", ".. tostring(t) .. ")\n") for i = 1, #recips[r]["ingredients"] do printIngs("@RIN", recips[r]["ingredients"][i]) end res = recips[r]["results"] or recips[r]["result"] if type(res) == "table" then for i = 1, #res do printIngs("@ROUT", res[i]) end else if recips[r]["result_count"] ~= nil then a = tostring(recips[r]["result_count"]) else a = "1" end rfid:write("@ROUT \"" .. res .. "\" " .. a .. "\n") end rfid:write("\n") end end end end end writeRecips() --[[ recipe = Recipe{Assembler}("Blue Circuit", 15) @RIN "Green Circuit" 20 @RIN "Red Circuit" 2 @RIN "Sulphuric Acid" 0.5 @ROUT "Blue Circuit" 1 ]]--
#!/usr/bin/lua5.3 recipfns = { "/home/matt/factorio/data/base/prototypes/recipe/ammo.lua", "/home/matt/factorio/data/base/prototypes/recipe/capsule.lua", "/home/matt/factorio/data/base/prototypes/recipe/equipment.lua", "/home/matt/factorio/data/base/prototypes/recipe/fluid-recipe.lua", "/home/matt/factorio/data/base/prototypes/recipe/furnace-recipe.lua", "/home/matt/factorio/data/base/prototypes/recipe/inserter.lua", "/home/matt/factorio/data/base/prototypes/recipe/module.lua", "/home/matt/factorio/data/base/prototypes/recipe/recipe.lua", "/home/matt/factorio/data/base/prototypes/recipe/turret.lua", "/home/matt/factorio/data/base/prototypes/recipe/demo-recipe.lua", "/home/matt/factorio/data/base/prototypes/recipe/demo-furnace-recipe.lua" } function wrt(fid, n, f, t, bits, res, rescnt) fid:write("recipe = Recipe{" .. f .. "}(\"" .. n .. "\", ".. tostring(t) .. ")\n") for i = 1, #bits do printIngs(fid, "@RIN", bits[i]) end if type(res) == "table" then for i = 1, #res do printIngs(fid, "@ROUT", res[i]) end else if rescnt ~= nil then a = tostring(rescnt) else a = "1" end fid:write("@ROUT \"" .. res .. "\" " .. a .. "\n") end end data = {} data["cheap"] = io.open("recipe_protos_cheap.jl", "w+") data["expensive"] = io.open("recipe_protos_expensive.jl", "w+") data["extend"] = function(data, recips) for r = 1,#recips do if recips[r]["type"] == "recipe" then if recips[r]["name"] == "basic-oil-processing" then f = "OilBasic" elseif recips[r]["name"] == "advanced-oil-processing" then f = "OilAdvanced" elseif recips[r]["category"] == "chemistry" then f = "ChemPlant" elseif recips[r]["category"] == "smelting" then f = "Smelter" else f = "Assembler" end print(recips[r]["name"] ) if recips[r]["ingredients"] == nil then t = recips[r]["normal"]["energy_required"] if t == nil then t = 0.5 end wrt(data["cheap"], recips[r]["name"], f, t, recips[r]["normal"]["ingredients"], recips[r]["normal"]["results"] or recips[r]["normal"]["result"], recips[r]["result_count"]) t = recips[r]["expensive"]["energy_required"] if t == nil then t = 0.5 end wrt(data["expensive"], recips[r]["name"], f, t, recips[r]["expensive"]["ingredients"], recips[r]["expensive"]["results"] or recips[r]["expensive"]["result"], recips[r]["result_count"]) else t = recips[r]["energy_required"] if t == nil then t = 0.5 end wrt(data["cheap"], recips[r]["name"], f, t, recips[r]["ingredients"], recips[r]["results"] or recips[r]["result"], recips[r]["result_count"]) wrt(data["expensive"], recips[r]["name"], f, t, recips[r]["ingredients"], recips[r]["results"] or recips[r]["result"], recips[r]["result_count"]) end data["cheap"]:write("\n") data["expensive"]:write("\n") end end end function printIngs(fid, dir, igs) if igs["type"] == "fluid" or igs["type"] == "item" then k = igs["name"] a = igs["amount"] elseif igs["probability"] == nil then k = igs[1] a = igs[2] if k == nil then k = igs["name"] a = igs["amount"] end else k = igs["name"] a = igs["probability"] * igs["amount"] end fid:write(dir .. " \"" .. k .. "\" " .. tostring(a) .. "\n") end function writeRecips() for fn = 1,#recipfns do print(recipfns[fn]) f = loadfile(recipfns[fn]) f() print("procced") end end writeRecips() --[[ recipe = Recipe{Assembler}("Blue Circuit", 15) @RIN "Green Circuit" 20 @RIN "Red Circuit" 2 @RIN "Sulphuric Acid" 0.5 @ROUT "Blue Circuit" 1 ]]--
fixed for 0.15 & 0.16
fixed for 0.15 & 0.16
Lua
mit
lawless-m/factorio-utils
de6cbd7c4afacb9178ab35cf78b7964c7ddd3d68
battery-widget/battery.lua
battery-widget/battery.lua
local wibox = require("wibox") local awful = require("awful") local naughty = require("naughty") local watch = require("awful.widget.watch") -- acpi sample outputs -- Battery 0: Discharging, 75%, 01:51:38 remaining -- Battery 0: Charging, 53%, 00:57:43 until charged battery_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, resize = false }, layout = wibox.container.margin(brightness_icon, 0, 0, 3), set_image = function(self, path) self.icon.image = path end } local path_to_icons = "/usr/share/icons/Arc/status/symbolic/" watch( "acpi", 10, function(widget, stdout, stderr, exitreason, exitcode) local batteryType local _, status, charge_str, time = string.match(stdout, '(.+): (%a+), (%d?%d%d)%%,? ?.*') local charge = tonumber(charge_str) if (charge >= 0 and charge < 15) then batteryType="battery-empty" show_battery_warning() elseif (charge >= 15 and charge < 40) then batteryType="battery-caution-symbolic" elseif (charge >= 40 and charge < 60) then batteryType="battery-low-symbolic" elseif (charge >= 60 and charge < 80) then batteryType="battery-good-symbolic" elseif (charge >= 80 and charge <= 100) then batteryType="battery-full-symbolic" end if status == 'Charging' then batteryType = batteryType .. '-charging' end battery_widget.image = path_to_icons .. batteryType .. ".svg" end ) function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, stderr, reason, exit_code) naughty.notify{ text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end ) end function show_battery_warning() naughty.notify{ icon = "/home/pashik/.config/awesome/nichosi.png", icon_size=100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end -- popup with battery info battery_widget:connect_signal("mouse::enter", function() show_battery_status() end)
local wibox = require("wibox") local awful = require("awful") local naughty = require("naughty") local watch = require("awful.widget.watch") -- acpi sample outputs -- Battery 0: Discharging, 75%, 01:51:38 remaining -- Battery 0: Charging, 53%, 00:57:43 until charged local path_to_icons = "/usr/share/icons/Arc/status/symbolic/" battery_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, resize = false }, layout = wibox.container.margin(brightness_icon, 0, 0, 3), set_image = function(self, path) self.icon.image = path end } watch( "acpi", 10, function(widget, stdout, stderr, exitreason, exitcode) local batteryType local _, status, charge_str, time = string.match(stdout, '(.+): (%a+), (%d?%d%d)%%,? ?.*') local charge = tonumber(charge_str) if (charge >= 0 and charge < 15) then batteryType="battery-empty%s-symbolic" show_battery_warning() elseif (charge >= 15 and charge < 40) then batteryType="battery-caution%s-symbolic" elseif (charge >= 40 and charge < 60) then batteryType="battery-low%s-symbolic" elseif (charge >= 60 and charge < 80) then batteryType="battery-good%s-symbolic" elseif (charge >= 80 and charge <= 100) then batteryType="battery-full%s-symbolic" end if status == 'Charging' then batteryType = string.format(batteryType,'-charging') else batteryType = string.format(batteryType,'') end battery_widget.image = path_to_icons .. batteryType .. ".svg" end ) function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, stderr, reason, exit_code) naughty.notify{ text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end ) end function show_battery_warning() naughty.notify{ icon = "/home/pashik/.config/awesome/nichosi.png", icon_size=100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end -- popup with battery info battery_widget:connect_signal("mouse::enter", function() show_battery_status() end)
battery: fix icons naming for charing status
battery: fix icons naming for charing status
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets,streetturtle/AwesomeWM