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
0d92ddb53dd22f9b0497c32466b5fb7b4a194896
lua/entities/gmod_wire_egp/lib/objects/boxoutline.lua
lua/entities/gmod_wire_egp/lib/objects/boxoutline.lua
local Obj = EGP:NewObject( "BoxOutline" ) Obj.size = 1 Obj.angle = 0 Obj.Draw = function( self ) if (self.a>0 and self.w > 0 and self.h > 0) then surface.SetDrawColor( self.r, self.g, self.b, self.a ) local s = self.size/2 if (self.angle == 0) then -- this is less demanding, so I'm using angle = 0 as a special case local vec1 = { x = self.x - self.w / 2 , y = self.y - self.h / 2 } local vec2 = { x = self.x - self.w / 2 + self.w , y = self.y - self.h / 2 } local vec3 = { x = self.x - self.w / 2 + self.w , y = self.y - self.h / 2 + self.h } local vec4 = { x = self.x - self.w / 2 , y = self.y - self.h / 2 + self.h } EGP:DrawLine( vec1.x , vec1.y + s , vec2.x , vec2.y + s, self.size ) EGP:DrawLine( vec2.x - s , vec2.y , vec3.x - s , vec3.y , self.size ) EGP:DrawLine( vec3.x , vec3.y - s , vec4.x , vec4.y - s, self.size ) EGP:DrawLine( vec4.x + s , vec4.y , vec1.x + s , vec1.y , self.size ) else local centerx, centery = self.x, self.y local ofsx, ofsy = -self.w / 2 , -self.h / 2 local vec1,_ = LocalToWorld(Vector(ofsx,ofsy + s,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local _vec4,_ = LocalToWorld(Vector(ofsx + s,ofsy,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local ofsx, ofsy = self.w / 2 , -self.h / 2 local _vec1,_ = LocalToWorld(Vector(ofsx,ofsy + s,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local vec2,_ = LocalToWorld(Vector(ofsx - s,ofsy,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local ofsx, ofsy = self.w / 2 , self.h / 2 local _vec2,_ = LocalToWorld(Vector(ofsx - s,ofsy,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local vec3,_ = LocalToWorld(Vector(ofsx,ofsy - s,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local ofsx, ofsy = -self.w / 2 , self.h / 2 local _vec3,_ = LocalToWorld(Vector(ofsx,ofsy - s,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) local vec4,_ = LocalToWorld(Vector(ofsx + s,ofsy,0),Angle(0,0,0),Vector(centerx,centery,0),Angle(0,-self.angle,0)) EGP:DrawLine( vec1.x, vec1.y, _vec1.x, _vec1.y, self.size ) EGP:DrawLine( vec2.x, vec2.y, _vec2.x, _vec2.y, self.size ) EGP:DrawLine( vec3.x, vec3.y, _vec3.x, _vec3.y, self.size ) EGP:DrawLine( vec4.x, vec4.y, _vec4.x, _vec4.y, self.size ) end end end Obj.Transmit = function( self ) EGP.umsg.Short( self.size ) EGP.umsg.Short( self.angle ) self.BaseClass.Transmit( self ) end Obj.Receive = function( self, um ) local tbl = {} tbl.size = um:ReadShort() tbl.angle = um:ReadShort() table.Merge( tbl, self.BaseClass.Receive( self, um ) ) return tbl end Obj.DataStreamInfo = function( self ) local tbl = {} tbl.size = self.size tbl.angle = self.angle table.Merge( tbl, self.BaseClass.DataStreamInfo( self ) ) return tbl end
local Obj = EGP:NewObject( "BoxOutline" ) Obj.size = 1 Obj.angle = 0 local function rotate( v, a ) local a = a * math.pi / 180 local x = math.cos(a) * v[1] - math.sin(a) * v[2] local y = math.sin(a) * v[1] + math.cos(a) * v[2] return { x, y } end Obj.Draw = function( self ) if (self.a>0 and self.w > 0 and self.h > 0) then surface.SetDrawColor( self.r, self.g, self.b, self.a ) local x, y, w, h, a, s = self.x, self.y, self.w, self.h, self.angle, self.size local vec1 = rotate( { w / 2 - s / 2, 0 }, -a ) local vec2 = rotate( { -w / 2 + s / 2, 0 }, -a ) local vec3 = rotate( { 0, h / 2 - s / 2 }, -a ) local vec4 = rotate( { 0, -h / 2 + s / 2 }, -a ) surface.DrawTexturedRectRotated( x + math.ceil(vec1[1]), y + math.ceil(vec1[2]), h, s, a + 90 ) surface.DrawTexturedRectRotated( x + math.ceil(vec2[1]), y + math.ceil(vec2[2]), h, s, a + 90 ) surface.DrawTexturedRectRotated( x + math.ceil(vec3[1]), y + math.ceil(vec3[2]), w, s, a ) surface.DrawTexturedRectRotated( x + math.ceil(vec4[1]), y + math.ceil(vec4[2]), w, s, a ) end end Obj.Transmit = function( self ) EGP.umsg.Short( self.size ) EGP.umsg.Short( self.angle ) self.BaseClass.Transmit( self ) end Obj.Receive = function( self, um ) local tbl = {} tbl.size = um:ReadShort() tbl.angle = um:ReadShort() table.Merge( tbl, self.BaseClass.Receive( self, um ) ) return tbl end Obj.DataStreamInfo = function( self ) local tbl = {} tbl.size = self.size tbl.angle = self.angle table.Merge( tbl, self.BaseClass.DataStreamInfo( self ) ) return tbl end
[EGP] Made the box outline drawing code half as big, twice as fast, and fixed both the bug where it'd sometimes be larger than a regular box of the same size, and where its corners would, at certain line widths, not be aligned.
[EGP] Made the box outline drawing code half as big, twice as fast, and fixed both the bug where it'd sometimes be larger than a regular box of the same size, and where its corners would, at certain line widths, not be aligned.
Lua
apache-2.0
mms92/wire,bigdogmat/wire,rafradek/wire,sammyt291/wire,thegrb93/wire,Grocel/wire,garrysmodlua/wire,NezzKryptic/Wire,immibis/wiremod,mitterdoo/wire,dvdvideo1234/wire,Python1320/wire,plinkopenguin/wiremod,notcake/wire,CaptainPRICE/wire,wiremod/wire
048ebc4c0b8cd3bd90b09bc28e3f20c9b3ca7a9d
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; 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
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 or nil).."@"..(host or nil)); 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 or nil).."@"..(host or nil)); 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 or nil).."@"..(host or nil)); return nil; end f:write("return "); simplesave(f, data); f:close(); return true; end
Fixed: datamanager.store and datamanager.load could crash when username or host arguments were nil. (useful for server specific and global data).
Fixed: datamanager.store and datamanager.load could crash when username or host arguments were nil. (useful for server specific and global data).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
5b008aa1dc4f27090794806d4c9cc5da2ba29971
lua/engine/viewport.lua
lua/engine/viewport.lua
local Viewport = {} -- GLFW shared library is libglfw.so on Linux, libglfw.dylib OSX but it's named glfw3.dll on Windows local name = (jit.os == 'Windows') and 'glfw' or 'glfw.3' local glfw = require 'engine.glfw'(name) local scene_tree = {} local window = nil function Viewport.init() -- Initialize GLFW if glfw.Init() == 0 then return false end end function Viewport.create(width, height, windowName) window = glfw.CreateWindow(width, height, windowName) Viewport.window = window if window == 0 then glfw.Terminate() return false end end function Viewport.addNode(node) table.insert(scene_tree,node) end function Viewport.run() -- Make the window's context current glfw.MakeContextCurrent(window) local prev_time = 0.0 local delta = 0.0 -- Loop until the user closes the window while glfw.WindowShouldClose(window) == 0 do delta = (prev_time > 0.0) and (glfw.GetTime() - g_Time) or (1.0/60.0); -- Render here for _,node in ipairs(scene_tree) do node.process(delta) end -- for _,node in ipairs(scene_tree) do -- node.render() -- end -- Swap front and back buffers glfw.SwapBuffers(window) -- Poll for and process events glfw.PollEvents() end glfw.Terminate() end return Viewport
local Viewport = {} -- GLFW shared library is libglfw.so on Linux, libglfw.dylib OSX but it's named glfw3.dll on Windows local name = (jit.os == 'Windows') and 'glfw' or 'glfw.3' local glfw = require 'engine.glfw'(name) local jit = require 'jit' local scene_tree = {} local window = nil function Viewport.init() -- Initialize GLFW if glfw.Init() == 0 then return false end end function Viewport.create(width, height, windowName) -- specify the client API version that the created context must be compatible with -- glfwCreateWindow will still fail if the resulting OpenGL version is less than the one requested -- ImGui requires OpenGL 3.3 glfw.WindowHint('CONTEXT_VERSION_MAJOR', 3); glfw.WindowHint('CONTEXT_VERSION_MINOR', 3); -- specifies which OpenGL profile to create the context for: -- OPENGL_CORE_PROFILE or OPENGL_COMPAT_PROFILE, or OPENGL_ANY_PROFILE. -- If requesting an OpenGL version below 3.2, OPENGL_ANY_PROFILE must be used glfw.WindowHint('OPENGL_PROFILE', 'OPENGL_CORE_PROFILE'); if (jit.os == 'OSX') then -- OpenGL context should be forward-compatible (all functionality deprecated in the requested version of OpenGL is removed) -- This may only be used if the requested OpenGL version is 3.0 or above. glfw.WindowHint('OPENGL_FORWARD_COMPAT', 1); end -- Resizable window in non fullscreen mode -- glfw.WindowHint('RESIZABLE',1) window = glfw.CreateWindow(width, height, windowName) if window == nil then glfw.Terminate() end return window end function Viewport.addNode(node) table.insert(scene_tree,node) end function Viewport.run() -- Make the window's context current glfw.MakeContextCurrent(window) local prev_time = 0.0 local delta = 0.0 -- Loop until the user closes the window while glfw.WindowShouldClose(window) == 0 do delta = (prev_time > 0.0) and (glfw.GetTime() - g_Time) or (1.0/60.0); -- Render here for _,node in ipairs(scene_tree) do node.process(delta) end -- for _,node in ipairs(scene_tree) do -- node.render() -- end -- Swap front and back buffers glfw.SwapBuffers(window) -- Poll for and process events glfw.PollEvents() end glfw.Terminate() end return Viewport
Fix ImGui requirements
Fix ImGui requirements
Lua
mit
lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot
cc21c6f44dbc199f8ce2c2d9d421437f4842235c
core/init.lua
core/init.lua
-- Copyright 2007-2013 Mitchell mitchell.att.foicica.com. See LICENSE. _RELEASE = "Textadept 7.0 beta 3" package.path = _HOME..'/core/?.lua;'..package.path _SCINTILLA = require('iface') _L = require('locale') events = require('events') args = require('args') require('file_io') require('lfs_ext') require('ui') keys = require('keys') _M = {} -- language modules table -- LuaJIT compatibility. if jit then module, package.searchers, bit32 = nil, package.loaders, bit end --[[ This comment is for LuaDoc. --- -- Extends Lua's _G table to provide extra functions and fields for Textadept. -- @field _HOME (string) -- The path to the directory containing Textadept. -- @field _RELEASE (string) -- The Textadept release version string. -- @field _USERHOME (string) -- The path to the user's *~/.textadept/* directory, where all preferences and -- user-data is stored. -- On Windows machines *~/* is the value of the "USERHOME" environment -- variable, typically *C:\Users\username\\* or -- *C:\Documents and Settings\username\\*. On Linux, BSD, and Mac OSX -- machines *~/* is the value of "$HOME", typically */home/username/* and -- */Users/username/* respectively. -- @field _CHARSET (string) -- The character set encoding of the filesystem. -- This is used when [working with files](io.html). -- @field WIN32 (bool) -- If Textadept is running on Windows, this flag is `true`. -- @field OSX (bool) -- If Textadept is running on Mac OSX, this flag is `true`. -- @field CURSES (bool) -- If Textadept is running in the terminal, this flag is `true`. -- Curses feature incompatibilities are listed in the [Appendix][]. -- -- [Appendix]: ../14_Appendix.html#Curses.Compatibility module('_G')]] --[[ The tables below were defined in C. --- -- Table of command line parameters passed to Textadept. -- @class table -- @see _G.args -- @name arg local arg --- -- Table of all open buffers in Textadept. -- Numeric keys have buffer values and buffer keys have their associated numeric -- keys. -- @class table -- @usage _BUFFERS[n] --> buffer at index n -- @usage _BUFFERS[buffer] --> index of buffer in _BUFFERS -- @see _G.buffer -- @name _BUFFERS local _BUFFERS --- -- Table of all views in Textadept. -- Numeric keys have view values and view keys have their associated numeric -- keys. -- @class table -- @usage _VIEWS[n] --> view at index n -- @usage _VIEWS[view] --> index of view in _VIEWS -- @see _G.view -- @name _VIEWS local _VIEWS --- -- The current [buffer](buffer.html) in the current [view](#view). -- @class table -- @name buffer local buffer --- -- The currently focused [view](view.html). -- @class table -- @name view local view -- The functions below are Lua C functions. --- -- Emits a `QUIT` event, and unless any handler returns `false`, quits -- Textadept. -- @see events.QUIT -- @class function -- @name quit local quit --- -- Resets the Lua state by reloading all initialization scripts. -- Language modules for opened files are NOT reloaded. Re-opening the files that -- use them will reload those modules instead. -- This function is useful for modifying user scripts (such as -- *~/.textadept/init.lua* and *~/.textadept/modules/textadept/keys.lua*) on -- the fly without having to restart Textadept. `arg` is set to `nil` when -- reinitializing the Lua State. Any scripts that need to differentiate between -- startup and reset can test `arg`. -- @class function -- @name reset local reset --- -- Calls function *f* with the given arguments after *interval* seconds and then -- repeatedly while *f* returns `true`. A `nil` or `false` return value stops -- repetition. -- @param interval The interval in seconds to call *f* after. -- @param f The function to call. -- @param ... Additional arguments to pass to *f*. -- @class function -- @name timeout local timeout ]]
-- Copyright 2007-2013 Mitchell mitchell.att.foicica.com. See LICENSE. _RELEASE = "Textadept 7.0 beta 3" package.path = _HOME..'/core/?.lua;'..package.path _SCINTILLA = require('iface') events = require('events') args = require('args') _L = require('locale') require('file_io') require('lfs_ext') require('ui') keys = require('keys') _M = {} -- language modules table -- LuaJIT compatibility. if jit then module, package.searchers, bit32 = nil, package.loaders, bit end --[[ This comment is for LuaDoc. --- -- Extends Lua's _G table to provide extra functions and fields for Textadept. -- @field _HOME (string) -- The path to the directory containing Textadept. -- @field _RELEASE (string) -- The Textadept release version string. -- @field _USERHOME (string) -- The path to the user's *~/.textadept/* directory, where all preferences and -- user-data is stored. -- On Windows machines *~/* is the value of the "USERHOME" environment -- variable, typically *C:\Users\username\\* or -- *C:\Documents and Settings\username\\*. On Linux, BSD, and Mac OSX -- machines *~/* is the value of "$HOME", typically */home/username/* and -- */Users/username/* respectively. -- @field _CHARSET (string) -- The character set encoding of the filesystem. -- This is used when [working with files](io.html). -- @field WIN32 (bool) -- If Textadept is running on Windows, this flag is `true`. -- @field OSX (bool) -- If Textadept is running on Mac OSX, this flag is `true`. -- @field CURSES (bool) -- If Textadept is running in the terminal, this flag is `true`. -- Curses feature incompatibilities are listed in the [Appendix][]. -- -- [Appendix]: ../14_Appendix.html#Curses.Compatibility module('_G')]] --[[ The tables below were defined in C. --- -- Table of command line parameters passed to Textadept. -- @class table -- @see _G.args -- @name arg local arg --- -- Table of all open buffers in Textadept. -- Numeric keys have buffer values and buffer keys have their associated numeric -- keys. -- @class table -- @usage _BUFFERS[n] --> buffer at index n -- @usage _BUFFERS[buffer] --> index of buffer in _BUFFERS -- @see _G.buffer -- @name _BUFFERS local _BUFFERS --- -- Table of all views in Textadept. -- Numeric keys have view values and view keys have their associated numeric -- keys. -- @class table -- @usage _VIEWS[n] --> view at index n -- @usage _VIEWS[view] --> index of view in _VIEWS -- @see _G.view -- @name _VIEWS local _VIEWS --- -- The current [buffer](buffer.html) in the current [view](#view). -- @class table -- @name buffer local buffer --- -- The currently focused [view](view.html). -- @class table -- @name view local view -- The functions below are Lua C functions. --- -- Emits a `QUIT` event, and unless any handler returns `false`, quits -- Textadept. -- @see events.QUIT -- @class function -- @name quit local quit --- -- Resets the Lua state by reloading all initialization scripts. -- Language modules for opened files are NOT reloaded. Re-opening the files that -- use them will reload those modules instead. -- This function is useful for modifying user scripts (such as -- *~/.textadept/init.lua* and *~/.textadept/modules/textadept/keys.lua*) on -- the fly without having to restart Textadept. `arg` is set to `nil` when -- reinitializing the Lua State. Any scripts that need to differentiate between -- startup and reset can test `arg`. -- @class function -- @name reset local reset --- -- Calls function *f* with the given arguments after *interval* seconds and then -- repeatedly while *f* returns `true`. A `nil` or `false` return value stops -- repetition. -- @param interval The interval in seconds to call *f* after. -- @param f The function to call. -- @param ... Additional arguments to pass to *f*. -- @class function -- @name timeout local timeout ]]
Fixed bug with previous commit.
Fixed bug with previous commit.
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
057d0e341a91e803a6dfb4a60799feda4a846ac0
src/lua/lzmq/poller.lua
src/lua/lzmq/poller.lua
-- Copyright (c) 2011 by Robert G. Jakabosky <bobby@sharedrealm.com> -- -- 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. -- -- zmq.poller wraps the low-level zmq.ZMQ_Poller object. -- -- This wrapper simplifies the event polling loop. -- local zmq = require"lzmq" local setmetatable = setmetatable local tonumber = tonumber local assert = assert local Poller = zmq.poller local function hashid(obj) obj = tostring(obj) return string.match(obj, ': (%x+)$') or obj end local poller_mt = {} poller_mt.__index = poller_mt local function raw_socket(sock) return (type(sock) == 'table') and (sock.socket) and sock:socket() or sock end function poller_mt:add(sock, events, cb) assert(cb ~= nil) local s = raw_socket(sock) local id = self.poller:add(s, events) self.callbacks[id] = function(revents) return cb(sock, revents) end end function poller_mt:modify(sock, events, cb) local id if events ~= 0 and cb then id = self.poller:modify(raw_socket(sock), events) self.callbacks[id] = function(revents) return cb(sock, revents) end else self:remove(sock) end end function poller_mt:remove(sock) local id = self.poller:remove(raw_socket(sock)) assert(id <= #self.callbacks) for i = id, #self.callbacks do self.callbacks[i] = self.callbacks[i+1] end end function poller_mt:poll(timeout) local poller = self.poller local count, err = poller:poll(timeout) if not count then return nil, err end local callbacks = self.callbacks for i=1,count do local id, revents = poller:next_revents_idx() callbacks[id](revents) end return count end function poller_mt:start() self.is_running = true while self.is_running do local status, err = self:poll(-1) if not status then return false, err end end return true end function poller_mt:stop() self.is_running = false end function poller_mt:__tostring() return string.format("LuaZMQ: Poller (%s)", self.hash) end local M = {} function M.new(pre_alloc) local poller = Poller(pre_alloc) return setmetatable({ poller = poller, hash = hashid(poller), callbacks = {}, }, poller_mt) end return setmetatable(M, {__call = function(tab, ...) return M.new(...) end})
-- Copyright (c) 2011 by Robert G. Jakabosky <bobby@sharedrealm.com> -- -- 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. -- -- zmq.poller wraps the low-level zmq.ZMQ_Poller object. -- -- This wrapper simplifies the event polling loop. -- local zmq = require"lzmq" local setmetatable = setmetatable local tonumber = tonumber local assert = assert local Poller = zmq.poller local function hashid(obj) obj = tostring(obj) return string.match(obj, ': (%x+)$') or obj end local poller_mt = {} poller_mt.__index = poller_mt local function raw_socket(sock) return (type(sock) == 'table') and (sock.socket) and sock:socket() or sock end function poller_mt:add(sock, events, cb) assert(cb ~= nil) local s = raw_socket(sock) local id = self.poller:add(s, events) self.callbacks[id] = function(revents) return cb(sock, revents) end end function poller_mt:modify(sock, events, cb) local id if events ~= 0 and cb then id = self.poller:modify(raw_socket(sock), events) self.callbacks[id] = function(revents) return cb(sock, revents) end else self:remove(sock) end end function poller_mt:remove(sock) local id = self.poller:remove(raw_socket(sock)) assert(id <= #self.callbacks) for i = id, #self.callbacks do self.callbacks[i] = self.callbacks[i+1] end end function poller_mt:poll(timeout) local poller = self.poller local count, err = poller:poll(timeout) if not count then return nil, err end local callbacks = self.callbacks for i=1,count do local id, revents = poller:next_revents_idx() callbacks[id](revents) end return count end function poller_mt:start() self.is_running = true while self.is_running do local status, err = self:poll(-1) if not status then return false, err end end return true end function poller_mt:stop() self.is_running = false end function poller_mt:__tostring() return string.format("LuaZMQ: Poller (%s)", self.hash) end local M = {} function M.new(pre_alloc) local poller = Poller(pre_alloc) return setmetatable({ poller = poller, hash = hashid(poller), callbacks = {}, }, poller_mt) end return setmetatable(M, {__call = function(tab, ...) return M.new(...) end})
Fix spaces [ci skip]
Fix spaces [ci skip]
Lua
mit
moteus/lzmq,zeromq/lzmq,zeromq/lzmq,zeromq/lzmq,moteus/lzmq,moteus/lzmq
d5192ab58e6452176058393cf73cae57657c19f4
lua/table/tablecopy.lua
lua/table/tablecopy.lua
local next,type,rawset,pcall = next,type,rawset,pcall local gmt = debug and debug.getmetatable or getmetatable local function trycopy(obj) local mt = gmt(obj) -- do we have a metatable? does it have a __copy method? if type(mt) == "table" and mt.__copy then -- try to call it (this supports __call-ables too) return pcall(mt.__copy, obj) else return false end end -- deepcopy for long tables local function deep_mode1(inp,copies) -- in case you change the function name, change it here too local _self = deep_mode1 local status, out = trycopy(inp) if status then return copy end if type(inp) ~= "table" then return inp end out = {} copies = type(copies) == "table" and copies or {} -- use normal assignment so we use copies' metatable (if any) copies[inp] = out -- skip metatables by using next directly for key, value in next, inp do rawset(out, key, copies[value] or _self(value, copies)) end return out end local function check(obj, todo, copies) if copies[obj] ~= nil then return copies[obj] end local status, copy = trycopy(obj) if status then copies[obj] = copy return copy end if type(obj) == "table" then local t = {} todo[obj], copies[obj] = t, t return t end return obj end local function deep_mode2(inp, copies) local todo = {} local copies = type(copies) == "table" and copies or {} local out = check(inp, todo, copies) while next(todo) do -- check todo for entries local i, o = next(todo) -- get an entry todo[i] = nil -- and clear it -- do a simple copy for k, v in next, i do rawset(o, k, check(v, todo, copies)) end end return out end -- NB local function shallow(inp) local out = {} for key, value in next, inp do -- skip metatables by using next directly out[key] = value end return out end -- set table.copy.shallow and table.copy.deep -- we could also set the metatable so that calling it calls table.copy.deep -- (or turn it into table.copy(table,deep) where deep is a boolean) table.copy = { shallow = shallow, -- best for copying _G deep = deep_mode1, -- best for copying long chains deep_chain = deep_mode1, -- best for copying long tables deep_long = deep_mode2 } -- //////////// -- // ADDONS // -- //////////// -- START metatable deep copy local mtdeepcopy_mt = { __newindex = function(t, k, v) setmetatable(v, gmt(k)) rawset(t, k, v) end } table.copy.deep_keep_metatable = function(inp) return table.copy.deep(inp, setmetatable({}, mtdeepcopy_mt)) end -- END metatable deep copy -- START metatable shallow copy local mtshallowcopy_mt = { __newindex = function(t, k, v) -- don't rawset() so that __index gets called setmetatable(v, gmt(k)) end, __index = function(t, k) return k end } table.copy.shallow_keep_metatable = function(inp) return table.copy.deep(inp, setmetatable({}, mtshallowcopy_mt)) end -- END metatable shallow copy
local next,type,rawset,pcall = next,type,rawset,pcall local gmt = debug and debug.getmetatable or getmetatable local function trycopy(obj) local mt = gmt(obj) -- do we have a metatable? does it have a __copy method? if type(mt) == "table" and mt.__copy then -- try to call it (this supports __call-ables too) return pcall(mt.__copy, obj) else return false end end -- deepcopy for long tables local function deep_mode1(inp,copies) -- in case you change the function name, change it here too local _self = deep_mode1 local status, out = trycopy(inp) if status then if type(copies) == "table" then copies[inp] = out end return out end if type(inp) ~= "table" then return inp end out = {} copies = type(copies) == "table" and copies or {} -- use normal assignment so we use copies' metatable (if any) copies[inp] = out -- skip metatables by using next directly for key, value in next, inp do rawset(out, key, copies[value] or _self(value, copies)) end return out end local function check(obj, todo, copies) if copies[obj] ~= nil then return copies[obj] end local status, copy = trycopy(obj) if status then copies[obj] = copy return copy end if type(obj) == "table" then local t = {} todo[obj], copies[obj] = t, t return t end return obj end local function deep_mode2(inp, copies) local todo = {} local copies = type(copies) == "table" and copies or {} local out = check(inp, todo, copies) while next(todo) do -- check todo for entries local i, o = next(todo) -- get an entry todo[i] = nil -- and clear it -- do a simple copy for k, v in next, i do rawset(o, k, check(v, todo, copies)) end end return out end -- NB local function shallow(inp) local out = {} for key, value in next, inp do -- skip metatables by using next directly out[key] = value end return out end -- set table.copy.shallow and table.copy.deep -- we could also set the metatable so that calling it calls table.copy.deep -- (or turn it into table.copy(table,deep) where deep is a boolean) table.copy = { shallow = shallow, -- best for copying _G deep = deep_mode1, -- best for copying long chains deep_chain = deep_mode1, -- best for copying long tables deep_long = deep_mode2 } -- //////////// -- // ADDONS // -- //////////// -- START metatable deep copy local mtdeepcopy_mt = { __newindex = function(t, k, v) setmetatable(v, gmt(k)) rawset(t, k, v) end } table.copy.deep_keep_metatable = function(inp) return table.copy.deep(inp, setmetatable({}, mtdeepcopy_mt)) end -- END metatable deep copy -- START metatable shallow copy local mtshallowcopy_mt = { __newindex = function(t, k, v) -- don't rawset() so that __index gets called setmetatable(v, gmt(k)) end, __index = function(t, k) return k end } table.copy.shallow_keep_metatable = function(inp) return table.copy.deep(inp, setmetatable({}, mtshallowcopy_mt)) end -- END metatable shallow copy
Fix derp... again
Fix derp... again
Lua
mit
SoniEx2/Stuff,SoniEx2/Stuff
c66eaccb89873efd5b5a572ecb5b1f3a070777c3
lib/out.lua
lib/out.lua
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment 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. ]=============================================================================] -- Note: Most/all of these functions are global too, because they are "too vital" -- TODO: Make globalisation optional. local out = {} do -- Overwrites `io.output' to our log file(s) io.output('jelly_stdout' .. (radiant.is_server and '_server' or '') .. '.log') local function print_plain(to_logger, ...) local t = { ... } local argc = select('#', ...) io.write('[') io.write(os.date()) io.write('] ') for i = 1, argc do t[i] = tostring(t[i]) io.write(t[i]) t[i] = t[i]:gsub('%%', '%%%%') if i < argc then io.write("\t") end end io.write("\n") io.flush() if to_logger then radiant.log.write('stdout', 0, table.concat(t, '\t')) end end function print(...) print_plain(true, ...) end function printf(str, ...) print_plain(false, string.format(str, ...)) radiant.log.write('stdout', 0, str, ...) end out.print, out.printf = print, printf end return out
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment 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. ]=============================================================================] -- Note: Most/all of these functions are global too, because they are "too vital" -- TODO: Make globalisation optional. local out = {} do -- Overwrites `io.output' to our log file(s) io.output('jelly_stdout' .. (radiant.is_server and '_server' or '') .. '.log') local function print_plain(to_logger, ...) local t = { ... } local argc = select('#', ...) io.write('[') io.write(os.date()) io.write('] ') for i = 1, argc do t[i] = tostring(t[i]) io.write(t[i]) t[i] = t[i]:gsub('%%', '%%%%') if i < argc then io.write("\t") end end io.write("\n") io.flush() if to_logger then radiant.log.write('stdout', 0, table.concat(t, '\t')) end end function print(...) print_plain(true, ...) end function printf(str, ...) local t = { ... } local argc = select('#', ...) for i = 1, argc do if type(t[i]) ~= 'number' then t[i] = tostring(t[i]) end end print_plain(false, string.format(str, unpack(t))) radiant.log.write('stdout', 0, str, unpack(t)) end out.print, out.printf = print, printf end return out
Fixed printf() for userdata and nil
Fixed printf() for userdata and nil
Lua
mit
Quit/jelly
4f4443f44f31f1ca1a0b62f6a238a72ad5ca4a7d
lib/cxjob.lua
lib/cxjob.lua
local cxjob = {} local function getJobInfo(server) local info = { 'k.aics.riken.jp' = { submitCmd = 'pjsub', delCmd = 'pjdel', statCmd = 'pjstat' statStateColumn = 0, statStateRow = 0, jobEndFunc = function(t) -- TODO: 'END' return false end, }, 'ff01.j-focus.jp' = { submitCmd = 'fjsub', delCmd = 'fjdel', statCmd = 'fjstat' statStateColumn = 0, statStateRow = 0, jobEndFunc = function (t) if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true else return false end end, } } return info[server] end function cxjob.new(usrname, sshkey, server) local inst = { user = usrname, sshkey = sshkey, server = server } inst.jobinfo = getJobInfo(server) setmetatable(inst, {__index = cxjob}) return inst; end function cxjob:uploadFile(localfile, remotefile) if (not remotefile) then remotefile = "./" end local scpcmd = 'scp -i '.. self.sshkey .. ' ' .. localfile .. ' ' .. self.user ..'@'.. self.server .. ':' .. remotefile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function cxjob:downloadFile(remotefile, localfile) if (not localfile) then localfile = "./" end local scpcmd = 'scp -i '.. self.sshkey .. ' ' .. self.user ..'@'.. self.server .. ':' .. remotefile .. ' ' .. localfile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end --- Remote(ssh) commands local function sshCmd(user, server, key, cmd, disableErr) local nullDev = '/dev/null' if (getPlatform() == 'Windows') then disableErr = false end local sshcmd = 'ssh -i '.. key .. ' ' .. user ..'@'.. server .. ' "' .. cmd ..'"' .. (disableErr and (' 2>'..nullDev) or '') --print('CMD>' .. sshcmd) local handle = io.popen(sshcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function cxjob:remoteExtractFile(filepath, varbose) local option = verbose and 'xvf' or 'xf' local cmd = 'tar ' .. option .. ' ' .. filepath return sshCmd(self.user, self.server, self.sshkey, cmd) end function cxjob:remoteCompressFile(srcfile, tarfile, verbose) local option = verbose and 'czvf' or 'czf' local cmd = 'tar ' .. option .. ' ' .. tarfile .. ' ' .. srcfile return sshCmd(self.user, self.server, self.sshkey, cmd) end function cxjob:remoteDeleteFile(filename) -- TODO print('not implemented yet!') end function cxjob:remoteMoveFile(fromFile, toFile) -- TODO print('not implemented yet!') end function cxjob:remoteCopyFile(fromFile, toFile) -- TODO print('not implemented yet!') end function cxjob:remoteMakeDir(dirpath) -- TODO print('not implemented yet!') end function cxjob:remoteDeleteDir(dirname) -- TODO print('not implemented yet!') end local function split(str, delim) local result,pat,lastPos = {},"(.-)" .. delim .. "()",1 for part, pos in string.gmatch(str, pat) do --print(pos, part) table.insert(result, part); lastPos = pos end table.insert(result, string.sub(str, lastPos)) return result end local function statSplit(res) local t = split(res, '\n') local statTable = {} for i,v in pairs(t) do local ss = string.gmatch(v,"[^%s]+") local statColumn = {} for k in ss do statColumn[#statColumn + 1] = k; end statTable[#statTable+1] = statColumn end return statTable end local function parseJobID(conf, cmdret) local t = split(cmdret, ' ') return t[conf.submitIDRow] end local function parseJobStat(conf, cmdret, jobid) local t = statSplit(cmdret) --[[ print('===============') for i,j in pairs(t) do io.write(i .. ',') for k,w in pairs(j) do io.write(k .. ': ' .. w .. ' ') end io.write('\n') end print('===============') --]] if conf.jobEndFunc(t) then --if (t[1][1] == 'Invalid' and t[1][2] == 'job') then -- END return 'END' end if (#t >= conf.statStateColumn and #(t[conf.statStateColumn]) >= conf.statStateRow) then return t[conf.statStateColumn][conf.statStateRow]; else return 'END' -- not found job end end function cxjob:remoteJobSubmit(jobdata) local cmdTarget = 'cd ' .. jobdata.targetpath ..';' local cmdSubmit = cmdTarget .. self.submitCmd .. ' ' .. jobdata.job --print(cmdSubmit) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdSubmit, true) local jobid = parseJobID(self.jobinfo, cmdret) jobdata.id = jobid --print('JOB ID = '.. jobid) return jobid end function cxjob:remoteJobDel(jobdata) if (not jobdata.id) then print('[Error] job id is invalid') return end local cmdDel = self.jobinfo.delCmd .. ' ' .. jobdata.id --print(cmdDel) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdDel, true) end function cxjob:remoteJobStat(jobdata) local cmdStat = self.jobinfo.statCmd .. ' ' .. (jobdata.id and jobdata.id or '') --print(cmdStat) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdStat, true) local jobstat = parseJobStat(self.jobinof, cmdret, jobdata.id) --print('JOB ST = ' .. jobstat) return jobstat end return cxjob
--[[ USAGE: local cxjob = require('cxjob') local jobmgr = cxjob.new( 'username', 'to_sshkey_path', 'server_address') or local jobmgr = cxjob.new( {username = 'username', sshkey = 'to_sshkey_path', server = 'server_address'}) --]] local cxjob = {} local function getJobInfo(server) local info = { ["k.aics.riken.jp"] = { submitCmd = 'pjsub', submitIDRow = 6, delCmd = 'pjdel', statCmd = 'pjstat', statStateColumn = 6, statStateRow = 4, jobEndFunc = function(t) -- TODO: 'END' return false end, }, ["ff01.j-focus.jp"] = { submitCmd = 'fjsub', submitIDRow = 4, delCmd = 'fjdel', statCmd = 'fjstat', statStateColumn = 5, statStateRow = 4, jobEndFunc = function (t) if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true else return false end end, } } return info[server] end function cxjob.new(username_or_table, sshkey, server) local username if type(username_or_table) == 'table' then username = username_or_table.user sshkey = username_or_table.sshkey server = username_or_table.server else username = username_or_table -- this is username. end local inst = { user = username, sshkey = sshkey, server = server } inst.jobinfo = getJobInfo(server) setmetatable(inst, {__index = cxjob}) return inst; end function cxjob:uploadFile(localfile, remotefile) if (not remotefile) then remotefile = "./" end local scpcmd = 'scp -i '.. self.sshkey .. ' ' .. localfile .. ' ' .. self.user ..'@'.. self.server .. ':' .. remotefile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function cxjob:downloadFile(remotefile, localfile) if (not localfile) then localfile = "./" end local scpcmd = 'scp -i '.. self.sshkey .. ' ' .. self.user ..'@'.. self.server .. ':' .. remotefile .. ' ' .. localfile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end --- Remote(ssh) commands local function sshCmd(user, server, key, cmd, disableErr) local nullDev = '/dev/null' if (getPlatform() == 'Windows') then disableErr = false end local sshcmd = 'ssh -i '.. key .. ' ' .. user ..'@'.. server .. ' "' .. cmd ..'"' .. (disableErr and (' 2>'..nullDev) or '') --print('CMD>' .. sshcmd) local handle = io.popen(sshcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function cxjob:remoteExtractFile(filepath, varbose) local option = verbose and 'xvf' or 'xf' local cmd = 'tar ' .. option .. ' ' .. filepath return sshCmd(self.user, self.server, self.sshkey, cmd) end function cxjob:remoteCompressFile(srcfile, tarfile, verbose) local option = verbose and 'czvf' or 'czf' local cmd = 'tar ' .. option .. ' ' .. tarfile .. ' ' .. srcfile return sshCmd(self.user, self.server, self.sshkey, cmd) end function cxjob:remoteDeleteFile(filename) -- TODO print('not implemented yet!') end function cxjob:remoteMoveFile(fromFile, toFile) -- TODO print('not implemented yet!') end function cxjob:remoteCopyFile(fromFile, toFile) -- TODO print('not implemented yet!') end function cxjob:remoteMakeDir(dirpath) -- TODO print('not implemented yet!') end function cxjob:remoteDeleteDir(dirname) -- TODO print('not implemented yet!') end local function split(str, delim) local result,pat,lastPos = {},"(.-)" .. delim .. "()",1 for part, pos in string.gmatch(str, pat) do --print(pos, part) table.insert(result, part); lastPos = pos end table.insert(result, string.sub(str, lastPos)) return result end local function statSplit(res) local t = split(res, '\n') local statTable = {} for i,v in pairs(t) do local ss = string.gmatch(v,"[^%s]+") local statColumn = {} for k in ss do statColumn[#statColumn + 1] = k; end statTable[#statTable+1] = statColumn end return statTable end local function parseJobID(conf, cmdret) local t = split(cmdret, ' ') return t[conf.submitIDRow] end local function parseJobStat(conf, cmdret, jobid) local t = statSplit(cmdret) --[[ print('===============') for i,j in pairs(t) do io.write(i .. ',') for k,w in pairs(j) do io.write(k .. ': ' .. w .. ' ') end io.write('\n') end print('===============') --]] if conf.jobEndFunc(t) then --if (t[1][1] == 'Invalid' and t[1][2] == 'job') then -- END return 'END' end if (#t >= conf.statStateColumn and #(t[conf.statStateColumn]) >= conf.statStateRow) then return t[conf.statStateColumn][conf.statStateRow]; else return 'END' -- not found job end end function cxjob:remoteJobSubmit(jobdata) local cmdTarget = 'cd ' .. jobdata.targetpath ..';' local cmdSubmit = cmdTarget .. self.jobinfo.submitCmd .. ' ' .. jobdata.job print(cmdSubmit) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdSubmit, true) local jobid = parseJobID(self.jobinfo, cmdret) jobdata.id = jobid --print('JOB ID = '.. jobid) return jobid end function cxjob:remoteJobDel(jobdata) if (not jobdata.id) then print('[Error] job id is invalid') return end local cmdDel = self.jobinfo.delCmd .. ' ' .. jobdata.id --print(cmdDel) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdDel, true) end function cxjob:remoteJobStat(jobdata) local cmdStat = self.jobinfo.statCmd .. ' ' .. (jobdata.id and jobdata.id or '') --print(cmdStat) local cmdret = sshCmd(self.user, self.server, self.sshkey, cmdStat, true) local jobstat = parseJobStat(self.jobinfo, cmdret, jobdata.id) --print('JOB ST = ' .. jobstat) return jobstat end return cxjob
fixed cxjob
fixed cxjob
Lua
bsd-2-clause
avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI
0da055bea818ec2ee56e0d2902d884691dda66cc
src_trunk/resources/spike-system/s_spikes.lua
src_trunk/resources/spike-system/s_spikes.lua
TotalSpikes=nil Spike = {} SpikeLimit=5 Shape= {} function PlacingSpikes(sourcePlayer, command) local theTeam = getPlayerTeam(sourcePlayer) local teamType = getElementData(theTeam, "type") if (teamType==2) then local x1,y1,z1 = getElementPosition(sourcePlayer) local rotz = getPedRotation(sourcePlayer) if(TotalSpikes == nil or TotalSpikes < SpikeLimit) then if(TotalSpikes == nil) then TotalSpikes = 1 else TotalSpikes = TotalSpikes+1 end for value=1,SpikeLimit,1 do if(Spike[value] == nil) then Spike[value] = createObject ( 1593, x1, y1, z1-0.8, 0.0, 0.0, rotz+90.0) exports.pool:allocateElement(Spike[value]) Shape[value] = createColCuboid ( x1-0.5, y1-0.5, z1-0.8, 2.0, 2.0, 2.5) exports.pool:allocateElement(Shape[value]) setElementData(Shape[value], "type", "spikes") outputChatBox("Spawned spikes with ID:" .. value, sourcePlayer, 0, 194, 0) break end end else outputChatBox("Too many spikes are already spawned.", sourcePlayer, 255, 194, 14) end end end addCommandHandler("deployspikes", PlacingSpikes) function RemovingSpikes(sourcePlayer, command, ID) local theTeam = getPlayerTeam(sourcePlayer) local teamType = getElementData(theTeam, "type") if (teamType==2) then if not (ID) then outputChatBox("SYNTAX: /removespikes [ID]", sourcePlayer, 255, 194, 14) else local message = tonumber(ID) if(Spike[message] ~= nil) then local x2,y2,z2 = getElementPosition(Spike[message]) local x1,y1,z1 = getElementPosition(sourcePlayer) if (getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2) <= 10) then outputChatBox("Removed spikes with ID:" .. message, sourcePlayer, 0, 194, 0) TotalSpikes = TotalSpikes -1 destroyElement(Spike[message]) Spike[message] = nil destroyElement(Shape[message]) Shape[message] = nil if(TotalSpikes <= 0) then TotalSpikes = nil end else outputChatBox("You are too far from those spikes!", sourcePlayer, 255, 194, 14) end else outputChatBox("No spikes with that ID found!", sourcePlayer, 255, 194, 14) end end end end addCommandHandler("removespikes", RemovingSpikes) function AdminRemovingSpikes(sourcePlayer, command) for value=1,SpikeLimit,1 do if(Spike[value] ~= nil) then local id = tonumber ( value ) destroyElement(Spike[id]) Spike[id] = nil destroyElement(Shape[message]) Shape[message] = nil end end triggerClientEvent ("onAllSpikesRemoved", getRootElement(), Shape, SpikeLimit) outputChatBox("Removed all the spawned spikes.", sourcePlayer, 0, 194, 0) TotalSpikes = nil end addCommandHandler("aremovespikes", AdminRemovingSpikes)
TotalSpikes=nil Spike = {} SpikeLimit=5 Shape= {} function PlacingSpikes(sourcePlayer, command) local theTeam = getPlayerTeam(sourcePlayer) local teamType = getElementData(theTeam, "type") if (teamType==2) then local x1,y1,z1 = getElementPosition(sourcePlayer) local rotz = getPedRotation(sourcePlayer) if(TotalSpikes == nil or TotalSpikes < SpikeLimit) then if(TotalSpikes == nil) then TotalSpikes = 1 else TotalSpikes = TotalSpikes+1 end for value=1,SpikeLimit,1 do if(Spike[value] == nil) then Spike[value] = createObject ( 1593, x1, y1, z1-0.8, 0.0, 0.0, rotz+90.0) exports.pool:allocateElement(Spike[value]) Shape[value] = createColCuboid ( x1-0.5, y1-0.5, z1-0.8, 2.0, 2.0, 2.5) exports.pool:allocateElement(Shape[value]) setElementData(Shape[value], "type", "spikes") outputChatBox("Spawned spikes with ID:" .. value, sourcePlayer, 0, 194, 0) break end end else outputChatBox("Too many spikes are already spawned.", sourcePlayer, 255, 194, 14) end end end addCommandHandler("deployspikes", PlacingSpikes) function RemovingSpikes(sourcePlayer, command, ID) local theTeam = getPlayerTeam(sourcePlayer) local teamType = getElementData(theTeam, "type") if (teamType==2) then if not (ID) then outputChatBox("SYNTAX: /removespikes [ID]", sourcePlayer, 255, 194, 14) else local message = tonumber(ID) if(Spike[message] ~= nil) then local x2,y2,z2 = getElementPosition(Spike[message]) local x1,y1,z1 = getElementPosition(sourcePlayer) if (getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2) <= 10) then outputChatBox("Removed spikes with ID:" .. message, sourcePlayer, 0, 194, 0) TotalSpikes = TotalSpikes -1 destroyElement(Spike[message]) Spike[message] = nil destroyElement(Shape[message]) Shape[message] = nil if(TotalSpikes <= 0) then TotalSpikes = nil end else outputChatBox("You are too far from those spikes!", sourcePlayer, 255, 194, 14) end else outputChatBox("No spikes with that ID found!", sourcePlayer, 255, 194, 14) end end end end addCommandHandler("removespikes", RemovingSpikes) function AdminRemovingSpikes(sourcePlayer, command) for value=1,SpikeLimit,1 do if(Spike[value] ~= nil) then local id = tonumber ( value ) destroyElement(Spike[id]) Spike[id] = nil destroyElement(Shape[id]) Shape[id] = nil end end outputChatBox("Removed all the spawned spikes.", sourcePlayer, 0, 194, 0) TotalSpikes = nil end addCommandHandler("aremovespikes", AdminRemovingSpikes)
Fixed spike-system
Fixed spike-system git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1209 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
10fc567541163a13c59d7ed2bdb0551a279dd58b
examples.lua
examples.lua
-- This file is a working script that demonstrates the basic syntax of the Lua scripting language. -- This is a one-line comment. You can put these at the ends of lines too. --[[ This is a multiline comment. Everything between the two surrounding symbols will be ignorned by Lua. ]]-- -- variables can be declared and assigned like this: score = 0 -- Notice there is no semi-colon at the end of the above statement. -- In Lua, C-style semi-colons to end statements are optional. The conventional -- Lua style is to omit semi-colons, but they are valid syntactically: score = 20; -- Lua variables are typeless, but the values they refer to have a type. myVariable = 20 -- number myVariable = 20.125 -- also a number myVariable = "hello" -- string myVariable = true -- truth-value (true or false) myVariable = nil -- nil is like nullptr in C++. It means the variable does not refer to any value. --Lua variables can hold other stuff too (threads, tables, userdata), but these are the basics. -- Lua has a built-in library of helpful functions. The first one we'll need is print(), -- which prints a line of text to the console (automatically adding a newline character at the end). -- You can send multiple arguments to print() separated by comments: age = 17 print("Bob is ", age, " years old.") -- Compare the output above with: io.write("Bob is ", age, " years old.\n") -- io.write does not add extra spacing around arguments, features more error checking, -- and you have to provide a newline if you want a line break. print() is meant more -- for quick-and-dirty debugging. Prefer io.write for all other uses that require -- formatted text. -- Functions begin with "function" and end with "end" function sayHi(name) io.write("Hi, ", name, "!\n") end -- You can return values from a function with the "return" keyword: function add(a, b) return a + b end -- Lua functions can return multiple values! function getSquareAndCube(x) return x * x, x * x * x end -- For example, if x == 3, this function returns 9 and 27 square, cube = getSquareAndCube(3) -- Lua variables are global by default. To create variables that are scoped to the -- block they were created in, use the local keyword function variableTest() local localX = 5 -- is in scope on while variableTest() is executing end print("localX: ", localX) -- expect this to print 'nil' -- use the "and" and "or" keywords like C's "&&" and "||". Use "not" like "!": isWithLegalGuardian = false is17OrOlder = true hasMoney = true isAllowed = isWithLegalGuardian or is17OrOlder canSeeMovie = isAllowed and hasMoney cannotSeeMove = not canSeeMovie -- control flow examples: -- if (must have matching "then" and "end") x = 15 if x > 5 then io.write("greater than five\n") end -- You can optionally add an else statement that is -- executed if the if-condition is false: if x > 5 then io.write("x is greater than five.\n") else io.write("x is less than or equal to five\n") end -- You can also create an "if-else" ladder with the elseif keyword like this: score = 100 if score < 10 then io.write("You can do better.\n") elseif score < 20 then io.write("Nice try!\n") elseif score < 50 then io.write("Not a bad score at all...\n") else io.write("You did really well!\n") end -- while (must have matching "do" and "end") x = 0 while x < 10 do io.write(x, "\n") x = x + 1 end -- Instead of "do-while", Lua has "repeat-until": x = 0 repeat x = x + 1 until x > 10 -- for loops! for i = 1, 15 do io.write(i, "\n") end -- You can add an optional third argument to change the iteration step for the for loop: for i = 15, 1, -1 do -- count backwards from 15 to 1. io.write(i, "\n") end -- You can use "break" to break out of any the above loops like in C: x = 0 while x < 10 do x = x + 1 io.write(x, "\n") if x == 5 then io.write("Forget this. I am outta here.\n") break; end end -- Fun fact: you can use do-end to create a scope block like this: sum = 0 do local xx = 227 local yy = 115 sum = xx + yy end -- xx and yy go out of scope here io.write(sum, "\n") -- goto -- Yes, you can use goto to jump to a label in your code. -- A label is defined using the form ::labelNameHere:: -- Here's a example of using goto to break out of a nested loop. --(the break keyword only breaks out of only the most deeply nested loop, not all the loops) -- this example is copied from: http://lua-users.org/wiki/GotoStatement for z=1,10 do for y=1,10 do for x=1,10 do if x^2 + y^2 == z^2 then io.write('found a Pythagorean triple: ', x, y, z, '\n') goto done end end end end ::done:: -- this is the label -- Arrays(sorta...) -- This is actually something called a Lua table, but -- you can also think of this particular use of a table as -- an array: list = { 2, 4, 6, 8, 10 } -- You can iterate over the elements of this table like so: -- (in this example, "in" is a reserved word and ipairs() is a library function) for index, value in ipairs(list) do io.write(index, ": ", value, "\n") end --[[ Here are all the reserved words in Lua: and break do else elseif end false for function goto if in local nil not or repeat return then true until while Guess what: In the examples above, you used every single one of these at least once:) Here are some other operators and tokens with special meanings in Lua: + - * / % ^ # & ~ | << >> // == ~= <= >= < > = ( ) { } [ ] :: ; : , . .. ... ]]-- -- HELPFUL LIBRARY STUFF io.write("You are running ", _VERSION, "\n") -- shows the version of Lua that is executing your scripts. io.write("\nseconds elapsed: ", os.clock(), "\n") -- shows time elapsed in seconds since the start of the application math.randomseed( os.time() ) -- seed RNG with current time. math.random() -- returns a random number between 0 and 1. math.random(1, 6) -- returns a random integer between the arguments (inclusive), so this example could return 1, 2, 3, 4, 5, or 6. -- for complete documentation of the Lua language, C API and library, see: -- https://www.lua.org/manual/5.3/manual.html
-- This file is a working script that demonstrates the basic syntax of the Lua scripting language. -- This is a one-line comment. You can put these at the ends of lines too. --[[ This is a multiline comment. Everything between the two surrounding symbols will be ignorned by Lua. ]]-- -- variables can be declared and assigned like this: score = 0 -- Notice there is no semi-colon at the end of the above statement. -- In Lua, C-style semi-colons to end statements are optional. The conventional -- Lua style is to omit semi-colons, but they are valid syntactically: score = 20; -- Lua variables are typeless, but the values they refer to have types. myVariable = 20 -- number myVariable = 20.125 -- also a number myVariable = "hello" -- string myVariable = true -- truth-value (true or false) myVariable = nil -- nil is like nullptr in C++. It means the variable does not refer to any value. --Lua variables can hold other stuff too (threads, tables, userdata), but these are the basics. -- Lua has a built-in library of helpful functions. The first one we'll need is print(), -- which prints a line of text to the console (automatically adding a newline character at the end). -- You can send multiple arguments to print() separated by comments: age = 17 print("Bob is ", age, " years old.") -- Compare the output above with: io.write("Bob is ", age, " years old.\n") -- io.write does not add extra spacing around arguments, features more error checking, -- and you have to provide a newline if you want a line break. print() is intended -- for quick-and-dirty debugging. Prefer io.write for other uses that require -- formatted text. -- Functions begin with "function" and end with "end" function sayHi(name) io.write("Hi, ", name, "!\n") end -- You can return values from a function with the "return" keyword: function add(a, b) return a + b end -- Lua functions can return multiple values! function getSquareAndCube(x) return x * x, x * x * x end -- For example, if x == 3, the above function returns 9 and 27 square, cube = getSquareAndCube(3) -- Lua variables are global by default. To create variables that are scoped to the -- block they were created in, use the local keyword function variableTest() local localX = 5 -- is in scope on while variableTest() is executing end print("localX: ", localX) -- expect this to print 'nil' -- use the "and" and "or" keywords like C's "&&" and "||". Use "not" like "!": isWithLegalGuardian = false is17OrOlder = true hasMoney = true isAllowed = isWithLegalGuardian or is17OrOlder canSeeMovieRatedR = isAllowed and hasMoney cannotSeeMovieRatedR = not canSeeMovieRatedR -- control flow examples: -- if (must have matching "then" and "end") x = 15 if x > 5 then io.write("greater than five\n") end -- You can optionally add an else statement that is -- executed if the if-condition is false: if x > 5 then io.write("x is greater than five.\n") else io.write("x is less than or equal to five\n") end -- You can also create an "if-else" ladder with the elseif keyword like this: score = 100 if score < 10 then io.write("You can do better.\n") elseif score < 20 then io.write("Nice try!\n") elseif score < 50 then io.write("Not a bad score at all...\n") else io.write("You did really well!\n") end -- while (must have matching "do" and "end") x = 0 while x < 10 do io.write(x, "\n") x = x + 1 end -- Instead of "do-while", Lua has "repeat-until": x = 0 repeat x = x + 1 until x > 10 -- for loops! for i = 1, 15 do io.write(i, "\n") end -- You can add an optional third argument to change the iteration step for the for loop: for i = 15, 1, -1 do -- count backwards from 15 to 1. io.write(i, "\n") end -- You can use "break" to break out of any the above loops like in C: x = 0 while x < 10 do x = x + 1 io.write(x, "\n") if x == 5 then io.write("Forget this. I am outta here.\n") break; end end -- Fun fact: you can use do-end to create a scope block like this: sum = 0 do local xx = 227 local yy = 115 sum = xx + yy end -- xx and yy go out of scope here io.write(sum, "\n") -- goto -- Yes, you can use goto to jump to a label in your code. -- A label is defined using the form ::labelNameHere:: -- Here's a example of using goto to break out of a nested loop. --(the break keyword only breaks out of only the most deeply nested loop, not all the loops) -- this example is copied from: http://lua-users.org/wiki/GotoStatement for z=1,10 do for y=1,10 do for x=1,10 do if x^2 + y^2 == z^2 then io.write('found a Pythagorean triple: ', x, y, z, '\n') goto done end end end end ::done:: -- this is the label -- Arrays(sorta...) -- This is actually something called a Lua table, but -- you can also think of this particular use of a table as -- an array: list = { 2, 4, 6, 8, 10 } -- You can iterate over the elements of this table like so: -- (in this example, "in" is a reserved word and ipairs() is a library function) for index, value in ipairs(list) do io.write(index, ": ", value, "\n") end --[[ Here are all the reserved words in Lua: and break do else elseif end false for function goto if in local nil not or repeat return then true until while Guess what: In the examples above, you used every single one of these at least once:) Here are some other operators and tokens with special meanings in Lua: + - * / % ^ # & ~ | << >> // == ~= <= >= < > = ( ) { } [ ] :: ; : , . .. ... ]]-- -- HELPFUL LIBRARY STUFF io.write("You are running ", _VERSION, "\n") -- shows the version of Lua that is executing your scripts. io.write("\nseconds elapsed: ", os.clock(), "\n") -- shows time elapsed in seconds since the start of the application math.randomseed( os.time() ) -- seed RNG with current time. math.random() -- returns a random number between 0 and 1. math.random(1, 6) -- returns a random integer between the arguments (inclusive), so this example could return 1, 2, 3, 4, 5, or 6. -- for complete documentation of the Lua language, C API and library, see: -- https://www.lua.org/manual/5.3/manual.html
Fixes minor readability issues.
Fixes minor readability issues.
Lua
unlicense
jmarshallstewart/LuaExamples
55e6dd78c3e713e0c5b19c5dfd72da5ca7db98c8
src/program/packetblaster/packetblaster.lua
src/program/packetblaster/packetblaster.lua
module(..., package.seeall) local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local intel_app = require("apps.intel.intel_app") local basic_apps = require("apps.basic.basic_apps") local main = require("core.main") local PcapReader= require("apps.pcap.pcap").PcapReader local LoadGen = require("apps.intel.loadgen").LoadGen local lib = require("core.lib") local ffi = require("ffi") local C = ffi.C local usage = require("program.packetblaster.README_inc") local long_opts = { duration = "D", help = "h" } function run (args) local opt = {} local duration function opt.D (arg) duration = tonumber(arg) end function opt.h (arg) print(usage) main.exit(1) end if #args < 3 or table.remove(args, 1) ~= 'replay' then opt.h() end args = lib.dogetopt(args, opt, "hD:", long_opts) local filename = table.remove(args, 1) local patterns = args local c = config.new() config.app(c, "pcap", PcapReader, filename) config.app(c, "loop", basic_apps.Repeater) config.app(c, "tee", basic_apps.Tee) config.link(c, "pcap.output -> loop.input") config.link(c, "loop.output -> tee.input") local nics = 0 pci.scan_devices() for _,device in ipairs(pci.devices) do if is_device_suitable(device, patterns) then nics = nics + 1 local name = "nic"..nics config.app(c, name, LoadGen, device.pciaddress) config.link(c, "tee."..tostring(nics).."->"..name..".input") end end engine.configure(c) local fn = function () print("Transmissions (last 1 sec):") engine.report_each_app() end local t = timer.new("report", fn, 1e9, 'repeating') timer.activate(t) if duration then engine.main({duration=duration}) else engine.main() end end function is_device_suitable (pcidev, patterns) if not pcidev.usable or pcidev.driver ~= 'apps.intel.intel_app' then return false end if #patterns == 0 then return true end for _, pattern in ipairs(patterns) do if pcidev.pciaddress:gmatch(pattern)() then return true end end end
module(..., package.seeall) local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local intel10g = require("apps.intel.intel10g") local intel_app = require("apps.intel.intel_app") local basic_apps = require("apps.basic.basic_apps") local main = require("core.main") local PcapReader= require("apps.pcap.pcap").PcapReader local LoadGen = require("apps.intel.loadgen").LoadGen local lib = require("core.lib") local ffi = require("ffi") local C = ffi.C local usage = require("program.packetblaster.README_inc") local long_opts = { duration = "D", help = "h" } function run (args) local opt = {} local duration function opt.D (arg) duration = tonumber(arg) end function opt.h (arg) print(usage) main.exit(1) end if #args < 3 or table.remove(args, 1) ~= 'replay' then opt.h() end args = lib.dogetopt(args, opt, "hD:", long_opts) local filename = table.remove(args, 1) local patterns = args local c = config.new() config.app(c, "pcap", PcapReader, filename) config.app(c, "loop", basic_apps.Repeater) config.app(c, "tee", basic_apps.Tee) config.link(c, "pcap.output -> loop.input") config.link(c, "loop.output -> tee.input") local nics = 0 pci.scan_devices() for _,device in ipairs(pci.devices) do if is_device_suitable(device, patterns) then nics = nics + 1 local name = "nic"..nics config.app(c, name, LoadGen, device.pciaddress) config.link(c, "tee."..tostring(nics).."->"..name..".input") end end engine.busywait = true intel10g.num_descriptors = 32*1024 engine.configure(c) local fn = function () print("Transmissions (last 1 sec):") engine.report_each_app() end local t = timer.new("report", fn, 1e9, 'repeating') timer.activate(t) if duration then engine.main({duration=duration}) else engine.main() end end function is_device_suitable (pcidev, patterns) if not pcidev.usable or pcidev.driver ~= 'apps.intel.intel_app' then return false end if #patterns == 0 then return true end for _, pattern in ipairs(patterns) do if pcidev.pciaddress:gmatch(pattern)() then return true end end end
packetblaster: Fix to avoid starvation
packetblaster: Fix to avoid starvation This commit introduces two changes to avoid the NIC becoming idle: - Use maximum descriptor ring size for 82599 (32K descriptors) - Busywait instead of sleeping between transmissions This makes packetblaster now run at 100% CPU as seen in top. Testing on Interlaken this boosted transmission from 3 Mpps to 12.8 Mpps. (I am not sure why it is less than 14.8 Mpps. Could be that we need to poke a TX register differently to get maximum packet rate.)
Lua
apache-2.0
aperezdc/snabbswitch,kellabyte/snabbswitch,pirate/snabbswitch,heryii/snabb,kbara/snabb,lukego/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabb,dpino/snabbswitch,kbara/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,lukego/snabb,plajjan/snabbswitch,eugeneia/snabb,dpino/snabb,heryii/snabb,lukego/snabbswitch,pirate/snabbswitch,dpino/snabb,snabbnfv-goodies/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,pavel-odintsov/snabbswitch,wingo/snabb,wingo/snabb,justincormack/snabbswitch,heryii/snabb,dpino/snabb,snabbco/snabb,justincormack/snabbswitch,kellabyte/snabbswitch,lukego/snabb,dpino/snabbswitch,aperezdc/snabbswitch,lukego/snabb,alexandergall/snabbswitch,dpino/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,snabbnfv-goodies/snabbswitch,mixflowtech/logsensor,pavel-odintsov/snabbswitch,andywingo/snabbswitch,Igalia/snabb,Igalia/snabb,eugeneia/snabb,dpino/snabbswitch,plajjan/snabbswitch,snabbco/snabb,snabbco/snabb,xdel/snabbswitch,heryii/snabb,mixflowtech/logsensor,Igalia/snabb,lukego/snabbswitch,mixflowtech/logsensor,Igalia/snabb,SnabbCo/snabbswitch,eugeneia/snabb,wingo/snabbswitch,dpino/snabb,snabbnfv-goodies/snabbswitch,eugeneia/snabb,hb9cwp/snabbswitch,wingo/snabb,kbara/snabb,snabbco/snabb,justincormack/snabbswitch,Igalia/snabb,eugeneia/snabb,hb9cwp/snabbswitch,wingo/snabb,justincormack/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,heryii/snabb,andywingo/snabbswitch,xdel/snabbswitch,dwdm/snabbswitch,SnabbCo/snabbswitch,kbara/snabb,lukego/snabbswitch,kellabyte/snabbswitch,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,fhanik/snabbswitch,alexandergall/snabbswitch,dwdm/snabbswitch,Igalia/snabbswitch,wingo/snabb,heryii/snabb,mixflowtech/logsensor,andywingo/snabbswitch,dpino/snabb,snabbco/snabb,wingo/snabb,alexandergall/snabbswitch,pirate/snabbswitch,fhanik/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,lukego/snabb,andywingo/snabbswitch,aperezdc/snabbswitch,snabbco/snabb,kbara/snabb,xdel/snabbswitch,alexandergall/snabbswitch,plajjan/snabbswitch,kbara/snabb,hb9cwp/snabbswitch,Igalia/snabb,eugeneia/snabb,dwdm/snabbswitch,Igalia/snabbswitch,snabbnfv-goodies/snabbswitch,wingo/snabbswitch,Igalia/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabb,snabbco/snabb,wingo/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,wingo/snabbswitch,plajjan/snabbswitch,fhanik/snabbswitch
ad299cacc51d1a517f8e5eb58e5aa1888d4f0955
worldedit_gui/init.lua
worldedit_gui/init.lua
worldedit = worldedit or {} --[[ Example: worldedit.register_gui_function("worldedit_gui_hollow_cylinder", { name = "Make Hollow Cylinder", privs = {worldedit=true}, get_formspec = function(name) return "some formspec here" end, on_select = function(name) print(name .. " clicked the button!") end, }) Use `nil` for the `options` parameter to unregister the function associated with the given identifier. Use `nil` for the `get_formspec` field to denote that the function does not have its own screen. Use `nil` for the `privs` field to denote that no special privileges are required to use the function. If the identifier is already registered to another function, it will be replaced by the new one. The `on_select` function must not call `worldedit.show_page` ]] worldedit.pages = {} --mapping of identifiers to options local identifiers = {} --ordered list of identifiers worldedit.register_gui_function = function(identifier, options) worldedit.pages[identifier] = options table.insert(identifiers, identifier) end --[[ Example: worldedit.register_gui_handler("worldedit_gui_hollow_cylinder", function(name, fields) print(minetest.serialize(fields)) end) ]] worldedit.register_gui_handler = function(identifier, handler) minetest.register_on_player_receive_fields(function(player, formname, fields) --ensure the form is not being exited since this is a duplicate message if fields.quit then return false end local name = player:get_player_name() --ensure the player has permission to perform the action local entry = worldedit.pages[identifier] if entry and minetest.check_player_privs(name, entry.privs or {}) then return handler(name, fields) end return false end) end worldedit.get_formspec_header = function(identifier) local entry = worldedit.pages[identifier] or {} return "button[0,0;2,0.5;worldedit_gui;Back]" .. string.format("label[2,0;WorldEdit GUI > %s]", entry.name or "") end local get_formspec = function(name, identifier) if worldedit.pages[identifier] then return worldedit.pages[identifier].get_formspec(name) end return worldedit.pages["worldedit_gui"].get_formspec(name) --default to showing main page if an unknown page is given end if unified_inventory then local old_func = worldedit.register_gui_function worldedit.register_gui_function = function(identifier, options) old_func(identifier, options) unified_inventory.register_page(identifier, {get_formspec=function(player) return {formspec=options.get_formspec(player:get_player_by_name())} end}) end unified_inventory.register_button("worldedit_gui", { type = "image", image = "inventory_plus_worldedit_gui.png", }) minetest.register_on_player_receive_fields(function(player, formname, fields) if fields.worldedit_gui_exit then unified_inventory.set_inventory_formspec(minetest.get_player_by_name(name), "craft") return true end return false end) worldedit.show_page = function(name, page) minetest.get_player_by_name(name):set_inventory_formspec(get_formspec(name, page)) end elseif inventory_plus then minetest.register_on_joinplayer(function(player) inventory_plus.register_button(player, "worldedit_gui", "WorldEdit") end) --show the form when the button is pressed and hide it when done local gui_player_formspecs = {} minetest.register_on_player_receive_fields(function(player, formname, fields) local name = player:get_player_name() if fields.worldedit_gui then --main page gui_player_formspecs[name] = player:get_inventory_formspec() worldedit.show_page(name, "worldedit_gui") return true elseif fields.worldedit_gui_exit then --return to original page if gui_player_formspecs[name] then inventory_plus.set_inventory_formspec(player, gui_player_formspecs[name]) end return true end return false end) worldedit.show_page = function(name, page) inventory_plus.set_inventory_formspec(minetest.get_player_by_name(name), get_formspec(name, page)) end else worldedit.show_page = function(name, page) minetest.log("error", "WorldEdit GUI cannot be shown, requires unified_inventory or inventory_plus") end minetest.log("error", "WorldEdit GUI is unavailable, requires unified_inventory or inventory_plus") end worldedit.register_gui_function("worldedit_gui", { name = "WorldEdit GUI", get_formspec = function(name) --create a form with all the buttons arranged in a grid --wip: show only buttons that the player has privs for local buttons, x, y, index = {}, 0, 1, 0 local width, height = 3, 0.8 local columns = 5 for i, identifier in pairs(identifiers) do if identifier ~= "worldedit_gui" then local entry = worldedit.pages[identifier] table.insert(buttons, string.format((entry.get_formspec and "button" or "button_exit") .. "[%g,%g;%g,%g;%s;%s]", x, y, width, height, identifier, minetest.formspec_escape(entry.name))) index, x = index + 1, x + width if index == columns then --row is full x, y = 0, y + height index = 0 end end end if index == 0 then --empty row y = y - height end return string.format("size[%g,%g]", math.max(columns * width, 5), math.max(y + 0.5, 3)) .. "button[0,0;2,0.5;worldedit_gui_exit;Back]" .. "label[2,0;WorldEdit GUI]" .. table.concat(buttons) end, }) worldedit.register_gui_handler("worldedit_gui", function(name, fields) for identifier, entry in pairs(worldedit.pages) do --check for WorldEdit GUI main formspec button selection if fields[identifier] and identifier ~= "worldedit_gui" then --ensure player has permission to perform action local has_privs, missing_privs = minetest.check_player_privs(name, entry.privs or {}) if not has_privs then worldedit.player_notify(name, "you are not allowed to use this function (missing privileges: " .. table.concat(missing_privs, ", ") .. ")") return false end if entry.on_select then entry.on_select(name) end if entry.get_formspec then worldedit.show_page(name, identifier) end return true end end return false end) dofile(minetest.get_modpath(minetest.get_current_modname()) .. "/functionality.lua")
worldedit = worldedit or {} --[[ Example: worldedit.register_gui_function("worldedit_gui_hollow_cylinder", { name = "Make Hollow Cylinder", privs = {worldedit=true}, get_formspec = function(name) return "some formspec here" end, on_select = function(name) print(name .. " clicked the button!") end, }) Use `nil` for the `options` parameter to unregister the function associated with the given identifier. Use `nil` for the `get_formspec` field to denote that the function does not have its own screen. Use `nil` for the `privs` field to denote that no special privileges are required to use the function. If the identifier is already registered to another function, it will be replaced by the new one. The `on_select` function must not call `worldedit.show_page` ]] worldedit.pages = {} --mapping of identifiers to options local identifiers = {} --ordered list of identifiers worldedit.register_gui_function = function(identifier, options) worldedit.pages[identifier] = options table.insert(identifiers, identifier) end --[[ Example: worldedit.register_gui_handler("worldedit_gui_hollow_cylinder", function(name, fields) print(minetest.serialize(fields)) end) ]] worldedit.register_gui_handler = function(identifier, handler) minetest.register_on_player_receive_fields(function(player, formname, fields) --ensure the form is not being exited since this is a duplicate message if fields.quit then return false end local name = player:get_player_name() --ensure the player has permission to perform the action local entry = worldedit.pages[identifier] if entry and minetest.check_player_privs(name, entry.privs or {}) then return handler(name, fields) end return false end) end worldedit.get_formspec_header = function(identifier) local entry = worldedit.pages[identifier] or {} return "button[0,0;2,0.5;worldedit_gui;Back]" .. string.format("label[2,0;WorldEdit GUI > %s]", entry.name or "") end local get_formspec = function(name, identifier) if worldedit.pages[identifier] then return worldedit.pages[identifier].get_formspec(name) end return worldedit.pages["worldedit_gui"].get_formspec(name) --default to showing main page if an unknown page is given end if unified_inventory then local old_func = worldedit.register_gui_function worldedit.register_gui_function = function(identifier, options) old_func(identifier, options) unified_inventory.register_page(identifier, {get_formspec=function(player) return {formspec=options.get_formspec(player:get_player_name())} end}) end unified_inventory.register_button("worldedit_gui", { type = "image", image = "inventory_plus_worldedit_gui.png", }) minetest.register_on_player_receive_fields(function(player, formname, fields) local name = player:get_player_name() if fields.worldedit_gui_exit then unified_inventory.set_inventory_formspec(minetest.get_player_by_name(name), "craft") return true end return false end) worldedit.show_page = function(name, page) minetest.get_player_by_name(name):set_inventory_formspec(get_formspec(name, page)) end elseif inventory_plus then minetest.register_on_joinplayer(function(player) inventory_plus.register_button(player, "worldedit_gui", "WorldEdit") end) --show the form when the button is pressed and hide it when done local gui_player_formspecs = {} minetest.register_on_player_receive_fields(function(player, formname, fields) local name = player:get_player_name() if fields.worldedit_gui then --main page gui_player_formspecs[name] = player:get_inventory_formspec() worldedit.show_page(name, "worldedit_gui") return true elseif fields.worldedit_gui_exit then --return to original page if gui_player_formspecs[name] then inventory_plus.set_inventory_formspec(player, gui_player_formspecs[name]) end return true end return false end) worldedit.show_page = function(name, page) inventory_plus.set_inventory_formspec(minetest.get_player_by_name(name), get_formspec(name, page)) end else worldedit.show_page = function(name, page) minetest.log("error", "WorldEdit GUI cannot be shown, requires unified_inventory or inventory_plus") end minetest.log("error", "WorldEdit GUI is unavailable, requires unified_inventory or inventory_plus") end worldedit.register_gui_function("worldedit_gui", { name = "WorldEdit GUI", get_formspec = function(name) --create a form with all the buttons arranged in a grid --wip: show only buttons that the player has privs for local buttons, x, y, index = {}, 0, 1, 0 local width, height = 3, 0.8 local columns = 5 for i, identifier in pairs(identifiers) do if identifier ~= "worldedit_gui" then local entry = worldedit.pages[identifier] table.insert(buttons, string.format((entry.get_formspec and "button" or "button_exit") .. "[%g,%g;%g,%g;%s;%s]", x, y, width, height, identifier, minetest.formspec_escape(entry.name))) index, x = index + 1, x + width if index == columns then --row is full x, y = 0, y + height index = 0 end end end if index == 0 then --empty row y = y - height end return string.format("size[%g,%g]", math.max(columns * width, 5), math.max(y + 0.5, 3)) .. "button[0,0;2,0.5;worldedit_gui_exit;Back]" .. "label[2,0;WorldEdit GUI]" .. table.concat(buttons) end, }) worldedit.register_gui_handler("worldedit_gui", function(name, fields) for identifier, entry in pairs(worldedit.pages) do --check for WorldEdit GUI main formspec button selection if fields[identifier] and identifier ~= "worldedit_gui" then --ensure player has permission to perform action local has_privs, missing_privs = minetest.check_player_privs(name, entry.privs or {}) if not has_privs then worldedit.player_notify(name, "you are not allowed to use this function (missing privileges: " .. table.concat(missing_privs, ", ") .. ")") return false end if entry.on_select then entry.on_select(name) end if entry.get_formspec then worldedit.show_page(name, identifier) end return true end end return false end) dofile(minetest.get_modpath(minetest.get_current_modname()) .. "/functionality.lua")
Fix crashes in GUI button.
Fix crashes in GUI button.
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
bb3258ab5d2ea12a9c711a93edf1aa316899b8ea
src/flyin.lua
src/flyin.lua
local Gamestate = require 'vendor/gamestate' local window = require 'window' local fonts = require 'fonts' local TunnelParticles = require "tunnelparticles" local flyin = Gamestate.new() local sound = require 'vendor/TEsound' local Timer = require 'vendor/timer' local Character = require 'character' function flyin:init( ) TunnelParticles:init() end function flyin:enter( prev ) self.flying = {} self.characterorder = {} for i,c in pairs(Character.characters) do if c.name ~= Character.name then table.insert(self.characterorder, c.name) end end self.characterorder = table.shuffle( self.characterorder, 5 ) table.insert( self.characterorder, Character.name ) local time = 0 for _,name in pairs( self.characterorder ) do Timer.add(time, function() table.insert( self.flying, { n = name, x = window.width / 2, y = window.height / 2, t = math.random( ( math.pi * 2 ) * 10000 ) / 10000, r = n == Character.name and 0 or ( math.random( 4 ) - 1 ) * ( math.pi / 2 ), s = 0.1, show = true }) end) time = time + 0.4 end end function flyin:draw() TunnelParticles.draw() love.graphics.circle( 'fill', window.width / 2, window.height / 2, 30 ) --draw in reverse order, so the older ones get drawn on top of the newer ones for i = #flyin.flying, 1, -1 do local v = flyin.flying[i] if v.show then love.graphics.setColor( 255, 255, 255, 255 ) Character.characters[v.n].animations.flyin:draw( Character.characters[v.n].sheets.base, v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 ) -- black mask while coming out of 'tunnel' if v.s <= 1 then love.graphics.setColor( 0, 0, 0, 255 * ( 1 - v.s ) ) Character.characters[v.n].animations.flyin:draw( Character.characters[v.n].sheets.base, v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 ) end end end end function flyin:keypressed(button) Timer.clear() Gamestate.switch( 'overworld' ) end function flyin:update(dt) Timer.update(dt) TunnelParticles.update(dt) for k,v in pairs(flyin.flying) do if v.n ~= Character.name then v.x = v.x + ( math.cos( v.t ) * dt * v.s * 90 ) v.y = v.y + ( math.sin( v.t ) * dt * v.s * 90 ) end v.s = v.s + dt * 4 v.r = v.r + dt * 5 if v.s >= 6 then v.show = false end end if not flyin.flying[ #flyin.flying ].show then Timer.clear() Gamestate.switch( 'overworld' ) end end return flyin
local Gamestate = require 'vendor/gamestate' local window = require 'window' local fonts = require 'fonts' local TunnelParticles = require "tunnelparticles" local flyin = Gamestate.new() local sound = require 'vendor/TEsound' local Timer = require 'vendor/timer' local Character = require 'character' function flyin:init( ) TunnelParticles:init() end function flyin:enter( prev ) self.flying = {} self.characterorder = {} for i,c in pairs(Character.characters) do if c.name ~= Character.name then table.insert(self.characterorder, c.name) end end self.characterorder = table.shuffle( self.characterorder, 5 ) table.insert( self.characterorder, Character.name ) local time = 0 for _,name in pairs( self.characterorder ) do Timer.add(time, function() table.insert( self.flying, { n = name, c = name == Character.name and Character.costume or 'base', x = window.width / 2, y = window.height / 2, t = math.random( ( math.pi * 2 ) * 10000 ) / 10000, r = n == Character.name and 0 or ( math.random( 4 ) - 1 ) * ( math.pi / 2 ), s = 0.1, show = true }) end) time = time + 0.4 end end function flyin:draw() TunnelParticles.draw() love.graphics.circle( 'fill', window.width / 2, window.height / 2, 30 ) --draw in reverse order, so the older ones get drawn on top of the newer ones for i = #flyin.flying, 1, -1 do local v = flyin.flying[i] if v.show then love.graphics.setColor( 255, 255, 255, 255 ) Character.characters[v.n].animations.flyin:draw( Character.characters[v.n].sheets[v.c], v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 ) -- black mask while coming out of 'tunnel' if v.s <= 1 then love.graphics.setColor( 0, 0, 0, 255 * ( 1 - v.s ) ) Character.characters[v.n].animations.flyin:draw( Character.characters[v.n].sheets[v.c], v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 ) end end end end function flyin:keypressed(button) Timer.clear() Gamestate.switch( 'overworld' ) end function flyin:update(dt) Timer.update(dt) TunnelParticles.update(dt) for k,v in pairs(flyin.flying) do if v.n ~= Character.name then v.x = v.x + ( math.cos( v.t ) * dt * v.s * 90 ) v.y = v.y + ( math.sin( v.t ) * dt * v.s * 90 ) end v.s = v.s + dt * 4 v.r = v.r + dt * 5 if v.s >= 6 then v.show = false end end if not flyin.flying[ #flyin.flying ].show then Timer.clear() Gamestate.switch( 'overworld' ) end end return flyin
Minor fix for flyin
Minor fix for flyin
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
3debb1f02b7bdc41898eb2ec5bb00de65283f09e
hammerspoon/init.lua
hammerspoon/init.lua
--- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") local v60hyper = {} local globalHyper = {"ctrl", "alt"} local primaryScreen = hs.screen.primaryScreen() local primaryScreenMenuBarOffset = primaryScreen:frame().y local screenDimensionFigurer = {} screenDimensionFigurer.__index = screenDimensionFigurer function screenDimensionFigurer.new(win) local self = setmetatable({}, screenDimensionFigurer) self.margin = 10 self.win = win self.frame = win:frame() local screen = win:screen() self.max = screen:frame() self.frame.x = self.margin -- self.frame.y = self.margin + screenFrameHeightDiff(win) self.frame.y = self.margin + primaryScreenMenuBarOffset self.frame.w = self.max.w - (2 * self.margin) self.frame.h = self.max.h - (2 * self.margin) - primaryScreenMenuBarOffset return self end hs.hotkey.bind({"alt", "ctrl"}, "x", function() local sdf = screenDimensionFigurer.new(hs.window.focusedWindow()) sdf.frame.h = sdf.max.h / 2 sdf.win:setFrame(sdf.frame) end) function stackWindows(win) -- find all windows in the app of the frontmost window -- make all the windows in the app the same size local f = win:frame() local app = win:application() local windows = app:allWindows() for i, window in ipairs(windows) do window:setFrame(f) end end hs.hotkey.bind(v60hyper, "f17", function() local win = hs.window.focusedWindow() stackWindows(win) end) maxFrame = { x = 0, y = primaryScreenMenuBarOffset, h = primaryScreen:frame().h, w = primaryScreen:frame().w, } -- on a 24x24 grid, these are {x, y, w, h} lowerRight = { 14.0, 10.0, 10.0, 14.0 } upperRight = { 14.0, 0.0, 10.0, 10.0 } halfLeft = { 0.0, 0.0, 14.0, 24.0 } local appPositions = { Atom = halfLeft, ['Google Chrome'] = halfLeft, ['IntelliJ IDEA'] = halfLeft, iTerm2 = upperRight, -- Messages = lowerRight, PyCharm = halfLeft, Slack = lowerRight, } hs.hotkey.bind(globalHyper, "k", function() -- print("setting up default window positions") -- print(appPositions.PyCharm.x) for appName, position in pairs(appPositions) do -- print("for ", appName) thisApp = hs.application.get(appName) if thisApp == nil then print("skipping nil app: ", appName) else for title, appWindow in pairs(thisApp:allWindows()) do print("the position for ", title, " is h/w/x/y", position.h, position.w, position.x, position.y) hs.grid.set(appWindow, position) end end end end) -- the 'pad=' key is under 'n' on layer 2 hs.hotkey.bind(v60hyper, "pad=", function() local win = hs.window.focusedWindow() local scr = win:screen() local nextScreen = scr:next() win:moveToScreen(scr:next()) if nextScreen:fullFrame().h * nextScreen:fullFrame().w < scr:fullFrame().h * scr:fullFrame().w then print(string.format("next screen area: %s", nextScreen:fullFrame().h * nextScreen:fullFrame().w)) print(string.format("this screen area: %s", scr:fullFrame().h * scr:fullFrame().w)) -- next screen is smaller; make it MiroWindowsManager's idea of full screen. spoon.MiroWindowsManager:_nextFullScreenStep() end end) myLog = hs.logger.new('pk_config', 'debug') hs.hotkey.bind(globalHyper, 'm', function() local currentMic = hs.audiodevice.defaultInputDevice() currentMic:setMuted(not currentMic:muted()) local verb = currentMic:muted() and " " or " un-" local alertString = currentMic:name() .. verb .. "muted" hs.alert.show(alertString) end)
--- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") local v60hyper = {} local globalHyper = {"ctrl", "alt"} local primaryScreen = hs.screen.primaryScreen() local primaryScreenMenuBarOffset = primaryScreen:frame().y local screenDimensionFigurer = {} screenDimensionFigurer.__index = screenDimensionFigurer function screenDimensionFigurer.new(win) local self = setmetatable({}, screenDimensionFigurer) self.margin = 10 self.win = win self.frame = win:frame() local screen = win:screen() self.max = screen:frame() self.menuBarOffset = win:screen():frame().y self.frame.x = self.margin self.frame.y = self.margin + self.menuBarOffset self.frame.w = self.max.w - (2 * self.margin) self.frame.h = self.max.h - (2 * self.margin) - self.menuBarOffset return self end hs.hotkey.bind({"alt", "ctrl"}, "x", function() local sdf = screenDimensionFigurer.new(hs.window.focusedWindow()) sdf.frame.h = sdf.max.h / 2 sdf.win:setFrame(sdf.frame) end) function stackWindows(win) -- find all windows in the app of the frontmost window -- make all the windows in the app the same size local f = win:frame() local app = win:application() local windows = app:allWindows() for i, window in ipairs(windows) do window:setFrame(f) end end hs.hotkey.bind(v60hyper, "f17", function() local win = hs.window.focusedWindow() stackWindows(win) end) maxFrame = { x = 0, y = primaryScreenMenuBarOffset, h = primaryScreen:frame().h, w = primaryScreen:frame().w, } -- on a 24x24 grid, these are {x, y, w, h} lowerRight = { 14.0, 10.0, 10.0, 14.0 } upperRight = { 14.0, 0.0, 10.0, 10.0 } halfLeft = { 0.0, 0.0, 14.0, 24.0 } local appPositions = { Atom = halfLeft, ['Google Chrome'] = halfLeft, ['IntelliJ IDEA'] = halfLeft, iTerm2 = upperRight, -- Messages = lowerRight, PyCharm = halfLeft, Slack = lowerRight, } hs.hotkey.bind(globalHyper, "k", function() -- print("setting up default window positions") -- print(appPositions.PyCharm.x) for appName, position in pairs(appPositions) do -- print("for ", appName) thisApp = hs.application.get(appName) if thisApp == nil then print("skipping nil app: ", appName) else for title, appWindow in pairs(thisApp:allWindows()) do print("the position for ", title, " is h/w/x/y", position.h, position.w, position.x, position.y) hs.grid.set(appWindow, position) end end end end) -- the 'pad=' key is under 'n' on layer 2 hs.hotkey.bind(v60hyper, "pad=", function() local win = hs.window.focusedWindow() local scr = win:screen() local nextScreen = scr:next() win:moveToScreen(scr:next()) if nextScreen:fullFrame().h * nextScreen:fullFrame().w < scr:fullFrame().h * scr:fullFrame().w then print(string.format("next screen area: %s", nextScreen:fullFrame().h * nextScreen:fullFrame().w)) print(string.format("this screen area: %s", scr:fullFrame().h * scr:fullFrame().w)) -- next screen is smaller; make it MiroWindowsManager's idea of full screen. spoon.MiroWindowsManager:_nextFullScreenStep() end end) myLog = hs.logger.new('pk_config', 'debug') hs.hotkey.bind(globalHyper, 'm', function() local currentMic = hs.audiodevice.defaultInputDevice() currentMic:setMuted(not currentMic:muted()) local verb = currentMic:muted() and " " or " un-" local alertString = currentMic:name() .. verb .. "muted" hs.alert.show(alertString) end)
fix previous
fix previous
Lua
mit
paul-krohn/configs
afd430366a6cdb38b23ec5bfddacd4e99e17d65e
examples/lua/memleak.lua
examples/lua/memleak.lua
--[[ Copyright 2016 GitHub, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local bpf_source = [[ #include <uapi/linux/ptrace.h> struct alloc_info_t { u64 size; u64 timestamp_ns; int stack_id; }; BPF_HASH(sizes, u64); BPF_HASH(allocs, u64, struct alloc_info_t); BPF_STACK_TRACE(stack_traces, 10240) int alloc_enter(struct pt_regs *ctx, size_t size) { SIZE_FILTER if (SAMPLE_EVERY_N > 1) { u64 ts = bpf_ktime_get_ns(); if (ts % SAMPLE_EVERY_N != 0) return 0; } u64 pid = bpf_get_current_pid_tgid(); u64 size64 = size; sizes.update(&pid, &size64); if (SHOULD_PRINT) bpf_trace_printk("alloc entered, size = %u\n", size); return 0; } int alloc_exit(struct pt_regs *ctx) { u64 address = ctx->ax; u64 pid = bpf_get_current_pid_tgid(); u64* size64 = sizes.lookup(&pid); struct alloc_info_t info = {0}; if (size64 == 0) return 0; // missed alloc entry info.size = *size64; sizes.delete(&pid); info.timestamp_ns = bpf_ktime_get_ns(); info.stack_id = stack_traces.get_stackid(ctx, STACK_FLAGS); allocs.update(&address, &info); if (SHOULD_PRINT) { bpf_trace_printk("alloc exited, size = %lu, result = %lx\n", info.size, address); } return 0; } int free_enter(struct pt_regs *ctx, void *address) { u64 addr = (u64)address; struct alloc_info_t *info = allocs.lookup(&addr); if (info == 0) return 0; allocs.delete(&addr); if (SHOULD_PRINT) { bpf_trace_printk("free entered, address = %lx, size = %lu\n", address, info->size); } return 0; } ]] return function(BPF, utils) local parser = utils.argparse("memleak", "Catch memory leaks") parser:flag("-t --trace") parser:flag("-a --show-allocs") parser:option("-p --pid"):convert(tonumber) parser:option("-i --interval", "", 5):convert(tonumber) parser:option("-o --older", "", 500):convert(tonumber) parser:option("-s --sample-rate", "", 1):convert(tonumber) parser:option("-z --min-size", ""):convert(tonumber) parser:option("-Z --max-size", ""):convert(tonumber) parser:option("-T --top", "", 10):convert(tonumber) local args = parser:parse() local size_filter = "" if args.min_size and args.max_size then size_filter = "if (size < %d || size > %d) return 0;" % {args.min_size, args.max_size} elseif args.min_size then size_filter = "if (size < %d) return 0;" % args.min_size elseif args.max_size then size_filter = "if (size > %d) return 0;" % args.max_size end local stack_flags = "BPF_F_REUSE_STACKID" if args.pid then stack_flags = stack_flags .. "|BPF_F_USER_STACK" end local text = bpf_source text = text:gsub("SIZE_FILTER", size_filter) text = text:gsub("STACK_FLAGS", stack_flags) text = text:gsub("SHOULD_PRINT", args.trace and "1" or "0") text = text:gsub("SAMPLE_EVERY_N", tostring(args.sample_rate)) local bpf = BPF:new{text=text, debug=0} local syms = nil local min_age_ns = args.older * 1e6 if args.pid then print("Attaching to malloc and free in pid %d, Ctrl+C to quit." % args.pid) bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_enter", pid=args.pid} bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_exit", pid=args.pid, retprobe=true} bpf:attach_uprobe{name="c", sym="free", fn_name="free_enter", pid=args.pid} else print("Attaching to kmalloc and kfree, Ctrl+C to quit.") bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_enter"} bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_exit", retprobe=true} -- TODO bpf:attach_kprobe{event="kfree", fn_name="free_enter"} end local syms = args.pid and utils.sym.ProcSymbols:new(args.pid) or utils.sym.KSymbols:new() local allocs = bpf:get_table("allocs") local stack_traces = bpf:get_table("stack_traces") local function resolve(addr) local sym = syms:lookup(addr) if args.pid == nil then sym = sym .. " [kernel]" end return string.format("%s (%x)", sym, addr) end local function print_outstanding() local alloc_info = {} local now = utils.posix.time_ns() print("[%s] Top %d stacks with outstanding allocations:" % {os.date("%H:%M:%S"), args.top}) for address, info in allocs:items() do if now - min_age_ns >= tonumber(info.timestamp_ns) then local stack_id = tonumber(info.stack_id) if stack_id >= 0 then if alloc_info[stack_id] then local s = alloc_info[stack_id] s.count = s.count + 1 s.size = s.size + tonumber(info.size) else local stack = stack_traces:get(stack_id, resolve) alloc_info[stack_id] = { stack=stack, count=1, size=tonumber(info.size) } end end if args.show_allocs then print("\taddr = %x size = %s" % {tonumber(address), tonumber(info.size)}) end end end local top = table.values(alloc_info) table.sort(top, function(a, b) return a.size > b.size end) for n, alloc in ipairs(top) do print("\t%d bytes in %d allocations from stack\n\t\t%s" % {alloc.size, alloc.count, table.concat(alloc.stack, "\n\t\t")}) if n == args.top then break end end end if args.trace then local pipe = bpf:pipe() while true do print(pipe:trace_fields()) end else while true do utils.posix.sleep(args.interval) syms:refresh() print_outstanding() end end end
--[[ Copyright 2016 GitHub, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local bpf_source = [[ #include <uapi/linux/ptrace.h> struct alloc_info_t { u64 size; u64 timestamp_ns; int stack_id; }; BPF_HASH(sizes, u64); BPF_HASH(allocs, u64, struct alloc_info_t); BPF_STACK_TRACE(stack_traces, 10240) int alloc_enter(struct pt_regs *ctx, size_t size) { SIZE_FILTER if (SAMPLE_EVERY_N > 1) { u64 ts = bpf_ktime_get_ns(); if (ts % SAMPLE_EVERY_N != 0) return 0; } u64 pid = bpf_get_current_pid_tgid(); u64 size64 = size; sizes.update(&pid, &size64); if (SHOULD_PRINT) bpf_trace_printk("alloc entered, size = %u\n", size); return 0; } int alloc_exit(struct pt_regs *ctx) { u64 address = ctx->ax; u64 pid = bpf_get_current_pid_tgid(); u64* size64 = sizes.lookup(&pid); struct alloc_info_t info = {0}; if (size64 == 0) return 0; // missed alloc entry info.size = *size64; sizes.delete(&pid); info.timestamp_ns = bpf_ktime_get_ns(); info.stack_id = stack_traces.get_stackid(ctx, STACK_FLAGS); allocs.update(&address, &info); if (SHOULD_PRINT) { bpf_trace_printk("alloc exited, size = %lu, result = %lx\n", info.size, address); } return 0; } int free_enter(struct pt_regs *ctx, void *address) { u64 addr = (u64)address; struct alloc_info_t *info = allocs.lookup(&addr); if (info == 0) return 0; allocs.delete(&addr); if (SHOULD_PRINT) { bpf_trace_printk("free entered, address = %lx, size = %lu\n", address, info->size); } return 0; } ]] return function(BPF, utils) local parser = utils.argparse("memleak", "Catch memory leaks") parser:flag("-t --trace") parser:flag("-a --show-allocs") parser:option("-p --pid"):convert(tonumber) parser:option("-i --interval", "", 5):convert(tonumber) parser:option("-o --older", "", 500):convert(tonumber) parser:option("-s --sample-rate", "", 1):convert(tonumber) parser:option("-z --min-size", ""):convert(tonumber) parser:option("-Z --max-size", ""):convert(tonumber) parser:option("-T --top", "", 10):convert(tonumber) local args = parser:parse() local size_filter = "" if args.min_size and args.max_size then size_filter = "if (size < %d || size > %d) return 0;" % {args.min_size, args.max_size} elseif args.min_size then size_filter = "if (size < %d) return 0;" % args.min_size elseif args.max_size then size_filter = "if (size > %d) return 0;" % args.max_size end local stack_flags = "BPF_F_REUSE_STACKID" if args.pid then stack_flags = stack_flags .. "|BPF_F_USER_STACK" end local text = bpf_source text = text:gsub("SIZE_FILTER", size_filter) text = text:gsub("STACK_FLAGS", stack_flags) text = text:gsub("SHOULD_PRINT", args.trace and "1" or "0") text = text:gsub("SAMPLE_EVERY_N", tostring(args.sample_rate)) local bpf = BPF:new{text=text, debug=0} local syms = nil local min_age_ns = args.older * 1e6 if args.pid then print("Attaching to malloc and free in pid %d, Ctrl+C to quit." % args.pid) bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_enter", pid=args.pid} bpf:attach_uprobe{name="c", sym="malloc", fn_name="alloc_exit", pid=args.pid, retprobe=true} bpf:attach_uprobe{name="c", sym="free", fn_name="free_enter", pid=args.pid} else print("Attaching to kmalloc and kfree, Ctrl+C to quit.") bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_enter"} bpf:attach_kprobe{event="__kmalloc", fn_name="alloc_exit", retprobe=true} -- TODO bpf:attach_kprobe{event="kfree", fn_name="free_enter"} end local syms = args.pid and utils.sym.ProcSymbols:new(args.pid) or utils.sym.KSymbols:new() local allocs = bpf:get_table("allocs") local stack_traces = bpf:get_table("stack_traces") local function resolve(addr) local sym = syms:lookup(addr) if args.pid == nil then sym = sym .. " [kernel]" end return string.format("%s (%x)", sym, addr) end local function print_outstanding() local alloc_info = {} local now = utils.posix.time_ns() print("[%s] Top %d stacks with outstanding allocations:" % {os.date("%H:%M:%S"), args.top}) for address, info in allocs:items() do if now - min_age_ns >= tonumber(info.timestamp_ns) then local stack_id = tonumber(info.stack_id) if stack_id >= 0 then if alloc_info[stack_id] then local s = alloc_info[stack_id] s.count = s.count + 1 s.size = s.size + tonumber(info.size) else local stack = stack_traces:get(stack_id, resolve) alloc_info[stack_id] = { stack=stack, count=1, size=tonumber(info.size) } end end if args.show_allocs then print("\taddr = %x size = %s" % {tonumber(address), tonumber(info.size)}) end end end local top = table.values(alloc_info) table.sort(top, function(a, b) return a.size > b.size end) for n, alloc in ipairs(top) do print("\t%d bytes in %d allocations from stack\n\t\t%s" % {alloc.size, alloc.count, table.concat(alloc.stack, "\n\t\t")}) if n == args.top then break end end end if args.trace then local pipe = bpf:pipe() while true do print(pipe:trace_fields()) end else while true do utils.posix.sleep(args.interval) syms:refresh() print_outstanding() end end end
memleak.lua: Fix indentation
memleak.lua: Fix indentation
Lua
apache-2.0
shodoco/bcc,tuxology/bcc,iovisor/bcc,shodoco/bcc,brendangregg/bcc,mcaleavya/bcc,mkacik/bcc,shodoco/bcc,tuxology/bcc,zaafar/bcc,zaafar/bcc,zaafar/bcc,romain-intel/bcc,zaafar/bcc,shodoco/bcc,mkacik/bcc,romain-intel/bcc,brendangregg/bcc,tuxology/bcc,iovisor/bcc,romain-intel/bcc,mkacik/bcc,mcaleavya/bcc,iovisor/bcc,shodoco/bcc,mkacik/bcc,mkacik/bcc,mcaleavya/bcc,tuxology/bcc,tuxology/bcc,romain-intel/bcc,romain-intel/bcc,mcaleavya/bcc,iovisor/bcc,iovisor/bcc,brendangregg/bcc,zaafar/bcc,mcaleavya/bcc,brendangregg/bcc,brendangregg/bcc
e65a0815dc4411dc777f5cfc930c9c28b89a2022
ffi/framebuffer_SDL.lua
ffi/framebuffer_SDL.lua
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h) fb.real_bb = BB.new(SDL.screen.w, SDL.screen.h, SDL.screen.pitch, SDL.screen.pixels, 32, true):invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if x1 == nil then x1 = 0 end if y1 == nil then y1 = 0 end if w == nil then w = SDL.screen.w - x1 end if h == nil then h = SDL.screen.h - y1 end if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end self.real_bb:blitFrom(self.bb, x1, y1, x1, y1, w, h) SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() -- for now, we do nothing when in emulator mode end return fb
local ffi = require("ffi") local bit = require("bit") -- load common SDL input/video library local SDL = require("ffi/SDL") local BB = require("ffi/blitbuffer") local fb = {} function fb.open() SDL.open() -- we present this buffer to the outside fb.bb = BB.new(SDL.screen.w, SDL.screen.h) fb.real_bb = BB.new(SDL.screen.w, SDL.screen.h, BB.TYPE_BBRGB32, SDL.screen.pixels, SDL.screen.pitch) fb.real_bb:invert() fb:refresh() return fb end function fb:getSize() return self.bb.w, self.bb.h end function fb:getPitch() return self.bb.pitch end function fb:setOrientation(mode) if mode == 1 or mode == 3 then -- TODO: landscape setting else -- TODO: flip back to portrait end end function fb:getOrientation() if SDL.screen.w > SDL.screen.h then return 1 else return 0 end end function fb:refresh(refreshtype, waveform_mode, x1, y1, w, h) if x1 == nil then x1 = 0 end if y1 == nil then y1 = 0 end -- adapt to possible rotation changes self.real_bb:setRotation(self.bb:getRotation()) if SDL.SDL.SDL_LockSurface(SDL.screen) < 0 then error("Locking screen surface") end self.real_bb:blitFrom(self.bb, x1, y1, x1, y1, w, h) SDL.SDL.SDL_UnlockSurface(SDL.screen) SDL.SDL.SDL_Flip(SDL.screen) end function fb:close() -- for now, we do nothing when in emulator mode end return fb
Adaptions and bugfixes for SDL framebuffer emulation
Adaptions and bugfixes for SDL framebuffer emulation Now properly does rotation.
Lua
agpl-3.0
houqp/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,koreader/koreader-base,koreader/koreader-base,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,houqp/koreader-base
a0508e145ebe78745e892b8b4fb43c787435c11c
games/starDash/unit.lua
games/starDash/unit.lua
-- Unit: A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.stardash.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- @classmod Unit local Unit = class(GameObject) -- initializes a Unit with basic logic as provided by the Creer code generator function Unit:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- Whether or not this Unit has performed its action this turn. self.acted = false --- The x value this unit is dashing to. self.dashX = 0 --- The y value this unit is dashing to. self.dashY = 0 --- The remaining health of a unit. self.energy = 0 --- The amount of Generium ore carried by this unit. (0 to job carry capacity - other carried items). self.genarium = 0 --- Tracks wheither or not the ship is dashing. self.isDashing = false --- The Job this Unit has. self.job = nil --- The amount of Legendarium ore carried by this unit. (0 to job carry capacity - other carried items). self.legendarium = 0 --- The distance this unit can still move. self.moves = 0 --- The amount of Mythicite carried by this unit. (0 to job carry capacity - other carried items). self.mythicite = 0 --- The Player that owns and can control this Unit. self.owner = nil --- The martyr ship that is currently shielding this ship if any. self.protector = nil --- The amount of Rarium carried by this unit. (0 to job carry capacity - other carried items). self.rarium = 0 --- The sheild that a martyr ship has. self.shield = 0 --- The x value this unit is on. self.x = 0 --- The y value this unit is on. self.y = 0 --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- Attacks the specified unit. -- @tparam Unit enemy The Unit being attacked. -- @treturn bool True if successfully attacked, false otherwise. function Unit:attack(enemy) return not not (self:_runOnServer("attack", { enemy = enemy, })) end --- Causes the unit to dash towards the designated destination. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:dash(x, y) return not not (self:_runOnServer("dash", { x = x, y = y, })) end --- allows a miner to mine a asteroid -- @tparam Body body The object to be mined. -- @treturn bool True if successfully acted, false otherwise. function Unit:mine(body) return not not (self:_runOnServer("mine", { body = body, })) end --- Moves this Unit from its current location to the new location specified. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:move(x, y) return not not (self:_runOnServer("move", { x = x, y = y, })) end --- tells you if your ship can be at that location. -- @tparam number x The x position of the location you wish to check. -- @tparam number y The y position of the location you wish to check. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:safe(x, y) return not not (self:_runOnServer("safe", { x = x, y = y, })) end --- Attacks the specified projectile. -- @tparam Projectile missile The projectile being shot down. -- @treturn bool True if successfully attacked, false otherwise. function Unit:shootDown(missile) return not not (self:_runOnServer("shootDown", { missile = missile, })) end --- Grab materials from a friendly unit. Doesn't use a action. -- @tparam Unit unit The unit you are grabbing the resources from. -- @tparam number amount The amount of materials to you with to grab. Amounts <= 0 will pick up all the materials that the unit can. -- @tparam string material The material the unit will pick up. 'resource1', 'resource2', or 'resource3'. -- @treturn bool True if successfully taken, false otherwise. function Unit:transfer(unit, amount, material) return not not (self:_runOnServer("transfer", { unit = unit, amount = amount, material = material, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Unit:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Unit
-- Unit: A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.stardash.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- @classmod Unit local Unit = class(GameObject) -- initializes a Unit with basic logic as provided by the Creer code generator function Unit:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- Whether or not this Unit has performed its action this turn. self.acted = false --- The x value this unit is dashing to. self.dashX = 0 --- The y value this unit is dashing to. self.dashY = 0 --- The remaining health of a unit. self.energy = 0 --- The amount of Genarium ore carried by this unit. (0 to job carry capacity - other carried items). self.genarium = 0 --- Tracks wheither or not the ship is dashing. self.isDashing = false --- The Job this Unit has. self.job = nil --- The amount of Legendarium ore carried by this unit. (0 to job carry capacity - other carried items). self.legendarium = 0 --- The distance this unit can still move. self.moves = 0 --- The amount of Mythicite carried by this unit. (0 to job carry capacity - other carried items). self.mythicite = 0 --- The Player that owns and can control this Unit. self.owner = nil --- The martyr ship that is currently shielding this ship if any. self.protector = nil --- The amount of Rarium carried by this unit. (0 to job carry capacity - other carried items). self.rarium = 0 --- The sheild that a martyr ship has. self.shield = 0 --- The x value this unit is on. self.x = 0 --- The y value this unit is on. self.y = 0 --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- Attacks the specified unit. -- @tparam Unit enemy The Unit being attacked. -- @treturn bool True if successfully attacked, false otherwise. function Unit:attack(enemy) return not not (self:_runOnServer("attack", { enemy = enemy, })) end --- Causes the unit to dash towards the designated destination. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:dash(x, y) return not not (self:_runOnServer("dash", { x = x, y = y, })) end --- tells you if your ship dash to that location. -- @tparam number x The x position of the location you wish to arrive. -- @tparam number y The y position of the location you wish to arrive. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:dashable(x, y) return not not (self:_runOnServer("dashable", { x = x, y = y, })) end --- allows a miner to mine a asteroid -- @tparam Body body The object to be mined. -- @treturn bool True if successfully acted, false otherwise. function Unit:mine(body) return not not (self:_runOnServer("mine", { body = body, })) end --- Moves this Unit from its current location to the new location specified. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:move(x, y) return not not (self:_runOnServer("move", { x = x, y = y, })) end --- tells you if your ship can move to that location. -- @tparam number x The x position of the location you wish to arrive. -- @tparam number y The y position of the location you wish to arrive. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:safe(x, y) return not not (self:_runOnServer("safe", { x = x, y = y, })) end --- Attacks the specified projectile. -- @tparam Projectile missile The projectile being shot down. -- @treturn bool True if successfully attacked, false otherwise. function Unit:shootDown(missile) return not not (self:_runOnServer("shootDown", { missile = missile, })) end --- Grab materials from a friendly unit. Doesn't use a action. -- @tparam Unit unit The unit you are grabbing the resources from. -- @tparam number amount The amount of materials to you with to grab. Amounts <= 0 will pick up all the materials that the unit can. -- @tparam string material The material the unit will pick up. 'resource1', 'resource2', or 'resource3'. -- @treturn bool True if successfully taken, false otherwise. function Unit:transfer(unit, amount, material) return not not (self:_runOnServer("transfer", { unit = unit, amount = amount, material = material, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Unit:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Unit
Added additional functions that tell the user if it is possible to move or dash to coordinates. Fixed typo.
Added additional functions that tell the user if it is possible to move or dash to coordinates. Fixed typo.
Lua
mit
siggame/Joueur.lua,siggame/Joueur.lua
da19df084b0edf4cdffb1270dead89f4b2c6463e
onmt/data/Vocabulary.lua
onmt/data/Vocabulary.lua
local path = require('pl.path') --[[ Vocabulary management utility functions. ]] local Vocabulary = torch.class("Vocabulary") local function countFeatures(filename) local reader = onmt.utils.FileReader.new(filename) local _, _, numFeatures = onmt.utils.Features.extract(reader:next()) reader:close() return numFeatures end function Vocabulary.make(filename, validFunc) local wordVocab = onmt.utils.Dict.new({onmt.Constants.PAD_WORD, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD}) local featuresVocabs = {} local reader = onmt.utils.FileReader.new(filename) local lineId = 0 while true do local sent = reader:next() if sent == nil then break end lineId = lineId + 1 if validFunc(sent) then local words, features, numFeatures local _, err = pcall(function () words, features, numFeatures = onmt.utils.Features.extract(sent) end) if err then error(err .. ' (' .. filename .. ':' .. lineId .. ')') end if #featuresVocabs == 0 and numFeatures > 0 then for j = 1, numFeatures do featuresVocabs[j] = onmt.utils.Dict.new({onmt.Constants.PAD_WORD, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD}) end else assert(#featuresVocabs == numFeatures, 'all sentences must have the same numbers of additional features (' .. filename .. ':' .. lineId .. ')') end for i = 1, #words do wordVocab:add(words[i]) for j = 1, numFeatures do featuresVocabs[j]:add(features[j][i]) end end end end reader:close() return wordVocab, featuresVocabs end function Vocabulary.init(name, dataFile, vocabFile, vocabSize, wordsMinFrequency, featuresVocabsFiles, validFunc) local wordVocab local featuresVocabs = {} local numFeatures = countFeatures(dataFile) if vocabFile:len() > 0 then -- If given, load existing word dictionary. _G.logger:info('Reading ' .. name .. ' vocabulary from \'' .. vocabFile .. '\'...') wordVocab = onmt.utils.Dict.new() wordVocab:loadFile(vocabFile) _G.logger:info('Loaded ' .. wordVocab:size() .. ' ' .. name .. ' words') end if featuresVocabsFiles:len() > 0 and numFeatures > 0 then -- If given, discover existing features dictionaries. local j = 1 while true do local file = featuresVocabsFiles .. '.' .. name .. '_feature_' .. j .. '.dict' if not path.exists(file) then break end _G.logger:info('Reading ' .. name .. ' feature ' .. j .. ' vocabulary from \'' .. file .. '\'...') featuresVocabs[j] = onmt.utils.Dict.new() featuresVocabs[j]:loadFile(file) _G.logger:info('Loaded ' .. featuresVocabs[j]:size() .. ' labels') j = j + 1 end assert(#featuresVocabs > 0, 'dictionary \'' .. featuresVocabsFiles .. '.' .. name .. '_feature_1.dict\' not found') assert(#featuresVocabs == numFeatures, 'the data contains ' .. numFeatures .. ' ' .. name .. ' features but only ' .. #featuresVocabs .. ' dictionaries were found') end if wordVocab == nil or (#featuresVocabs == 0 and numFeatures > 0) then -- If a dictionary is still missing, generate it. _G.logger:info('Building ' .. name .. ' vocabularies...') local genWordVocab, genFeaturesVocabs = Vocabulary.make(dataFile, validFunc) local originalSizes = { genWordVocab:size() } for i = 1, #genFeaturesVocabs do table.insert(originalSizes, genFeaturesVocabs[i]:size()) end local newSizes = onmt.utils.String.split(vocabSize, ',') local minFrequency = onmt.utils.String.split(wordsMinFrequency, ',') for i = 1, 1 + #genFeaturesVocabs do newSizes[i] = (newSizes[i] and tonumber(newSizes[i])) or 0 minFrequency[i] = (minFrequency[i] and tonumber(minFrequency[i])) or 0 end if wordVocab == nil then if minFrequency[1] > 0 then wordVocab = genWordVocab:pruneByMinFrequency(minFrequency[1]) elseif newSizes[1] > 0 then wordVocab = genWordVocab:prune(newSizes[1]) end _G.logger:info('Created word dictionary of size ' .. wordVocab:size() .. ' (pruned from ' .. originalSizes[1] .. ')') end if #featuresVocabs == 0 then for i = 1, #genFeaturesVocabs do if minFrequency[i + 1] > 0 then featuresVocabs[i] = genFeaturesVocabs[i]:pruneByMinFrequency(minFrequency[i + 1]) elseif newSizes[i + 1] > 0 then featuresVocabs[i] = genFeaturesVocabs[i]:prune(newSizes[i + 1]) end _G.logger:info('Created feature ' .. i .. ' dictionary of size ' .. featuresVocabs[i]:size() .. ' (pruned from ' .. originalSizes[i + 1] .. ')') end end end _G.logger:info('') return { words = wordVocab, features = featuresVocabs } end function Vocabulary.save(name, vocab, file) _G.logger:info('Saving ' .. name .. ' vocabulary to \'' .. file .. '\'...') vocab:writeFile(file) end function Vocabulary.saveFeatures(name, vocabs, prefix) for j = 1, #vocabs do local file = prefix .. '.' .. name .. '_feature_' .. j .. '.dict' _G.logger:info('Saving ' .. name .. ' feature ' .. j .. ' vocabulary to \'' .. file .. '\'...') vocabs[j]:writeFile(file) end end return Vocabulary
local path = require('pl.path') --[[ Vocabulary management utility functions. ]] local Vocabulary = torch.class("Vocabulary") local function countFeatures(filename) local reader = onmt.utils.FileReader.new(filename) local _, _, numFeatures = onmt.utils.Features.extract(reader:next()) reader:close() return numFeatures end function Vocabulary.make(filename, validFunc) local wordVocab = onmt.utils.Dict.new({onmt.Constants.PAD_WORD, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD}) local featuresVocabs = {} local reader = onmt.utils.FileReader.new(filename) local lineId = 0 while true do local sent = reader:next() if sent == nil then break end lineId = lineId + 1 if validFunc(sent) then local words, features, numFeatures local _, err = pcall(function () words, features, numFeatures = onmt.utils.Features.extract(sent) end) if err then error(err .. ' (' .. filename .. ':' .. lineId .. ')') end if #featuresVocabs == 0 and numFeatures > 0 then for j = 1, numFeatures do featuresVocabs[j] = onmt.utils.Dict.new({onmt.Constants.PAD_WORD, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD}) end else assert(#featuresVocabs == numFeatures, 'all sentences must have the same numbers of additional features (' .. filename .. ':' .. lineId .. ')') end for i = 1, #words do wordVocab:add(words[i]) for j = 1, numFeatures do featuresVocabs[j]:add(features[j][i]) end end end end reader:close() return wordVocab, featuresVocabs end function Vocabulary.init(name, dataFile, vocabFile, vocabSize, wordsMinFrequency, featuresVocabsFiles, validFunc) local wordVocab local featuresVocabs = {} local numFeatures = countFeatures(dataFile) if vocabFile:len() > 0 then -- If given, load existing word dictionary. _G.logger:info('Reading ' .. name .. ' vocabulary from \'' .. vocabFile .. '\'...') wordVocab = onmt.utils.Dict.new() wordVocab:loadFile(vocabFile) _G.logger:info('Loaded ' .. wordVocab:size() .. ' ' .. name .. ' words') end if featuresVocabsFiles:len() > 0 and numFeatures > 0 then -- If given, discover existing features dictionaries. local j = 1 while true do local file = featuresVocabsFiles .. '.' .. name .. '_feature_' .. j .. '.dict' if not path.exists(file) then break end _G.logger:info('Reading ' .. name .. ' feature ' .. j .. ' vocabulary from \'' .. file .. '\'...') featuresVocabs[j] = onmt.utils.Dict.new() featuresVocabs[j]:loadFile(file) _G.logger:info('Loaded ' .. featuresVocabs[j]:size() .. ' labels') j = j + 1 end assert(#featuresVocabs > 0, 'dictionary \'' .. featuresVocabsFiles .. '.' .. name .. '_feature_1.dict\' not found') assert(#featuresVocabs == numFeatures, 'the data contains ' .. numFeatures .. ' ' .. name .. ' features but only ' .. #featuresVocabs .. ' dictionaries were found') end if wordVocab == nil or (#featuresVocabs == 0 and numFeatures > 0) then -- If a dictionary is still missing, generate it. _G.logger:info('Building ' .. name .. ' vocabularies...') local genWordVocab, genFeaturesVocabs = Vocabulary.make(dataFile, validFunc) local originalSizes = { genWordVocab:size() } for i = 1, #genFeaturesVocabs do table.insert(originalSizes, genFeaturesVocabs[i]:size()) end local newSizes = onmt.utils.String.split(vocabSize, ',') local minFrequency = onmt.utils.String.split(wordsMinFrequency, ',') for i = 1, 1 + #genFeaturesVocabs do newSizes[i] = (newSizes[i] and tonumber(newSizes[i])) or 0 minFrequency[i] = (minFrequency[i] and tonumber(minFrequency[i])) or 0 end if wordVocab == nil then if minFrequency[1] > 0 then wordVocab = genWordVocab:pruneByMinFrequency(minFrequency[1]) elseif newSizes[1] > 0 then wordVocab = genWordVocab:prune(newSizes[1]) else wordVocab = genWordVocab end _G.logger:info('Created word dictionary of size ' .. wordVocab:size() .. ' (pruned from ' .. originalSizes[1] .. ')') end if #featuresVocabs == 0 then for i = 1, #genFeaturesVocabs do if minFrequency[i + 1] > 0 then featuresVocabs[i] = genFeaturesVocabs[i]:pruneByMinFrequency(minFrequency[i + 1]) elseif newSizes[i + 1] > 0 then featuresVocabs[i] = genFeaturesVocabs[i]:prune(newSizes[i + 1]) else featuresVocabs[i] = genFeaturesVocabs[i] end _G.logger:info('Created feature ' .. i .. ' dictionary of size ' .. featuresVocabs[i]:size() .. ' (pruned from ' .. originalSizes[i + 1] .. ')') end end end _G.logger:info('') return { words = wordVocab, features = featuresVocabs } end function Vocabulary.save(name, vocab, file) _G.logger:info('Saving ' .. name .. ' vocabulary to \'' .. file .. '\'...') vocab:writeFile(file) end function Vocabulary.saveFeatures(name, vocabs, prefix) for j = 1, #vocabs do local file = prefix .. '.' .. name .. '_feature_' .. j .. '.dict' _G.logger:info('Saving ' .. name .. ' feature ' .. j .. ' vocabulary to \'' .. file .. '\'...') vocabs[j]:writeFile(file) end end return Vocabulary
Fix vocabularies assignment when no pruning is required
Fix vocabularies assignment when no pruning is required
Lua
mit
jungikim/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT
78c366af6f1e3ffaacc5fda11584b4390f3d892b
plugins/mod_saslauth.lua
plugins/mod_saslauth.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local sm_make_authenticated = require "core.sessionmanager".make_authenticated; local base64 = require "util.encodings".base64; local nodeprep = require "util.encodings".stringprep.nodeprep; local datamanager_load = require "util.datamanager".load; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_get_password = require "core.usermanager".get_password; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption"); local sasl_backend = module:get_option("sasl_backend") or "builtin"; local log = module._log; local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl if sasl_backend == "cyrus" then local cyrus_new = require "util.sasl_cyrus".new; new_sasl = function(realm) return cyrus_new(realm, module:get_option("cyrus_service_name") or "xmpp") end else if sasl_backend ~= "builtin" then module:log("warn", "Unknown SASL backend %s", sasl_backend) end; new_sasl = require "util.sasl".new; end local default_authentication_profile = { plain = function(username, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end local password = usermanager_get_password(prepped_username, realm); if not password then return "", nil; end return password, true; end }; local anonymous_authentication_profile = { anonymous = function(username, realm) return true; -- for normal usage you should always return true here end }; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); else module:log("error", "Unknown sasl status: %s", status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = session.sasl_handler:clean_clone(); elseif status == "success" then local username = nodeprep(session.sasl_handler.username); if not username then -- TODO move this to sessionmanager module:log("warn", "SASL succeeded but we didn't get a username!"); session.sasl_handler = nil; session:reset_stream(); return; end sm_make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does if config.get(session.host or "*", "core", "anonymous_login") then if stanza.attr.mechanism ~= "ANONYMOUS" then return session.send(build_reply("failure", "invalid-mechanism")); end elseif stanza.attr.mechanism == "ANONYMOUS" then return session.send(build_reply("failure", "mechanism-too-weak")); end local valid_mechanism = session.sasl_handler:select(stanza.attr.mechanism); if not valid_mechanism then return session.send(build_reply("failure", "invalid-mechanism")); end if secure_auth_only and not session.secure then return session.send(build_reply("failure", "encryption-required")); end elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", "%s", text:gsub("[%z\001-\008\011\012\014-\031]", " ")); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:process(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: %s", tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function (session, features) if not session.username then if secure_auth_only and not session.secure then return; end if module:get_option("anonymous_login") then session.sasl_handler = new_sasl(session.host, anonymous_authentication_profile); else session.sasl_handler = new_sasl(session.host, default_authentication_profile); if not (module:get_option("allow_unencrypted_plain_auth")) and not session.secure then session.sasl_handler:forbidden({"PLAIN"}); end end features:tag("mechanisms", mechanisms_attr); for k, v in pairs(session.sasl_handler:mechanisms()) do features:tag("mechanism"):text(v):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):tag("optional"):up():up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function (session, stanza) log("debug", "Client requesting a resource bind"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function (session, stanza) log("debug", "Client requesting a session"); session.send(st.reply(stanza)); end);
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local sm_make_authenticated = require "core.sessionmanager".make_authenticated; local base64 = require "util.encodings".base64; local nodeprep = require "util.encodings".stringprep.nodeprep; local datamanager_load = require "util.datamanager".load; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_get_password = require "core.usermanager".get_password; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split; local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local secure_auth_only = module:get_option("c2s_require_encryption") or module:get_option("require_encryption"); local sasl_backend = module:get_option("sasl_backend") or "builtin"; local log = module._log; local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl if sasl_backend == "cyrus" then local cyrus_new = require "util.sasl_cyrus".new; new_sasl = function(realm) return cyrus_new(realm, module:get_option("cyrus_service_name") or "xmpp"); end else if sasl_backend ~= "builtin" then module:log("warn", "Unknown SASL backend %s", sasl_backend); end; new_sasl = require "util.sasl".new; end local default_authentication_profile = { plain = function(username, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end local password = usermanager_get_password(prepped_username, realm); if not password then return "", nil; end return password, true; end }; local anonymous_authentication_profile = { anonymous = function(username, realm) return true; -- for normal usage you should always return true here end }; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", "%s", ret or ""); reply:text(base64.encode(ret or "")); else module:log("error", "Unknown sasl status: %s", status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = session.sasl_handler:clean_clone(); elseif status == "success" then local username = nodeprep(session.sasl_handler.username); if not username then -- TODO move this to sessionmanager module:log("warn", "SASL succeeded but we didn't get a username!"); session.sasl_handler = nil; session:reset_stream(); return; end sm_make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does if config.get(session.host or "*", "core", "anonymous_login") then if stanza.attr.mechanism ~= "ANONYMOUS" then return session.send(build_reply("failure", "invalid-mechanism")); end elseif stanza.attr.mechanism == "ANONYMOUS" then return session.send(build_reply("failure", "mechanism-too-weak")); end local valid_mechanism = session.sasl_handler:select(stanza.attr.mechanism); if not valid_mechanism then return session.send(build_reply("failure", "invalid-mechanism")); end if secure_auth_only and not session.secure then return session.send(build_reply("failure", "encryption-required")); end elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", "%s", text:gsub("[%z\001-\008\011\012\014-\031]", " ")); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:process(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: %s", tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function(session, features) if not session.username then if secure_auth_only and not session.secure then return; end if module:get_option("anonymous_login") then session.sasl_handler = new_sasl(session.host, anonymous_authentication_profile); else session.sasl_handler = new_sasl(session.host, default_authentication_profile); if not (module:get_option("allow_unencrypted_plain_auth")) and not session.secure then session.sasl_handler:forbidden({"PLAIN"}); end end features:tag("mechanisms", mechanisms_attr); for k, v in pairs(session.sasl_handler:mechanisms()) do features:tag("mechanism"):text(v):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):tag("optional"):up():up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function(session, stanza) log("debug", "Client requesting a resource bind"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function(session, stanza) log("debug", "Client requesting a session"); session.send(st.reply(stanza)); end);
mod_saslauth: Fixed some indentation and added some semi-colons.
mod_saslauth: Fixed some indentation and added some semi-colons.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e8a48483abd3b210f9f687a11a6a8325d76a4227
service/clusterd.lua
service/clusterd.lua
local skynet = require "skynet" require "skynet.manager" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice("clustersender", key, nodename, host, port) if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c else err = string.format("changenode [%s] (%s:%s) failed", key, host, port) end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) if node_address[key] ~= address then return open_channel(t,key) end return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end local reload = {} for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection table.insert(reload, name) end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end for _, name in ipairs(reload) do -- open_channel would block skynet.fork(open_channel, node_channel, name) end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end function command.senders(source) skynet.retpack(node_sender) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
local skynet = require "skynet" require "skynet.manager" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice("clustersender", key, nodename, host, port) if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c else err = string.format("changenode [%s] (%s:%s) failed", key, host, port) end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end if node_address[key] ~= address then return open_channel(t,key) end assert(succ, err) return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end local reload = {} for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection table.insert(reload, name) end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end for _, name in ipairs(reload) do -- open_channel would block skynet.fork(open_channel, node_channel, name) end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end function command.senders(source) skynet.retpack(node_sender) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
Check address changes before raise error, fix #1273
Check address changes before raise error, fix #1273
Lua
mit
hongling0/skynet,xcjmine/skynet,xjdrew/skynet,korialuo/skynet,sanikoyes/skynet,cloudwu/skynet,xcjmine/skynet,hongling0/skynet,wangyi0226/skynet,xjdrew/skynet,icetoggle/skynet,pigparadise/skynet,xjdrew/skynet,icetoggle/skynet,wangyi0226/skynet,korialuo/skynet,pigparadise/skynet,cloudwu/skynet,cloudwu/skynet,icetoggle/skynet,hongling0/skynet,pigparadise/skynet,wangyi0226/skynet,xcjmine/skynet,korialuo/skynet,sanikoyes/skynet,sanikoyes/skynet
704b016f2cec9ba7d0799c8bd1408b613fef0e64
service/clusterd.lua
service/clusterd.lua
local skynet = require "skynet" local sc = require "socketchannel" local socket = require "socket" local cluster = require "cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_session = {} local command = {} local function read_response(sock) local sz = socket.header(sock:read(2)) local msg = sock:read(sz) return cluster.unpackresponse(msg) -- session, ok, data end local function open_channel(t, key) local host, port = string.match(node_address[key], "([^:]+):(.*)$") local c = sc.channel { host = host, port = tonumber(port), response = read_response, nodelay = true, } assert(c:connect(true)) t[key] = c return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig() local f = assert(io.open(config_name)) local source = f:read "*a" f:close() local tmp = {} assert(load(source, "@"..config_name, "t", tmp))() for name,address in pairs(tmp) do assert(type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end end end function command.reload() loadconfig() skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then addr, port = string.match(node_address[addr], "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end local function send_request(source, node, addr, msg, sz) local session = node_session[node] or 1 -- msg is a local pointer, cluster.packrequest will free it local request, new_session = cluster.packrequest(addr, session, msg, sz) local c = node_channel[node] node_session[node] = new_session return c:request(request, session) end function command.req(...) local ok, msg, sz = pcall(send_request, ...) if ok then skynet.ret(msg, sz) else skynet.error(msg) skynet.response()(false) end end local proxy = {} function command.proxy(source, node, name) local fullname = node .. "." .. name if proxy[fullname] == nil then proxy[fullname] = skynet.newservice("clusterproxy", node, name) end skynet.ret(skynet.pack(proxy[fullname])) end local request_fd = {} function command.socket(source, subcmd, fd, msg) if subcmd == "data" then local addr, session, msg = cluster.unpackrequest(msg) local ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg) local response if ok then response = cluster.packresponse(session, true, msg, sz) else response = cluster.packresponse(session, false, msg) end socket.write(fd, response) elseif subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) skynet.call(source, "lua", "accept", fd) else skynet.error(string.format("socket %s %d : %s", subcmd, fd, msg)) end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
local skynet = require "skynet" local sc = require "socketchannel" local socket = require "socket" local cluster = require "cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_session = {} local command = {} local function read_response(sock) local sz = socket.header(sock:read(2)) local msg = sock:read(sz) return cluster.unpackresponse(msg) -- session, ok, data end local function open_channel(t, key) local host, port = string.match(node_address[key], "([^:]+):(.*)$") local c = sc.channel { host = host, port = tonumber(port), response = read_response, nodelay = true, } assert(c:connect(true)) t[key] = c return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig() local f = assert(io.open(config_name)) local source = f:read "*a" f:close() local tmp = {} assert(load(source, "@"..config_name, "t", tmp))() for name,address in pairs(tmp) do assert(type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection end node_address[name] = address end end end function command.reload() loadconfig() skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then addr, port = string.match(node_address[addr], "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end local function send_request(source, node, addr, msg, sz) local session = node_session[node] or 1 -- msg is a local pointer, cluster.packrequest will free it local request, new_session = cluster.packrequest(addr, session, msg, sz) node_session[node] = new_session -- node_channel[node] may yield or throw error local c = node_channel[node] return c:request(request, session) end function command.req(...) local ok, msg, sz = pcall(send_request, ...) if ok then skynet.ret(msg, sz) else skynet.error(msg) skynet.response()(false) end end local proxy = {} function command.proxy(source, node, name) local fullname = node .. "." .. name if proxy[fullname] == nil then proxy[fullname] = skynet.newservice("clusterproxy", node, name) end skynet.ret(skynet.pack(proxy[fullname])) end local request_fd = {} function command.socket(source, subcmd, fd, msg) if subcmd == "data" then local addr, session, msg = cluster.unpackrequest(msg) local ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg) local response if ok then response = cluster.packresponse(session, true, msg, sz) else response = cluster.packresponse(session, false, msg) end socket.write(fd, response) elseif subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) skynet.call(source, "lua", "accept", fd) else skynet.error(string.format("socket %s %d : %s", subcmd, fd, msg)) end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
bugfix: inc session before get channel
bugfix: inc session before get channel
Lua
mit
Ding8222/skynet,helling34/skynet,helling34/skynet,great90/skynet,jxlczjp77/skynet,hongling0/skynet,u20024804/skynet,MRunFoss/skynet,catinred2/skynet,sundream/skynet,cuit-zhaxin/skynet,your-gatsby/skynet,czlc/skynet,MetSystem/skynet,your-gatsby/skynet,your-gatsby/skynet,xjdrew/skynet,kyle-wang/skynet,great90/skynet,KittyCookie/skynet,korialuo/skynet,letmefly/skynet,zhouxiaoxiaoxujian/skynet,cmingjian/skynet,asanosoyokaze/skynet,QuiQiJingFeng/skynet,sundream/skynet,letmefly/skynet,MRunFoss/skynet,ypengju/skynet_comment,zhangshiqian1214/skynet,zhangshiqian1214/skynet,cdd990/skynet,MRunFoss/skynet,boyuegame/skynet,kyle-wang/skynet,dymx101/skynet,microcai/skynet,samael65535/skynet,QuiQiJingFeng/skynet,wangyi0226/skynet,jxlczjp77/skynet,zzh442856860/skynet,JiessieDawn/skynet,rainfiel/skynet,enulex/skynet,zhoukk/skynet,chfg007/skynet,pichina/skynet,wangjunwei01/skynet,icetoggle/skynet,ag6ag/skynet,gitfancode/skynet,zhangshiqian1214/skynet,bingo235/skynet,harryzeng/skynet,pichina/skynet,cloudwu/skynet,liuxuezhan/skynet,helling34/skynet,sdgdsffdsfff/skynet,lc412/skynet,wangjunwei01/skynet,puXiaoyi/skynet,codingabc/skynet,fhaoquan/skynet,liuxuezhan/skynet,harryzeng/skynet,fhaoquan/skynet,Ding8222/skynet,xcjmine/skynet,zhangshiqian1214/skynet,puXiaoyi/skynet,hongling0/skynet,xcjmine/skynet,chuenlungwang/skynet,Markal128/skynet,liuxuezhan/skynet,samael65535/skynet,gitfancode/skynet,sundream/skynet,KAndQ/skynet,catinred2/skynet,longmian/skynet,lc412/skynet,matinJ/skynet,xinjuncoding/skynet,bigrpg/skynet,firedtoad/skynet,cuit-zhaxin/skynet,microcai/skynet,enulex/skynet,pigparadise/skynet,cloudwu/skynet,codingabc/skynet,MetSystem/skynet,zhangshiqian1214/skynet,jxlczjp77/skynet,great90/skynet,iskygame/skynet,javachengwc/skynet,felixdae/skynet,microcai/skynet,Zirpon/skynet,felixdae/skynet,xinjuncoding/skynet,ag6ag/skynet,bingo235/skynet,firedtoad/skynet,leezhongshan/skynet,boyuegame/skynet,lawnight/skynet,asanosoyokaze/skynet,ludi1991/skynet,felixdae/skynet,LiangMa/skynet,Ding8222/skynet,xjdrew/skynet,bttscut/skynet,leezhongshan/skynet,kebo/skynet,vizewang/skynet,nightcj/mmo,bigrpg/skynet,QuiQiJingFeng/skynet,kebo/skynet,fhaoquan/skynet,JiessieDawn/skynet,Zirpon/skynet,cpascal/skynet,wangyi0226/skynet,kyle-wang/skynet,icetoggle/skynet,zhoukk/skynet,enulex/skynet,cmingjian/skynet,zhouxiaoxiaoxujian/skynet,xcjmine/skynet,Zirpon/skynet,LiangMa/skynet,yunGit/skynet,nightcj/mmo,u20024804/skynet,leezhongshan/skynet,codingabc/skynet,dymx101/skynet,pigparadise/skynet,cloudwu/skynet,u20024804/skynet,liuxuezhan/skynet,ag6ag/skynet,bttscut/skynet,sanikoyes/skynet,chfg007/skynet,bigrpg/skynet,cmingjian/skynet,lynx-seu/skynet,ypengju/skynet_comment,nightcj/mmo,Markal128/skynet,kebo/skynet,sanikoyes/skynet,rainfiel/skynet,ludi1991/skynet,xinjuncoding/skynet,ypengju/skynet_comment,fztcjjl/skynet,zzh442856860/skynet,zzh442856860/skynet,asanosoyokaze/skynet,MoZhonghua/skynet,KittyCookie/skynet,korialuo/skynet,vizewang/skynet,lawnight/skynet,KittyCookie/skynet,javachengwc/skynet,xjdrew/skynet,chuenlungwang/skynet,letmefly/skynet,rainfiel/skynet,cpascal/skynet,MoZhonghua/skynet,iskygame/skynet,chuenlungwang/skynet,cpascal/skynet,iskygame/skynet,fztcjjl/skynet,cdd990/skynet,puXiaoyi/skynet,MetSystem/skynet,KAndQ/skynet,yunGit/skynet,lawnight/skynet,vizewang/skynet,pigparadise/skynet,icetoggle/skynet,czlc/skynet,korialuo/skynet,lynx-seu/skynet,ilylia/skynet,lawnight/skynet,LiangMa/skynet,lynx-seu/skynet,czlc/skynet,hongling0/skynet,fztcjjl/skynet,chfg007/skynet,cdd990/skynet,jiuaiwo1314/skynet,Markal128/skynet,wangjunwei01/skynet,gitfancode/skynet,harryzeng/skynet,jiuaiwo1314/skynet,bingo235/skynet,letmefly/skynet,JiessieDawn/skynet,MoZhonghua/skynet,longmian/skynet,dymx101/skynet,bttscut/skynet,zhoukk/skynet,cuit-zhaxin/skynet,sdgdsffdsfff/skynet,lc412/skynet,longmian/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,sanikoyes/skynet,javachengwc/skynet,jiuaiwo1314/skynet,samael65535/skynet,KAndQ/skynet,ludi1991/skynet,wangyi0226/skynet,catinred2/skynet,matinJ/skynet,firedtoad/skynet,yunGit/skynet,ilylia/skynet,pichina/skynet,boyuegame/skynet,ilylia/skynet,sdgdsffdsfff/skynet,ludi1991/skynet,matinJ/skynet
30d86516eb9e73304a4ed3a1f57242d435b04c87
premake4.lua
premake4.lua
-- os.outputof is broken in premake4, hence this workaround function llvm_config(opt) local stream = assert(io.popen("llvm-config-3.5 " .. opt)) local output = "" --llvm-config contains '\n' while true do local curr = stream:read("*l") if curr == nil then break end output = output .. curr end stream:close() return output end function link_libponyc() linkoptions { llvm_config("--ldflags") } links { "libponyc", "libponyrt", "libponycc", "z", "curses" } local output = llvm_config("--libs") for lib in string.gmatch(output, "-l(%S+)") do links { lib } end configuration("not macosx") links { "tinfo", "dl", } configuration("*") end solution "ponyc" configurations { "Debug", "Release", "Profile" } buildoptions { "-mcx16", "-march=native", "-pthread" } linkoptions { "-pthread" } flags { "ExtraWarnings", "FatalWarnings", "Symbols" } configuration "macosx" buildoptions "-Qunused-arguments" linkoptions "-Qunused-arguments" configuration "Debug" targetdir "bin/debug" configuration "Release" targetdir "bin/release" configuration "Profile" targetdir "bin/profile" buildoptions "-pg" linkoptions "-pg" configuration "Release or Profile" defines "NDEBUG" flags "OptimizeSpeed" linkoptions { "-fuse-ld=gold", } configuration "*" includedirs { "inc/" } files { "inc/**.h" } project "libponyc" targetname "ponyc" kind "StaticLib" language "C" buildoptions "-std=gnu11" includedirs { llvm_config("--includedir") } defines { "_DEBUG", "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS", } files { "src/libponyc/**.c", "src/libponyc/**.h" } configuration "linux or macosx" excludes { "src/libponyc/platform/**.cc", "src/libponyc/platform/vcvars.c", "src/libponyrt/asio/iocp.c", "src/libponyrt/lang/win_except.c" } configuration "linux" excludes { "src/libponyrt/asio/kqueue.c" } configuration "macosx" excludes { "src/libponyrt/asio/epoll.c" } project "libponyrt" targetname "ponyrt" kind "StaticLib" language "C" buildoptions "-std=gnu11" files { "src/libponyrt/**.h", "src/libponyrt/**.c" } configuration "macosx" excludes { "src/libponyrt/asio/epoll.c", "src/libponyrt/asio/iocp.c", "src/libponyrt/lang/win_except.c" } project "libponycc" targetname "ponycc" kind "StaticLib" language "C++" buildoptions "-std=gnu++11" includedirs { llvm_config("--includedir") } defines { "_DEBUG", "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS", } files { "src/libponyc/codegen/host.cc" } project "ponyc" kind "ConsoleApp" language "C++" buildoptions "-std=gnu11" files { "src/ponyc/**.c", "src/ponyc/**.h" } link_libponyc() postbuildcommands { "rm -rf $(TARGETDIR)/builtin", "-ln -sf " .. path.getabsolute("packages/builtin") .. " $(TARGETDIR)" } project "gtest" language "C++" kind "StaticLib" includedirs { "utils/gtest/" } files { "utils/gtest/gtest-all.cc", "utils/gtest/gtest_main.cc" } project "tests" language "C++" kind "ConsoleApp" configuration "*" includedirs { "utils/gtest/", "src/libponyc/", "src/libponyrt/", } buildoptions "-std=gnu++11" files { "test/unit/ponyc/**.cc", "test/unit/ponyc/**.h" } links { "gtest" } link_libponyc()
-- os.outputof is broken in premake4, hence this workaround function llvm_config(opt) local stream = assert(io.popen("llvm-config-3.5 " .. opt)) local output = "" --llvm-config contains '\n' while true do local curr = stream:read("*l") if curr == nil then break end output = output .. curr end stream:close() return output end function link_libponyc() linkoptions { llvm_config("--ldflags") } links { "libponyc", "libponyrt", "libponycc", "z", "curses" } local output = llvm_config("--libs") for lib in string.gmatch(output, "-l(%S+)") do links { lib } end configuration("not macosx") links { "tinfo", "dl", } configuration("*") end solution "ponyc" configurations { "Debug", "Release", "Profile" } buildoptions { "-mcx16", "-march=native", "-pthread" } linkoptions { "-pthread" } flags { "ExtraWarnings", "FatalWarnings", "Symbols" } configuration "macosx" buildoptions "-Qunused-arguments" linkoptions "-Qunused-arguments" configuration "Debug" targetdir "bin/debug" configuration "Release" targetdir "bin/release" configuration "Profile" targetdir "bin/profile" buildoptions "-pg" linkoptions "-pg" configuration "Release or Profile" defines "NDEBUG" flags "OptimizeSpeed" linkoptions { "-fuse-ld=gold", } configuration "*" includedirs { "inc/" } files { "inc/**.h" } project "libponyc" targetname "ponyc" kind "StaticLib" language "C" buildoptions "-std=gnu11" includedirs { llvm_config("--includedir") } defines { "_DEBUG", "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS", } files { "src/libponyc/**.c", "src/libponyc/**.h" } configuration "linux or macosx" excludes { "src/libponyc/platform/**.cc", "src/libponyc/platform/vcvars.c" } project "libponyrt" targetname "ponyrt" kind "StaticLib" language "C" buildoptions "-std=gnu11" files { "src/libponyrt/**.h", "src/libponyrt/**.c" } configuration "linux or macosx" excludes { "src/libponyrt/asio/iocp.c", "src/libponyrt/lang/win_except.c" } configuration "linux" excludes { "src/libponyrt/asio/kqueue.c" } configuration "macosx" excludes { "src/libponyrt/asio/epoll.c" } project "libponycc" targetname "ponycc" kind "StaticLib" language "C++" buildoptions "-std=gnu++11" includedirs { llvm_config("--includedir") } defines { "_DEBUG", "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS", } files { "src/libponyc/codegen/host.cc" } project "ponyc" kind "ConsoleApp" language "C++" buildoptions "-std=gnu11" files { "src/ponyc/**.c", "src/ponyc/**.h" } link_libponyc() postbuildcommands { "rm -rf $(TARGETDIR)/builtin", "-ln -sf " .. path.getabsolute("packages/builtin") .. " $(TARGETDIR)" } project "gtest" language "C++" kind "StaticLib" includedirs { "utils/gtest/" } files { "utils/gtest/gtest-all.cc", "utils/gtest/gtest_main.cc" } project "tests" language "C++" kind "ConsoleApp" configuration "*" includedirs { "utils/gtest/", "src/libponyc/", "src/libponyrt/", } buildoptions "-std=gnu++11" files { "test/unit/ponyc/**.cc", "test/unit/ponyc/**.h" } links { "gtest" } link_libponyc()
premake fix again
premake fix again
Lua
bsd-2-clause
doublec/ponyc,kulibali/ponyc,kulibali/ponyc,pap/ponyc,cquinn/ponyc,Theodus/ponyc,lukecheeseman/ponyta,shlomif/ponyc,jupvfranco/ponyc,malthe/ponyc,CausalityLtd/ponyc,doublec/ponyc,mkfifo/ponyc,jonas-l/ponyc,influx6/ponyc,sgebbie/ponyc,jonas-l/ponyc,darach/ponyc,pap/ponyc,Praetonus/ponyc,boemmels/ponyc,jupvfranco/ponyc,Praetonus/ponyc,jemc/ponyc,malthe/ponyc,cquinn/ponyc,Theodus/ponyc,kulibali/ponyc,Perelandric/ponyc,mkfifo/ponyc,ryanai3/ponyc,cquinn/ponyc,darach/ponyc,mkfifo/ponyc,boemmels/ponyc,CausalityLtd/ponyc,darach/ponyc,ponylang/ponyc,boemmels/ponyc,jupvfranco/ponyc,dckc/ponyc,kulibali/ponyc,malthe/ponyc,mkfifo/ponyc,Praetonus/ponyc,Perelandric/ponyc,boemmels/ponyc,dipinhora/ponyc,cquinn/ponyc,ryanai3/ponyc,Perelandric/ponyc,boemmels/ponyc,doublec/ponyc,shlomif/ponyc,dckc/ponyc,Perelandric/ponyc,gwelr/ponyc,gwelr/ponyc,lukecheeseman/ponyta,mkfifo/ponyc,sgebbie/ponyc,Perelandric/ponyc,influx6/ponyc,sgebbie/ponyc,jupvfranco/ponyc,Praetonus/ponyc,ponylang/ponyc,dipinhora/ponyc,CausalityLtd/ponyc,jupvfranco/ponyc,sgebbie/ponyc,malthe/ponyc,Theodus/ponyc,ponylang/ponyc,jemc/ponyc,Theodus/ponyc,sgebbie/ponyc,pap/ponyc,jonas-l/ponyc,dipinhora/ponyc,Theodus/ponyc,lukecheeseman/ponyta,jemc/ponyc,ryanai3/ponyc
902d682238e1c874f1fdcb280932c15b87b1c89a
premake4.lua
premake4.lua
function args_contains( element ) for _, value in pairs(_ARGS) do if value == element then return true end end return false end solution "efsw" location("./make/" .. os.get() .. "/") targetdir("./bin") configurations { "debug", "release" } if os.is("windows") then osfiles = "src/efsw/platform/win/*.cpp" else osfiles = "src/efsw/platform/posix/*.cpp" end -- This is for testing in other platforms that don't support kqueue if args_contains( "kqueue" ) then links { "kqueue" } defines { "EFSW_KQUEUE" } printf("Forced Kqueue backend build.") end -- Activates verbose mode if args_contains( "verbose" ) then defines { "EFSW_VERBOSE" } end if os.is("macosx") then -- Premake 4.4 needed for this if not string.match(_PREMAKE_VERSION, "^4.[123]") then local ver = os.getversion(); if not ( ver.majorversion >= 10 and ver.minorversion >= 5 ) then defines { "EFSW_FSEVENTS_NOT_SUPPORTED" } end end end objdir("obj/" .. os.get() .. "/") project "efsw-static-lib" kind "StaticLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall -pedantic -Wno-long-long" } targetname "efsw-static-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } targetname "efsw-static-release" project "efsw-test" kind "ConsoleApp" language "C++" links { "efsw-static-lib" } files { "src/test/*.cpp" } includedirs { "include", "src" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall" } targetname "efsw-test-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw-test-release" project "efsw-shared-lib" kind "SharedLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } defines { "EFSW_DYNAMIC", "EFSW_EXPORTS" } configuration "debug" defines { "DEBUG" } buildoptions{ "-Wall" } flags { "Symbols" } targetname "efsw-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw"
function args_contains( element ) for _, value in pairs(_ARGS) do if value == element then return true end end return false end solution "efsw" location("./make/" .. os.get() .. "/") targetdir("./bin") configurations { "debug", "release" } if os.is("windows") then osfiles = "src/efsw/platform/win/*.cpp" else osfiles = "src/efsw/platform/posix/*.cpp" end -- This is for testing in other platforms that don't support kqueue if args_contains( "kqueue" ) then links { "kqueue" } defines { "EFSW_KQUEUE" } printf("Forced Kqueue backend build.") end -- Activates verbose mode if args_contains( "verbose" ) then defines { "EFSW_VERBOSE" } end if os.is("macosx") then -- Premake 4.4 needed for this if not string.match(_PREMAKE_VERSION, "^4.[123]") then local ver = os.getversion(); if not ( ver.majorversion >= 10 and ver.minorversion >= 5 ) then defines { "EFSW_FSEVENTS_NOT_SUPPORTED" } end end end objdir("obj/" .. os.get() .. "/") project "efsw-static-lib" kind "StaticLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall -pedantic -Wno-long-long" } targetname "efsw-static-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } targetname "efsw-static-release" project "efsw-test" kind "ConsoleApp" language "C++" links { "efsw-static-lib" } files { "src/test/*.cpp" } includedirs { "include", "src" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall" } targetname "efsw-test-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw-test-release" project "efsw-shared-lib" kind "SharedLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } defines { "EFSW_DYNAMIC", "EFSW_EXPORTS" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } buildoptions{ "-Wall" } flags { "Symbols" } targetname "efsw-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw"
Fixed shared library links.
Fixed shared library links.
Lua
mit
havoc-io/efsw,havoc-io/efsw,havoc-io/efsw
afad480387f0178eadc70d90582797bb594fc803
src/Game.lua
src/Game.lua
require ("lib.lclass") require ("src.EventManager") require ("src.data.PositionData") require ("src.events.FocusGainedEvent") require ("src.events.FocusLostEvent") require ("src.events.KeyboardKeyDownEvent") require ("src.events.KeyboardKeyUpEvent") require ("src.events.MouseButtonDownEvent") require ("src.events.MouseButtonUpEvent") require ("src.events.ResizeEvent") require ("src.Ship") class "Game" -- Constructs a new game function Game:Game () -- self.eventManager = EventManager () self.eventManager:subscribe ("FocusGainedEvent", self) self.eventManager:subscribe ("FocusLostEvent", self) self.eventManager:subscribe ("KeyboardKeyDownEvent", self) self.eventManager:subscribe ("KeyboardKeyUpEvent", self) self.eventManager:subscribe ("MouseButtonDownEvent", self) self.eventManager:subscribe ("MouseButtonUpEvent", self) self.eventManager:subscribe ("ResizeEvent", self) self.bg = love.graphics.newImage("gfx/bg.jpg") self.log = {} self.shipoflife = Ship () self.eventManager:subscribe ("KeyboardKeyDownEvent", self.shipoflife) self.eventManager:subscribe ("KeyboardKeyUpEvent", self.shipoflife) end -- Raises (queues) a new event function Game:raise (event) -- self.eventManager:push (event) end -- Callback used by EventManager function Game:handle (event) -- print ("trying to handle " .. type (event)) if event:getClass () == "MouseButtonUpEvent" then table.insert (self.log, { timestamp = tostring (os.date ("%c")), ttl = 4, tal = 0, message = tostring (event) }) end end -- Updates game logic function Game:onUpdate (dt) -- self.eventManager:update (dt) self.shipoflife:onUpdate (dt) local toberemoved = {} for i, v in pairs (self.log) do if (v.ttl - v.tal) <= 0 then table.insert (toberemoved, i) else v.tal = v.tal + dt end end for i, v in pairs (toberemoved) do table.remove (self.log, v) end end -- Renders stuff onto the screen function Game:onRender () -- local width = love.graphics.getWidth() local height = love.graphics.getHeight() local scaleX = self.bg:getWidth() / width local scaleY = self.bg:getHeight() / height love.graphics.draw(self.bg, 0, 0, 0, scaleX, scaleY) self:renderLog () self.shipoflife:onRender () end -- Gets called when game exits. May be used to do some clean up. function Game:onExit () -- end function Game:renderLog () -- local basepos = {x = 42, y = 42} for i, v in pairs (self.log) do local msg = "[" .. v.timestamp .. "]: " .. v.message local y = basepos.y + (i - 1) * 21 love.graphics.print (msg, basepos.x, y) end end
require ("lib.lclass") require ("src.EventManager") require ("src.data.PositionData") require ("src.events.FocusGainedEvent") require ("src.events.FocusLostEvent") require ("src.events.KeyboardKeyDownEvent") require ("src.events.KeyboardKeyUpEvent") require ("src.events.MouseButtonDownEvent") require ("src.events.MouseButtonUpEvent") require ("src.events.ResizeEvent") require ("src.Ship") class "Game" -- Constructs a new game function Game:Game () -- self.eventManager = EventManager () self.eventManager:subscribe ("FocusGainedEvent", self) self.eventManager:subscribe ("FocusLostEvent", self) self.eventManager:subscribe ("KeyboardKeyDownEvent", self) self.eventManager:subscribe ("KeyboardKeyUpEvent", self) self.eventManager:subscribe ("MouseButtonDownEvent", self) self.eventManager:subscribe ("MouseButtonUpEvent", self) self.eventManager:subscribe ("ResizeEvent", self) self.bg = love.graphics.newImage("gfx/bg.jpg") self.log = {} self.shipoflife = Ship () self.eventManager:subscribe ("KeyboardKeyDownEvent", self.shipoflife) self.eventManager:subscribe ("KeyboardKeyUpEvent", self.shipoflife) end -- Raises (queues) a new event function Game:raise (event) -- self.eventManager:push (event) end -- Callback used by EventManager function Game:handle (event) -- end -- Updates game logic function Game:onUpdate (dt) -- self.eventManager:update (dt) self.shipoflife:onUpdate (dt) end -- Renders stuff onto the screen function Game:onRender () -- local width = love.graphics.getWidth() local height = love.graphics.getHeight() local scaleX = width / self.bg:getWidth() local scaleY = height / self.bg:getHeight() love.graphics.draw(self.bg, 0, 0, 0, scaleX, scaleY) self.shipoflife:onRender () end -- Gets called when game exits. May be used to do some clean up. function Game:onExit () -- end
removed debug messages and fixed bg dimensions
removed debug messages and fixed bg dimensions removed the debug log for mousekey events fixed formular to calculate scale factor for background image depending on the current window size
Lua
mit
BlurryRoots/weltraumsteinekaputtmachen
b880c82bd6cf00de9718b29c2183ffbc5aa73274
Quadtastic/AppLogic.lua
Quadtastic/AppLogic.lua
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function" or self._state.coroutine) local co, ret if self._state.coroutine then -- The coroutine might be running if this was a nested call. -- In this case however we do expect that a function was passed. if coroutine.running() then assert(type(f) == "function") co = coroutine.running() ret = {true, f(self, self._state.data, ...)} else co = self._state.coroutine ret = {coroutine.resume(co, ...)} end else co = coroutine.create(f) ret = {coroutine.resume(co, self, self._state.data, ...)} end -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else if coroutine.status(co) == "dead" then -- Remove dead coroutine self._state.coroutine = nil else assert(co == coroutine.running(), "coroutine wasn't running") end -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 1 then if #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else self._should_quit = true quit(ret[2]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} application._has_active_state_changed = false application._should_quit = false setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return setmetatable({}, {__index = function(_, event) local f = self._state.transitions[event] return function(...) run(self, f, ...) end end}) -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return setmetatable({}, {__index = function(_, event) return function(...) table.insert(self._event_queue[key], {event, {...}}) end end}) else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state if there isn't one already if not self._event_queue[self._state.name] then self._event_queue[self._state.name] = {} end -- Switch states self._state = new_state self._has_active_state_changed = true end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) self._has_active_state_changed = true local statename = self._state.name -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then run(self, nil, ...) end -- Catch up on events that happened for that state while we were in a -- different state, but make sure that states haven't changed since. if self._state.name == statename then local queued_events = self._event_queue[statename] self._event_queue[statename] = nil for _,event_bundle in ipairs(queued_events) do local f = self._state.transitions[event_bundle[1]] run(self, f, unpack(event_bundle[2])) end end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = {state, false} end -- Add the current state table.insert(states, {self._state, true}) return states end function AppLogic.get_current_state(self) return self._state.name end -- Will return true once after each time the active state has changed. function AppLogic.has_active_state_changed(self) local has_changed = self._has_active_state_changed self._has_active_state_changed = false return has_changed end return AppLogic
local unpack = unpack or table.unpack local quit = love.event.quit or os.exit local AppLogic = {} local function run(self, f, ...) assert(type(f) == "function" or self._state.coroutine) local co, ret if self._state.coroutine then -- The coroutine might be running if this was a nested call. -- In this case however we do expect that a function was passed. if coroutine.running() then assert(type(f) == "function") co = coroutine.running() ret = {true, f(self, self._state.data, ...)} else co = self._state.coroutine ret = {coroutine.resume(co, ...)} end else co = coroutine.create(f) self._state.coroutine = co ret = {coroutine.resume(co, self, self._state.data, ...)} end -- Print errors if there are any assert(ret[1], ret[2]) -- If the coroutine yielded then we will issue a state switch based -- on the returned values. if coroutine.status(co) == "suspended" then local new_state = ret[2] -- Save the coroutine so that it can be resumed later self._state.coroutine = co self:push_state(new_state) else if coroutine.status(co) == "dead" then -- Remove dead coroutine self._state.coroutine = nil else assert(co == coroutine.running(), "coroutine wasn't running") end -- If values were returned, then they will be returned to the -- next state higher up in the state stack. -- If this is the only state, then the app will exit with the -- returned integer as exit code. if #ret > 1 then if self._state.coroutine then -- In this case we can return the return values directly return select(2, unpack(ret)) elseif #self._state_stack > 0 then self:pop_state(select(2, unpack(ret))) else self._should_quit = true quit(ret[2]) end end end end setmetatable(AppLogic, { __call = function(_, initial_state) local application = {} application._state = initial_state application._state_stack = {} application._event_queue = {} application._has_active_state_changed = false application._should_quit = false setmetatable(application, { __index = function(self, key) if rawget(AppLogic, key) then return rawget(AppLogic, key) -- If this is a call for the current state, return that state elseif key == self._state.name then -- return a function that executes the command in a subroutine, -- and captures the function's return values return setmetatable({}, {__index = function(_, event) local f = self._state.transitions[event] return function(...) return run(self, f, ...) end end}) -- Otherwise queue that call for later if we have a queue for it elseif self._event_queue[key] then return setmetatable({}, {__index = function(_, event) return function(...) table.insert(self._event_queue[key], {event, {...}}) end end}) else error(string.format("There is no state %s in the current application.", key)) end end }) return application end }) function AppLogic.push_state(self, new_state) assert(string.sub(new_state.name, 1, 1) ~= "_", "State name cannot start with underscore") -- Push the current state onto the state stack table.insert(self._state_stack, self._state) -- Create a new event queue for the pushed state if there isn't one already if not self._event_queue[self._state.name] then self._event_queue[self._state.name] = {} end -- Switch states self._state = new_state self._has_active_state_changed = true end function AppLogic.pop_state(self, ...) -- Return to previous state self._state = table.remove(self._state_stack) self._has_active_state_changed = true local statename = self._state.name -- Resume state's current coroutine with the passed event if self._state.coroutine and coroutine.status(self._state.coroutine) == "suspended" then run(self, nil, ...) end -- Catch up on events that happened for that state while we were in a -- different state, but make sure that states haven't changed since. if self._state.name == statename then local queued_events = self._event_queue[statename] self._event_queue[statename] = nil for _,event_bundle in ipairs(queued_events) do local f = self._state.transitions[event_bundle[1]] run(self, f, unpack(event_bundle[2])) end end end function AppLogic.get_states(self) local states = {} for i,state in ipairs(self._state_stack) do states[i] = {state, false} end -- Add the current state table.insert(states, {self._state, true}) return states end function AppLogic.get_current_state(self) return self._state.name end -- Will return true once after each time the active state has changed. function AppLogic.has_active_state_changed(self) local has_changed = self._has_active_state_changed self._has_active_state_changed = false return has_changed end return AppLogic
Fix bug in app logic where nested calls would not produce return values
Fix bug in app logic where nested calls would not produce return values
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
0e2c090e9205bc2f9fefe2bf150b7d38f47e04a3
xmake/rules/utils/inherit_links/inherit_links.lua
xmake/rules/utils/inherit_links/inherit_links.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file inherit_links.lua -- -- add values from target options function _add_values_from_targetopts(values, target, name) for _, opt in ipairs(target:orderopts()) do table.join2(values, table.wrap(opt:get(name))) end end -- add values from target packages function _add_values_from_targetpkgs(values, target, name) for _, pkg in ipairs(target:orderpkgs()) do -- uses them instead of the builtin configs if exists extra package config -- e.g. `add_packages("xxx", {links = "xxx"})` local configinfo = target:pkgconfig(pkg:name()) if configinfo and configinfo[name] then table.join2(values, configinfo[name]) else -- uses the builtin package configs table.join2(values, pkg:get(name)) end end end -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) _add_values_from_targetopts(values, target, name) _add_values_from_targetpkgs(values, target, name) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then target:add(name, values, {public = true}) end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file inherit_links.lua -- -- add values from target options function _add_values_from_targetopts(values, target, name) for _, opt in ipairs(target:orderopts()) do table.join2(values, table.wrap(opt:get(name))) end end -- add values from target packages function _add_values_from_targetpkgs(values, target, name) for _, pkg in ipairs(target:orderpkgs()) do -- uses them instead of the builtin configs if exists extra package config -- e.g. `add_packages("xxx", {links = "xxx"})` local configinfo = target:pkgconfig(pkg:name()) if configinfo and configinfo[name] then table.join2(values, configinfo[name]) else -- uses the builtin package configs table.join2(values, pkg:get(name)) end end end -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) _add_values_from_targetopts(values, target, name) _add_values_from_targetpkgs(values, target, name) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then target:add(name, values, {public = true}) end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do if dep:targetkind() == "shared" then local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end end
fix inherit links
fix inherit links
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
629ef25d711a5cb837d16826d2aef63035b0fdf8
boss.lua
boss.lua
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local BOSSES = { -- The Obsidian Sanctum [28860] = "Sartharion", -- Eye of Eternity [28859] = "Malygos", -- Naxxramas [15956] = "Anub'Rekhan", [15953] = "Grand Widow Faerlina", [15952] = "Maexxna", [16028] = "Patchwerk", [15931] = "Grobbulus", [15932] = "Gluth", [15928] = "Thaddius", [16061] = "Instructor Razuvious", [16060] = "Gothik the Harvester", -- TODO(alkis): Add Four Horsemen [15954] = "Noth the Plaguebringer", [15936] = "Heigan the Unclean", [16011] = "Loatheb", [15989] = "Sapphiron", [15990] = "Kel'Thuzad", -- Vault of Archavon [31125] = "Archavon the Stone Watcher", [33993] = "Emalon the Storm Watcher", -- Ulduar [33113] = "Flame Leviathan", [33118] = "Ignis the Furnace Master", [33186] = "Razorscale", [33293] = "XT-002 Deconstructor", -- TODO(alkis): Add Assembly of Iron [32930] = "Kologarn", [33515] = "Auriaya", [33412] = "Mimiron", [32845] = "Hodir", [32865] = "Thorim", [32906] = "Freya", [33271] = "General Vezax", [33288] = "Yogg-Saron", -- TODO(alkis): Add Algalon the Observer } local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name, timestamp, event, source, source_name, source_flags, dest, dest_name, dest_flags, ...) -- bitlib does not support 64 bit integers so we are going to do some -- string hacking to get what we want. For an NPC: -- guid & 0x00F0000000000000 == 3 -- and the NPC id is: -- (guid & 0x0000FFFFFF000000) >> 24 if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then local npc_id = tonumber(string.sub(dest, -12, -7), 16) if BOSSES[npc_id] then self:SendMessage("BossKilled", dest_name, "kill") end end end local in_combat = false local award_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopAwardQueue(event_name) if in_combat then return end if #award_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end if StaticPopup_Visible("EPGP_BOSS_DEAD") or StaticPopup_Visible("EPGP_BOSS_ATTEMPT") then return end local boss_name = table.remove(award_queue, 1) local dialog if event_name == "kill" then dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name) elseif event_name == "wipe" and mod.db.profile.wipedetection then dialog = StaticPopup_Show("EPGP_BOSS_ATTEMPT", boss_name) end if dialog then dialog.reason = boss_name end end local function BossAttempt(event_name, boss_name) Debug("Boss attempt: %s (%s)", boss_name, event_name) -- Temporary fix since we cannot unregister DBM callbacks if not mod:IsEnabled() then return end if CanEditOfficerNote() and IsRLorML() then tinsert(award_queue, boss_name) if not timer then timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 0.1, event_name) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:DebugTest() BossKilled("BossKilled", "Sapphiron") end mod.dbDefaults = { profile = { enabled = false, wipedetection = false, }, } mod.optionsName = L["Boss"] mod.optionsDesc = L["Automatic boss tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] }, wipedetection = { type = "toggle", name = L["Wipe awards"], desc = L["Awards for wipes on bosses. Requires Deadly Boss Mods"], order = 2, disabled = function(v) return not DBM end, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") if DBM then EPGP:Print(L["Using DBM for boss kill tracking"]) DBM:RegisterCallback("kill", function (mod) BossAttempt("kill", mod.combatInfo.name) end) DBM:RegisterCallback("wipe", function (mod) BossAttempt("wipe", mod.combatInfo.name) end) else self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("BossKilled", BossAttempt) end end
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local BOSSES = { -- The Obsidian Sanctum [28860] = "Sartharion", -- Eye of Eternity [28859] = "Malygos", -- Naxxramas [15956] = "Anub'Rekhan", [15953] = "Grand Widow Faerlina", [15952] = "Maexxna", [16028] = "Patchwerk", [15931] = "Grobbulus", [15932] = "Gluth", [15928] = "Thaddius", [16061] = "Instructor Razuvious", [16060] = "Gothik the Harvester", -- TODO(alkis): Add Four Horsemen [15954] = "Noth the Plaguebringer", [15936] = "Heigan the Unclean", [16011] = "Loatheb", [15989] = "Sapphiron", [15990] = "Kel'Thuzad", -- Vault of Archavon [31125] = "Archavon the Stone Watcher", [33993] = "Emalon the Storm Watcher", -- Ulduar [33113] = "Flame Leviathan", [33118] = "Ignis the Furnace Master", [33186] = "Razorscale", [33293] = "XT-002 Deconstructor", -- TODO(alkis): Add Assembly of Iron [32930] = "Kologarn", [33515] = "Auriaya", [33412] = "Mimiron", [32845] = "Hodir", [32865] = "Thorim", [32906] = "Freya", [33271] = "General Vezax", [33288] = "Yogg-Saron", -- TODO(alkis): Add Algalon the Observer } local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name, timestamp, event, source, source_name, source_flags, dest, dest_name, dest_flags, ...) -- bitlib does not support 64 bit integers so we are going to do some -- string hacking to get what we want. For an NPC: -- guid & 0x00F0000000000000 == 3 -- and the NPC id is: -- (guid & 0x0000FFFFFF000000) >> 24 if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then local npc_id = tonumber(string.sub(dest, -12, -7), 16) if BOSSES[npc_id] then self:SendMessage("BossKilled", dest_name, "kill") end end end local in_combat = false local award_queue = {} local timer function mod:PopAwardQueue(event_name) if in_combat then return end if #award_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end if StaticPopup_Visible("EPGP_BOSS_DEAD") or StaticPopup_Visible("EPGP_BOSS_ATTEMPT") then return end local boss_name = table.remove(award_queue, 1) local dialog if event_name == "kill" then dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name) elseif event_name == "wipe" and mod.db.profile.wipedetection then dialog = StaticPopup_Show("EPGP_BOSS_ATTEMPT", boss_name) end if dialog then dialog.reason = boss_name end end local function BossAttempt(event_name, boss_name) Debug("Boss attempt: %s (%s)", boss_name, event_name) -- Temporary fix since we cannot unregister DBM callbacks if not mod:IsEnabled() then return end if CanEditOfficerNote() and IsRLorML() then tinsert(award_queue, boss_name) if not timer then timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 0.1, event_name) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:DebugTest() BossKilled("BossKilled", "Sapphiron") end mod.dbDefaults = { profile = { enabled = false, wipedetection = false, }, } mod.optionsName = L["Boss"] mod.optionsDesc = L["Automatic boss tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] }, wipedetection = { type = "toggle", name = L["Wipe awards"], desc = L["Awards for wipes on bosses. Requires Deadly Boss Mods"], order = 2, disabled = function(v) return not DBM end, }, } local function dbmCallback(event, mod) return BossAttempt(event, mod.combatInfo.name) end function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") if DBM then EPGP:Print(L["Using DBM for boss kill tracking"]) DBM:RegisterCallback("kill", dbmCallback) DBM:RegisterCallback("wipe", dbmCallback) else self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("BossKilled", BossAttempt) end end
Changes for DBM API changes.
Changes for DBM API changes. Fixes issue 513.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,sheldon/epgp,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded
8ff88fcd852ccc6184abe94898b571605bfb888e
libs/sys/luasrc/sys/mtdow.lua
libs/sys/luasrc/sys/mtdow.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtdblock" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('([%w-_]+):.*-"%s"' % mtdname) if k then return prefix..k end end end function Write._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.SAFEMTD, appendfile, devicename, self.IMAGEFIFO } ) end function Writer._refresh_block(self, devicename) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) return os.execute("%s refresh '%s'" % {self.SAFEMTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.SAFEMTD, erase, appendfile, devicename } ) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local io = require "io" local os = require "os" local fs = require "luci.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local posix = require "posix" local type, assert, error = type, assert, error module "luci.sys.mtdow" WRITE_IMAGE = 0 WRITE_COMBINED = 1 WRITE_EMULATED = 2 ERROR_INTERNAL = 1 ERROR_NOTFOUND = 2 ERROR_RESOURCE = 3 ERROR_NODETECT = 4 ERROR_NOTAVAIL = 5 ERROR_NOSTREAM = 6 ERROR_INVMAGIC = 7 Writer = util.class() -- x86 EmulatedWriter = util.class(Writer) EmulatedWriter.blocks = { image = { magic = "eb48", device = "/dev/hda", write = WRITE_SEPARATELY } } function EmulatedWriter.write_block(self, name, imagestream, appendpattern) if appendpattern then os.execute("grep rootfs /proc/mtd >/dev/null || " .. "{ echo /dev/hda2,65536,rootfs > " .. "/sys/module/block2mtd/parameters/block2mtd }") end return Writer.write_block(self, name, imagestream, appendpattern) end -- Broadcom CFEWriter = util.class(Writer) CFEWriter.blocks = { image = { magic = {"4844", "5735"}, device = "linux", write = WRITE_COMBINED } } -- Magicbox CommonWriter = util.class(Writer) CommonWriter.blocks = { image = { device = "linux", write = WRITE_COMBINED } } -- Atheros RedWriter = util.class(Writer) RedWriter.blocks = { kernel = { device = "vmlinux.bin.l7", write = WRITE_IMAGE }, rootfs = { device = "rootfs", write = WRITE_COMBINED } } -- Auto Detect function native_writer() local w = Writer() -- Detect amd64 / x86 local x86 = {"x86_64", "i386", "i486", "i586", "i686"} if util.contains(x86, posix.uname("%m")) then return EmulatedWriter() end -- Detect CFE if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then return CFEWriter() end -- Detect Redboot if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then return RedWriter() end -- Detect MagicBox if fs.readfile("/proc/cpuinfo"):find("MagicBox") then return CommonWriter() end end Writer.MTD = "/sbin/mtd" Writer.SAFEMTD = "/tmp/mtd" Writer.IMAGEFIFO = "/tmp/mtdimage.fifo" function Writer.write_block(self, name, imagestream, appendfile) assert(self.blocks[name], ERROR_NOTFOUND) local block = self.blocks[name] local device = block.device device = fs.stat(device) and device or self:_find_mtdblock(device) assert(device, ERROR_NODETECT) if block.magic then imagestream = self:_check_magic(imagestream, block.magic) end assert(imagestream, ERROR_INVMAGIC) if appendfile then if block.write == WRITE_COMBINED then return (self:_write_combined(device, imagestream, appendfile) == 0) elseif block.write == WRITE_EMULATED then return (self:_write_emulated(device, imagestream, appendfile) == 0) else error(ERROR_NOTAVAIL) end else return (self:_write_memory(device, imagestream) == 0) end end function Writer._check_magic(self, imagestream, magic) magic = type(magic) == "table" and magic or {magic} local block = imagestream() assert(block, ERROR_NOSTREAM) local cm = "%x%x" % {block:byte(1), block:byte(2)} if util.contains(magic, cm) then return ltn12.source.cat(ltn12.source.string(block), imagestream) end end function Writer._find_mtdblock(self, mtdname) local k local prefix = "/dev/mtd" prefix = prefix .. (fs.stat(prefix) and "/" or "") for l in io.lines("/proc/mtd") do local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname) if k then return prefix..k end end end function Writer._write_emulated(self, devicename, imagestream, appendfile) local stat = (self:_write_memory(device, imagestream) == 0) stat = stat and (self:_refresh_block("rootfs") == 0) local squash = self:_find_mtdblock("rootfs_data") if squash then stat = stat and (self:_append("rootfs_data", imagestream, true) == 0) else stat = stat and (self:_append("rootfs", imagestream) == 0) end return stat end function Writer._write_memory(self, devicename, imagestream) local devicestream = ltn12.sink.file(io.open(devicename, "w")) local stat, err = ltn12.pump.all(imagestream, devicestream) if stat then return os.execute("sync") end end function Writer._write_combined(self, devicename, imagestream, appendfile) local imageproc = posix.fork() assert(imageproc ~= -1, ERROR_RESOURCE) if imageproc == 0 then fs.unlink(self.IMAGEFIFO) assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE) local imagefifo = io.open(self.IMAGEFIFO, "w") assert(imagefifo, ERROR_RESOURCE) ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo)) os.exit(0) end return os.execute( "%s -j '%s' write '%s' '%s'" % { self.MTD, appendfile, self.IMAGEFIFO, devicename } ) end function Writer._refresh_block(self, devicename) return os.execute("%s refresh '%s'" % {self.MTD, devicename}) end function Writer._append(self, devicename, appendfile, erase) erase = erase and ("-e '%s' " % devicename) or '' return os.execute( "%s %s jffs2write '%s' '%s'" % { self.MTD, erase, appendfile, devicename } ) end
mtdow fixes level 1
mtdow fixes level 1
Lua
apache-2.0
Sakura-Winkey/LuCI,wongsyrone/luci-1,Kyklas/luci-proto-hso,bright-things/ionic-luci,openwrt/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,slayerrensky/luci,obsy/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,mumuqz/luci,urueedi/luci,Noltari/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,sujeet14108/luci,florian-shellfire/luci,urueedi/luci,RuiChen1113/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,oyido/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,teslamint/luci,hnyman/luci,NeoRaider/luci,lcf258/openwrtcn,hnyman/luci,oneru/luci,dismantl/luci-0.12,ff94315/luci-1,hnyman/luci,cappiewu/luci,jlopenwrtluci/luci,kuoruan/lede-luci,joaofvieira/luci,MinFu/luci,teslamint/luci,forward619/luci,cappiewu/luci,981213/luci-1,bright-things/ionic-luci,LuttyYang/luci,david-xiao/luci,shangjiyu/luci-with-extra,Noltari/luci,cshore/luci,marcel-sch/luci,sujeet14108/luci,mumuqz/luci,aa65535/luci,jorgifumi/luci,forward619/luci,forward619/luci,opentechinstitute/luci,cshore/luci,jlopenwrtluci/luci,bittorf/luci,jlopenwrtluci/luci,jchuang1977/luci-1,keyidadi/luci,RuiChen1113/luci,thesabbir/luci,RuiChen1113/luci,kuoruan/luci,chris5560/openwrt-luci,jorgifumi/luci,taiha/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,daofeng2015/luci,bright-things/ionic-luci,LuttyYang/luci,remakeelectric/luci,sujeet14108/luci,obsy/luci,taiha/luci,urueedi/luci,rogerpueyo/luci,tobiaswaldvogel/luci,maxrio/luci981213,Wedmer/luci,thesabbir/luci,dwmw2/luci,NeoRaider/luci,Sakura-Winkey/LuCI,Hostle/luci,nmav/luci,MinFu/luci,MinFu/luci,schidler/ionic-luci,tcatm/luci,harveyhu2012/luci,thess/OpenWrt-luci,openwrt/luci,palmettos/test,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,jchuang1977/luci-1,palmettos/cnLuCI,wongsyrone/luci-1,ollie27/openwrt_luci,Wedmer/luci,mumuqz/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,tobiaswaldvogel/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,chris5560/openwrt-luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,deepak78/new-luci,nmav/luci,dismantl/luci-0.12,rogerpueyo/luci,bright-things/ionic-luci,Hostle/luci,opentechinstitute/luci,artynet/luci,shangjiyu/luci-with-extra,bittorf/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,kuoruan/luci,Hostle/openwrt-luci-multi-user,palmettos/test,RuiChen1113/luci,shangjiyu/luci-with-extra,RuiChen1113/luci,Wedmer/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,oyido/luci,deepak78/new-luci,remakeelectric/luci,sujeet14108/luci,artynet/luci,urueedi/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,lbthomsen/openwrt-luci,openwrt/luci,artynet/luci,slayerrensky/luci,obsy/luci,thesabbir/luci,nmav/luci,schidler/ionic-luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,LuttyYang/luci,kuoruan/lede-luci,Hostle/openwrt-luci-multi-user,taiha/luci,jlopenwrtluci/luci,oyido/luci,lcf258/openwrtcn,bittorf/luci,thess/OpenWrt-luci,nmav/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,lcf258/openwrtcn,openwrt/luci,NeoRaider/luci,artynet/luci,ollie27/openwrt_luci,maxrio/luci981213,bittorf/luci,Noltari/luci,openwrt/luci,artynet/luci,forward619/luci,chris5560/openwrt-luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,taiha/luci,jorgifumi/luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,joaofvieira/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,MinFu/luci,remakeelectric/luci,LuttyYang/luci,oneru/luci,david-xiao/luci,lbthomsen/openwrt-luci,teslamint/luci,palmettos/test,keyidadi/luci,Kyklas/luci-proto-hso,artynet/luci,cappiewu/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,cappiewu/luci,nwf/openwrt-luci,marcel-sch/luci,lcf258/openwrtcn,tcatm/luci,deepak78/new-luci,Kyklas/luci-proto-hso,david-xiao/luci,ff94315/luci-1,nwf/openwrt-luci,openwrt-es/openwrt-luci,Noltari/luci,Wedmer/luci,aa65535/luci,aa65535/luci,forward619/luci,tcatm/luci,NeoRaider/luci,chris5560/openwrt-luci,ff94315/luci-1,nmav/luci,tcatm/luci,male-puppies/luci,teslamint/luci,florian-shellfire/luci,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,fkooman/luci,oyido/luci,oneru/luci,slayerrensky/luci,openwrt/luci,981213/luci-1,thesabbir/luci,Sakura-Winkey/LuCI,nmav/luci,RuiChen1113/luci,male-puppies/luci,schidler/ionic-luci,urueedi/luci,urueedi/luci,deepak78/new-luci,florian-shellfire/luci,lcf258/openwrtcn,teslamint/luci,keyidadi/luci,hnyman/luci,thess/OpenWrt-luci,zhaoxx063/luci,dwmw2/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,981213/luci-1,lbthomsen/openwrt-luci,kuoruan/luci,shangjiyu/luci-with-extra,rogerpueyo/luci,Hostle/luci,daofeng2015/luci,oyido/luci,jchuang1977/luci-1,hnyman/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,Hostle/luci,openwrt-es/openwrt-luci,kuoruan/luci,palmettos/test,Hostle/openwrt-luci-multi-user,dwmw2/luci,daofeng2015/luci,hnyman/luci,harveyhu2012/luci,chris5560/openwrt-luci,harveyhu2012/luci,981213/luci-1,wongsyrone/luci-1,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,joaofvieira/luci,NeoRaider/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,bittorf/luci,oyido/luci,openwrt-es/openwrt-luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,jorgifumi/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,nwf/openwrt-luci,dismantl/luci-0.12,ollie27/openwrt_luci,opentechinstitute/luci,palmettos/test,artynet/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,forward619/luci,maxrio/luci981213,LuttyYang/luci,keyidadi/luci,palmettos/cnLuCI,david-xiao/luci,Kyklas/luci-proto-hso,Wedmer/luci,jchuang1977/luci-1,harveyhu2012/luci,slayerrensky/luci,Noltari/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,joaofvieira/luci,openwrt/luci,schidler/ionic-luci,zhaoxx063/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,Hostle/luci,jlopenwrtluci/luci,wongsyrone/luci-1,Wedmer/luci,nwf/openwrt-luci,mumuqz/luci,tcatm/luci,palmettos/test,bittorf/luci,shangjiyu/luci-with-extra,remakeelectric/luci,Wedmer/luci,male-puppies/luci,keyidadi/luci,hnyman/luci,fkooman/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,taiha/luci,aa65535/luci,Noltari/luci,RuiChen1113/luci,kuoruan/lede-luci,marcel-sch/luci,deepak78/new-luci,daofeng2015/luci,florian-shellfire/luci,dismantl/luci-0.12,marcel-sch/luci,david-xiao/luci,daofeng2015/luci,artynet/luci,cappiewu/luci,urueedi/luci,ff94315/luci-1,teslamint/luci,aa65535/luci,florian-shellfire/luci,urueedi/luci,lcf258/openwrtcn,palmettos/cnLuCI,nmav/luci,bright-things/ionic-luci,Noltari/luci,dwmw2/luci,opentechinstitute/luci,wongsyrone/luci-1,aa65535/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,bittorf/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,obsy/luci,schidler/ionic-luci,fkooman/luci,slayerrensky/luci,thesabbir/luci,mumuqz/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,lbthomsen/openwrt-luci,dwmw2/luci,aa65535/luci,MinFu/luci,bittorf/luci,maxrio/luci981213,lbthomsen/openwrt-luci,keyidadi/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,palmettos/cnLuCI,marcel-sch/luci,981213/luci-1,marcel-sch/luci,ff94315/luci-1,oneru/luci,oneru/luci,mumuqz/luci,jlopenwrtluci/luci,oneru/luci,palmettos/test,nwf/openwrt-luci,florian-shellfire/luci,mumuqz/luci,fkooman/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,oyido/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,zhaoxx063/luci,daofeng2015/luci,MinFu/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,taiha/luci,keyidadi/luci,male-puppies/luci,tcatm/luci,marcel-sch/luci,taiha/luci,rogerpueyo/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,MinFu/luci,palmettos/cnLuCI,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,sujeet14108/luci,david-xiao/luci,kuoruan/lede-luci,palmettos/test,cshore/luci,jchuang1977/luci-1,thess/OpenWrt-luci,taiha/luci,openwrt-es/openwrt-luci,male-puppies/luci,harveyhu2012/luci,cshore/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,marcel-sch/luci,david-xiao/luci,cshore/luci,obsy/luci,tcatm/luci,slayerrensky/luci,kuoruan/lede-luci,keyidadi/luci,wongsyrone/luci-1,rogerpueyo/luci,forward619/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,ollie27/openwrt_luci,opentechinstitute/luci,lcf258/openwrtcn,joaofvieira/luci,dwmw2/luci,ollie27/openwrt_luci,Hostle/luci,hnyman/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,jorgifumi/luci,tcatm/luci,opentechinstitute/luci,slayerrensky/luci,jorgifumi/luci,lcf258/openwrtcn,obsy/luci,wongsyrone/luci-1,Kyklas/luci-proto-hso,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,Sakura-Winkey/LuCI,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,Sakura-Winkey/LuCI,forward619/luci,palmettos/cnLuCI,mumuqz/luci,cappiewu/luci,jchuang1977/luci-1,remakeelectric/luci,opentechinstitute/luci,Wedmer/luci,LuttyYang/luci,aa65535/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,nwf/openwrt-luci,thess/OpenWrt-luci,joaofvieira/luci,fkooman/luci,jorgifumi/luci,deepak78/new-luci,NeoRaider/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,cshore/luci,ollie27/openwrt_luci,zhaoxx063/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,jorgifumi/luci,thess/OpenWrt-luci,schidler/ionic-luci,bright-things/ionic-luci,obsy/luci,maxrio/luci981213,rogerpueyo/luci,openwrt/luci,teslamint/luci,LuttyYang/luci,MinFu/luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,male-puppies/luci,Hostle/luci,cappiewu/luci,schidler/ionic-luci,florian-shellfire/luci,oyido/luci,remakeelectric/luci,palmettos/cnLuCI,Noltari/luci,daofeng2015/luci,ff94315/luci-1,fkooman/luci,male-puppies/luci,dismantl/luci-0.12,joaofvieira/luci,LuttyYang/luci,fkooman/luci,obsy/luci,ff94315/luci-1,chris5560/openwrt-luci,kuoruan/lede-luci,artynet/luci
f0b090516f130b291407755d494b1f7b18f85c96
hammerspoon/init.lua
hammerspoon/init.lua
-- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") -- define sizes of the 'large' vs 'small' left/right sections small = 0.4 large = 0.6 -- left small hs.hotkey.bind({"alt", "ctrl"}, "U", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * small f.h = max.h win:setFrame(f) end) -- left large hs.hotkey.bind({"alt", "ctrl"}, "I", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * large f.h = max.h win:setFrame(f) end) -- right large hs.hotkey.bind({"alt", "ctrl"}, "O", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w * small) f.y = max.y f.w = max.w * large f.h = max.h win:setFrame(f) end) -- right small hs.hotkey.bind({"alt", "ctrl"}, "P", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.y = max.y f.w = max.w * small f.h = max.h win:setFrame(f) end) -- upper right small hs.hotkey.bind({"alt", "ctrl"}, ";", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + large * max.w f.y = max.y f.w = max.w * small f.h = max.h / 2 win:setFrame(f) end) -- lower right small hs.hotkey.bind({"alt", "ctrl"}, "l", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + large * max.w f.y = max.y + max.h / 2 f.w = max.w * small f.h = max.h / 2 win:setFrame(f) end) -- full screen hs.hotkey.bind({"alt", "ctrl"}, "m", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end) -- half left hs.hotkey.bind({"alt", "ctrl"}, "j", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- half right hs.hotkey.bind({"alt", "ctrl"}, "k", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + max.w / 2 f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end)
-- reload config hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Config loaded") -- define sizes of the 'large' vs 'small' left/right sections small = 0.4 large = 0.6 -- left small hs.hotkey.bind({"alt", "ctrl"}, "U", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * small f.h = max.h win:setFrame(f) end) -- left large hs.hotkey.bind({"alt", "ctrl"}, "I", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w * large f.h = max.h win:setFrame(f) end) -- right large hs.hotkey.bind({"alt", "ctrl"}, "O", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w * small) f.y = max.y f.w = max.w * large f.h = max.h win:setFrame(f) end) -- right small hs.hotkey.bind({"alt", "ctrl"}, "P", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.w - (max.w * small) f.y = max.y f.w = max.w * small f.h = max.h win:setFrame(f) end) -- upper right small hs.hotkey.bind({"alt", "ctrl"}, ";", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + large * max.w f.y = max.y f.w = max.w * small f.h = max.h / 2 win:setFrame(f) end) -- lower right small hs.hotkey.bind({"alt", "ctrl"}, "l", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + large * max.w f.y = max.y + max.h / 2 f.w = max.w * small f.h = max.h / 2 win:setFrame(f) end) -- full screen hs.hotkey.bind({"alt", "ctrl"}, "m", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end) -- half left hs.hotkey.bind({"alt", "ctrl"}, "j", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- half right hs.hotkey.bind({"alt", "ctrl"}, "k", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + max.w / 2 f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end)
fix right-small
fix right-small
Lua
mit
paul-krohn/configs
45b2b40e52ac35aa382ef99b72817834554aeb0a
src/rava.lua
src/rava.lua
local bcsave = require("libs/bcsave").start local preHooks = {} local postHooks = {} local maincode local mainobj local objs = {} local rava = {} -- check if file exists local function fileExists(file) if file then local f = io.open(file,"r") if f ~= nil then io.close(f) return true else return false end end end -- run Hooks local function callHooks(hooks, ...) for i=1, #hooks do hooks[i](...) end end local function addHook(hooks, fn) for i = 1, #hooks do if hooks[i] == fn then return false end end table.insert(hooks, fn) return true end -- call through pipe to generate local function generateCodeObject(path, name) local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$") local objpath = path local leavesym = "" name = name or (dir:gsub("^%./",""):gsub("^/",""):gsub("/",".") .. file:gsub("%.lua$","")) -- First file we add is always main if mainobj == nil then name = "main" mainobj = true end -- Run preprocessors on file callHooks(preHooks, path) -- generate lua object if path:match("%.lua$") then if (not opt.flag("n")) then -- load code to check it for errors local fn, err = loadstring(rava.code[path]) -- die on syntax errors if not fn then msg.fatal(err) end end -- check for leave symbols flag if opt.flag("g") then leavesym = "-g" end objpath = path..".o" msg.info("Chunk '"..name.."' in "..objpath) -- create CC line local f = io.popen(string.format( "%s -q %s --generate=%s %s %s", RAVABIN, leavesym, name, "-", objpath),"w") -- write code to generator f:write(rava.code[path]) f:close() msg.done() end -- add object if name == "main" then mainobj = objpath else table.insert(objs, objpath) end --reclame memory (probably overkill in most cases) rava.code[path] = true return objpath end -- list files in a directory function rava.scandir(dir) local r = {} for file in io.popen("ls -a '"..dir.."'"):lines() do table.insert(r, file) end return r end -- Add PreHooks to filter input function rava.addPreHook(fn) return addHook(preHooks, fn) end -- Add PostHooks to futher process output function rava.addPostHook(fn) return addHook(postHooks, fn) end -- Add files to the rava compiler function rava.addFile(...) local arg = {...} for i=1, #arg do local file = arg[i] if rava.code[file] then break elseif not fileExists(file) then msg.warning("File not found: "..file) break elseif file:match("%.lua$") then msg.info("Loading "..file) local f, err = io.open(file,"r") if err then msg.fatal(err) end rava.code[file] = f:read("*all") f:close() msg.done() end generateCodeObject(file) end end -- Add a string to the rava compiler function rava.addString(name, code) rava.code[name] = code generateCodeObject(name, name) end -- Evaluate code to run in realtime function rava.eval(...) local arg = {...} local chunk = "" for x = 1, #arg do chunk = chunk.."\n"..arg[x] end local fn=loadstring(chunk) fn() end -- Execute external files function rava.exec(...) local arg = {...} for x = 1, #arg do dofile(arg[x]) end end -- Compile the rava object state to binary function rava.compile(binary, ...) -- make sure we have a name if binary == true then binary = "rava" end --load Lua Code rava.addFile(...) msg.info("Compiling Binary... ") local f, err = io.open(binary..".a", "w+") local files = require("ravastore") f:write(files["rava.a"]) f:close() local cinit = string.format([[ %s -O%s -Wall -Wl,-E \ -x none %s -x none %s \ %s \ -o %s -lm -ldl -flto ]], os.getenv("CC") or "gcc", OPLEVEL, "rava.a", mainobj, os.getenv("CCARGS").." "..table.concat(objs, " "), binary) msg.warning(cinit) os.execute(cinit) -- run PostHooks callHooks(postHooks, binary) print("\n") end -- Generate an object file from lua files function rava.generate(name, ...) local arg = {...} local calls = {} if name ~= true then table.insert(calls, "-n") table.insert(calls, name) end for i = 1, #arg do table.insert(calls, arg[i]) end bcsave(unpack(calls)) end -- Generate binary data store function rava.store(variable, store, ...) -- open store local out = io.open(store, "w+") local files = {...} variable = variable or "files" out:write("local "..variable.." = {}\n") for path in files do local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$") local data = f:read("*all") local ins = io.open(path, "r") if not ins then msg.fatal("Error reading " .. path) end ins:close() out:write(variable..'["'..dir:gsub("^%./",""):gsub("^/","")..file..'"] = "') for i = 1, #data do out:write(string.format("\\%i", string.byte(data, i))) end out:write('"\n') end out:write('"\nmodule(...)\n') out:write('return '..variable) out:close() bcsave(store, store..".o") end -- code repository rava.code = {} module(...) return rava
local bcsave = require("libs/bcsave").start local preHooks = {} local postHooks = {} local maincode local mainobj local objs = {} local rava = {} -- check if file exists local function fileExists(file) if file then local f = io.open(file,"r") if f ~= nil then io.close(f) return true else return false end end end -- run Hooks local function callHooks(hooks, ...) for i=1, #hooks do hooks[i](...) end end local function addHook(hooks, fn) for i = 1, #hooks do if hooks[i] == fn then return false end end table.insert(hooks, fn) return true end -- call through pipe to generate local function generateCodeObject(path, name) local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$") local objpath = path local leavesym = "" name = name or (dir:gsub("^%./",""):gsub("^/",""):gsub("/",".") .. file:gsub("%.lua$","")) -- First file we add is always main if mainobj == nil then name = "main" mainobj = true end -- Run preprocessors on file callHooks(preHooks, path) -- generate lua object if path:match("%.lua$") then if (not opt.flag("n")) then -- load code to check it for errors local fn, err = loadstring(rava.code[path]) -- die on syntax errors if not fn then msg.fatal(err) end end -- check for leave symbols flag if opt.flag("g") then leavesym = "-g" end objpath = path..".o" msg.info("Chunk '"..name.."' in "..objpath) -- create CC line local f = io.popen(string.format( "%s -q %s --generate=%s %s %s", RAVABIN, leavesym, name, "-", objpath),"w") -- write code to generator f:write(rava.code[path]) f:close() msg.done() end -- add object if name == "main" then mainobj = objpath else table.insert(objs, objpath) end --reclame memory (probably overkill in most cases) rava.code[path] = true return objpath end -- list files in a directory function rava.scandir(dir) local r = {} for file in io.popen("ls -a '"..dir.."'"):lines() do table.insert(r, file) end return r end -- Add PreHooks to filter input function rava.addPreHook(fn) return addHook(preHooks, fn) end -- Add PostHooks to futher process output function rava.addPostHook(fn) return addHook(postHooks, fn) end -- Add files to the rava compiler function rava.addFile(...) local arg = {...} for i=1, #arg do local file = arg[i] if rava.code[file] then break elseif not fileExists(file) then msg.warning("Failed to add module: "..file) if #file > 10 then end break elseif file:match("%.lua$") then msg.info("Loading "..file) local f, err = io.open(file,"r") if err then msg.fatal(err) end rava.code[file] = f:read("*all") f:close() msg.done() end generateCodeObject(file) end end -- Add a string to the rava compiler function rava.addString(name, code) rava.code[name] = code generateCodeObject(name, name) end -- Evaluate code to run in realtime function rava.eval(...) local arg = {...} local chunk = "" for x = 1, #arg do chunk = chunk.."\n"..arg[x] end local fn=loadstring(chunk) fn() end -- Execute external files function rava.exec(...) local arg = {...} for x = 1, #arg do dofile(arg[x]) end end -- Generate binary data store function rava.store(variable, store, ...) -- open store local out = io.open(store:gsub("%..+$", "")..".lua", "w+") local files = {...} -- make sure variable is set variable = variable or "files" -- start variable out:write("local "..variable.." = {}\n") -- loop through files for _, path in pairs(files) do local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$") local ins = io.open(path, "r") local data = ins:read("*all") if not ins then msg.fatal("Error reading " .. path) end ins:close() out:write(variable..'["'..dir:gsub("^%./", ""):gsub("^/", "")..file..'"] = "') for i = 1, #data do out:write(string.format("\\%i", string.byte(data, i))) end out:write('"\n') end out:write('\nmodule(...)\n') out:write('return '..variable) out:close() bcsave( store:gsub("%..+$", "")..".lua", store:gsub("%..+$", "")..".o") end -- Compile the rava object state to binary function rava.compile(binary, ...) -- make sure we have a name if binary == true then binary = "rava" end --load Lua Code rava.addFile(...) msg.info("Compiling Binary... ") local f, err = io.open(binary..".a", "w+") local files = require("libs/ravastore") f:write(files["libs/rava.a"]) f:close() -- Construct compiler call local ccall = string.format([[ %s -O%s -Wall -Wl,-E \ -x none %s -x none %s \ %s \ -o %s -lm -ldl -flto ]], os.getenv("CC") or "gcc", OPLEVEL, binary..".a", mainobj, os.getenv("CCARGS").." "..table.concat(objs, " "), binary) -- Call compiler msg.warning(ccall) os.execute(ccall) -- run PostHooks callHooks(postHooks, binary) print("\n") end -- Generate an object file from lua files function rava.generate(name, ...) local arg = {...} local calls = {} if name ~= true then table.insert(calls, "-n") table.insert(calls, name) end for i = 1, #arg do table.insert(calls, arg[i]) end bcsave(unpack(calls)) end -- code repository rava.code = {} module(...) return rava
fixed bad references in compile
fixed bad references in compile
Lua
mit
frinknet/rava,frinknet/rava,frinknet/rava
1426fb02e296ea6996d3d23e45d12748b9ec2ee7
vsandroid_androidproj.lua
vsandroid_androidproj.lua
-- -- android/vsandroid_androidproj.lua -- vs-android integration for vstudio. -- Copyright (c) 2012-2015 Manu Evans and the Premake project -- local p = premake local android = p.modules.android local vsandroid = p.modules.vsandroid local vc2010 = p.vstudio.vc2010 local vstudio = p.vstudio local project = p.project -- -- Add android tools to vstudio actions. -- premake.override(vstudio.vs2010, "generateProject", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.eol("\r\n") p.indent(" ") p.escaper(vstudio.vs2010.esc) if project.iscpp(prj) then p.generate(prj, ".androidproj", vc2010.generate) -- Skip generation of empty user files local user = p.capture(function() vc2010.generateUser(prj) end) if #user > 0 then p.generate(prj, ".androidproj.user", function() p.outln(user) end) end end else oldfn(prj) end end) premake.override(vstudio, "projectfile", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then return premake.filename(prj, ".androidproj") else return oldfn(prj) end end) premake.override(vstudio, "tool", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then return "39E2626F-3545-4960-A6E8-258AD8476CE5" else return oldfn(prj) end end) premake.override(vc2010.elements, "globals", function (oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == premake.ANDROIDPROJ then -- Remove "IgnoreWarnCompileDuplicatedFilename". local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename) table.remove(elements, pos) elements = table.join(elements, { android.projectVersion }) end return elements end) function android.projectVersion(cfg) _p(2, "<RootNamespace>%s</RootNamespace>", cfg.project.name) _p(2, "<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>") _p(2, "<ProjectVersion>1.0</ProjectVersion>") end premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == p.ANDROIDPROJ then elements = { vc2010.useDebugLibraries, } end return elements end) premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == p.ANDROIDPROJ then elements = { android.antPackage, } end return elements end) premake.override(vc2010, "importDefaultProps", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.Default.props" />') else oldfn(prj) end end) premake.override(vc2010, "importLanguageSettings", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.props" />') else oldfn(prj) end end) premake.override(vc2010, "propertySheets", function(oldfn, cfg) if cfg.kind ~= p.ANDROIDPROJ then oldfn(cfg) end end) premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg) if cfg.kind == p.ANDROIDPROJ then return { vc2010.outDir, } else return oldfn(cfg) end end) premake.override(vc2010, "importLanguageTargets", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.targets" />') else oldfn(prj) end end) vc2010.categories.AndroidManifest = { name = "AndroidManifest", priority = 99, emitFiles = function(prj, group) local fileCfgFunc = { android.manifestSubType, } vc2010.emitFiles(prj, group, "AndroidManifest", {vc2010.generatedFile}, fileCfgFunc) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AndroidManifest") end } function android.manifestSubType(cfg, file) vc2010.element("SubType", nil, "Designer") end vc2010.categories.AntBuildXml = { name = "AntBuildXml", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "AntBuildXml", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AntBuildXml") end } vc2010.categories.AntProjectPropertiesFile = { name = "AntProjectPropertiesFile", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "AntProjectPropertiesFile", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AntProjectPropertiesFile") end } vc2010.categories.Content = { name = "Content", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "Content", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "Content") end } premake.override(vc2010, "categorizeFile", function(base, prj, file) if prj.kind ~= p.ANDROIDPROJ then return base(prj, file) end local filename = path.getname(file.name):lower() if filename == "androidmanifest.xml" then return vc2010.categories.AndroidManifest elseif filename == "build.xml" then return vc2010.categories.AntBuildXml elseif filename == "project.properties" then return vc2010.categories.AntProjectPropertiesFile else return vc2010.categories.Content end end)
-- -- android/vsandroid_androidproj.lua -- vs-android integration for vstudio. -- Copyright (c) 2012-2015 Manu Evans and the Premake project -- local p = premake local android = p.modules.android local vsandroid = p.modules.vsandroid local vc2010 = p.vstudio.vc2010 local vstudio = p.vstudio local project = p.project -- -- Add android tools to vstudio actions. -- premake.override(vstudio.vs2010, "generateProject", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.eol("\r\n") p.indent(" ") p.escaper(vstudio.vs2010.esc) if project.iscpp(prj) then p.generate(prj, ".androidproj", vc2010.generate) -- Skip generation of empty user files local user = p.capture(function() vc2010.generateUser(prj) end) if #user > 0 then p.generate(prj, ".androidproj.user", function() p.outln(user) end) end end else oldfn(prj) end end) premake.override(vstudio, "projectfile", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then return premake.filename(prj, ".androidproj") else return oldfn(prj) end end) premake.override(vstudio, "tool", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then return "39E2626F-3545-4960-A6E8-258AD8476CE5" else return oldfn(prj) end end) premake.override(vc2010.elements, "globals", function (oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == premake.ANDROIDPROJ then -- Remove "IgnoreWarnCompileDuplicatedFilename". local pos = table.indexof(elements, vc2010.ignoreWarnDuplicateFilename) table.remove(elements, pos) elements = table.join(elements, { android.projectVersion }) end return elements end) function android.projectVersion(cfg) _p(2, "<RootNamespace>%s</RootNamespace>", cfg.project.name) _p(2, "<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>") _p(2, "<ProjectVersion>1.0</ProjectVersion>") end premake.override(vc2010.elements, "configurationProperties", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == p.ANDROIDPROJ then elements = { vc2010.useDebugLibraries, } end return elements end) premake.override(vc2010.elements, "itemDefinitionGroup", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.kind == p.ANDROIDPROJ then elements = { android.antPackage, } end return elements end) premake.override(vc2010, "importDefaultProps", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.Default.props" />') else oldfn(prj) end end) premake.override(vc2010, "importLanguageSettings", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.props" />') else oldfn(prj) end end) premake.override(vc2010, "propertySheets", function(oldfn, cfg) if cfg.kind ~= p.ANDROIDPROJ then oldfn(cfg) end end) premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg) if cfg.kind == p.ANDROIDPROJ then return { android.outDir, } else return oldfn(cfg) end end) function android.outDir(cfg) vc2010.element("OutDir", nil, "%s\\", cfg.buildtarget.directory) end premake.override(vc2010, "importLanguageTargets", function(oldfn, prj) if prj.kind == p.ANDROIDPROJ then p.w('<Import Project="$(AndroidTargetsPath)\\Android.targets" />') else oldfn(prj) end end) vc2010.categories.AndroidManifest = { name = "AndroidManifest", priority = 99, emitFiles = function(prj, group) local fileCfgFunc = { android.manifestSubType, } vc2010.emitFiles(prj, group, "AndroidManifest", {vc2010.generatedFile}, fileCfgFunc) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AndroidManifest") end } function android.manifestSubType(cfg, file) vc2010.element("SubType", nil, "Designer") end vc2010.categories.AntBuildXml = { name = "AntBuildXml", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "AntBuildXml", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AntBuildXml") end } vc2010.categories.AntProjectPropertiesFile = { name = "AntProjectPropertiesFile", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "AntProjectPropertiesFile", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "AntProjectPropertiesFile") end } vc2010.categories.Content = { name = "Content", priority = 99, emitFiles = function(prj, group) vc2010.emitFiles(prj, group, "Content", {vc2010.generatedFile}) end, emitFilter = function(prj, group) vc2010.filterGroup(prj, group, "Content") end } premake.override(vc2010, "categorizeFile", function(base, prj, file) if prj.kind ~= p.ANDROIDPROJ then return base(prj, file) end local filename = path.getname(file.name):lower() if filename == "androidmanifest.xml" then return vc2010.categories.AndroidManifest elseif filename == "build.xml" then return vc2010.categories.AntBuildXml elseif filename == "project.properties" then return vc2010.categories.AntProjectPropertiesFile else return vc2010.categories.Content end end)
Fixed output directory for androidproj projects, requires absolute paths.
Fixed output directory for androidproj projects, requires absolute paths.
Lua
bsd-3-clause
LORgames/premake-core,LORgames/premake-core,dcourtois/premake-core,noresources/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,mandersan/premake-core,tvandijck/premake-core,noresources/premake-core,sleepingwit/premake-core,premake/premake-core,mandersan/premake-core,mandersan/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,starkos/premake-core,soundsrc/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,dcourtois/premake-core,starkos/premake-core,noresources/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,dcourtois/premake-core,tvandijck/premake-core,premake/premake-core,starkos/premake-core,premake/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,sleepingwit/premake-core,tvandijck/premake-core,dcourtois/premake-core,starkos/premake-core,noresources/premake-core,premake/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,tvandijck/premake-core,premake/premake-core,premake/premake-core,noresources/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,starkos/premake-core,soundsrc/premake-core,premake/premake-core,Zefiros-Software/premake-core,sleepingwit/premake-core,starkos/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,mandersan/premake-core,soundsrc/premake-core,noresources/premake-core,Zefiros-Software/premake-core,LORgames/premake-core
5b323914db97fdce211f694d8f7222dafbe5ee3d
modules/announce.lua
modules/announce.lua
local mod = EPGP:NewModule("announce") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local SendChatMessage = _G.SendChatMessage if ChatThrottleLib then SendChatMessage = function(...) ChatThrottleLib:SendChatMessage("NORMAL", "EPGP", ...) end end function mod:AnnounceTo(medium, fmt, ...) if not medium then return end local channel = GetChannelName(self.db.profile.channel or 0) -- Override raid and party if we are not grouped if (medium == "RAID" or medium == "GUILD") and not UnitInRaid("player") then medium = "GUILD" end local msg = string.format(fmt, ...) local str = "EPGP:" for _,s in pairs({strsplit(" ", msg)}) do if #str + #s >= 250 then SendChatMessage(str, medium, nil, channel) str = "EPGP:" end str = str .. " " .. s end SendChatMessage(str, medium, nil, channel) end function mod:Announce(fmt, ...) local medium = self.db.profile.medium return mod:AnnounceTo(medium, fmt, ...) end function mod:EPAward(event_name, name, reason, amount, mass) if mass then return end mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name) end function mod:GPAward(event_name, name, reason, amount, mass) if mass then return end mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name) end function mod:BankedItem(event_name, name, reason, amount, mass) mod:Announce(L["%s to %s"], reason, name) end local function MakeCommaSeparated(t) local first = true local awarded = "" for name in pairs(t) do if first then awarded = name first = false else awarded = awarded..", "..name end end return awarded end function mod:MassEPAward(event_name, names, reason, amount, extras_names, extras_reason, extras_amount) local normal = MakeCommaSeparated(names) mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal) if extras_names then local extras = MakeCommaSeparated(extras_names) mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras) end end function mod:Decay(event_name, decay_p) mod:Announce(L["Decay of EP/GP by %d%%"], decay_p) end function mod:StartRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end function mod:ResumeRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end function mod:StopRecurringAward(event_name) mod:Announce(L["Stop recurring award"]) end function mod:EPGPReset(event_name) mod:Announce(L["EP/GP are reset"]) end function mod:GPReset(event_name) mod:Announce(L["GP (not EP) is reset"]) end function mod:GPRescale(event_name) mod:Announce(L["GP is rescaled for the new tier"]) end function mod:LootEpics(event_name, loot) for _, itemLink in ipairs(loot) do local _, _, itemRarity = GetItemInfo(itemLink) if itemRarity >= ITEM_QUALITY_EPIC then mod:Announce(itemLink) lib:SendCommMessage("EPGPCORPSELOOT", tostring(itemLink)) end end end mod.dbDefaults = { profile = { enabled = true, medium = "GUILD", events = { ['*'] = true, }, } } function mod:OnInitialize() self.db = EPGP.db:RegisterNamespace("announce", mod.dbDefaults) end mod.optionsName = L["Announce"] mod.optionsDesc = L["Announcement of EPGP actions"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Announces EPGP actions to the specified medium."], }, medium = { order = 10, type = "select", name = L["Announce medium"], desc = L["Sets the announce medium EPGP will use to announce EPGP actions."], values = { ["GUILD"] = CHAT_MSG_GUILD, ["OFFICER"] = CHAT_MSG_OFFICER, ["RAID"] = CHAT_MSG_RAID, ["PARTY"] = CHAT_MSG_PARTY, ["CHANNEL"] = CUSTOM, }, }, channel = { order = 11, type = "input", name = L["Custom announce channel name"], desc = L["Sets the custom announce channel name used to announce EPGP actions."], disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end, }, events = { order = 12, type = "multiselect", name = L["Announce when:"], values = { EPAward = L["A member is awarded EP"], MassEPAward = L["Guild or Raid are awarded EP"], GPAward = L["A member is credited GP"], BankedItem = L["An item was disenchanted or deposited into the guild bank"], Decay = L["EPGP decay"], StartRecurringAward = L["Recurring awards start"], StopRecurringAward = L["Recurring awards stop"], ResumeRecurringAward = L["Recurring awards resume"], EPGPReset = L["EPGP reset"], GPReset = L["GP (not ep) reset"], GPRescale = L["GP rescale for new tier"], LootEpics = L["Announce epic loot from corpses"], }, width = "full", get = "GetEvent", set = "SetEvent", }, } function mod:GetEvent(i, e) return self.db.profile.events[e] end function mod:SetEvent(i, e, v) if v then Debug("Enabling announce of: %s", e) EPGP.RegisterCallback(self, e) else Debug("Disabling announce of: %s", e) EPGP.UnregisterCallback(self, e) end self.db.profile.events[e] = v end function mod:OnEnable() for e, _ in pairs(mod.optionsArgs.events.values) do if self.db.profile.events[e] then Debug("Enabling announce of: %s (startup)", e) EPGP.RegisterCallback(self, e) end end end function mod:OnDisable() EPGP.UnregisterAllCallbacks(self) end
local mod = EPGP:NewModule("announce") local AC = LibStub("AceComm-3.0") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local SendChatMessage = _G.SendChatMessage if ChatThrottleLib then SendChatMessage = function(...) ChatThrottleLib:SendChatMessage("NORMAL", "EPGP", ...) end end function mod:AnnounceTo(medium, fmt, ...) if not medium then return end local channel = GetChannelName(self.db.profile.channel or 0) -- Override raid and party if we are not grouped if (medium == "RAID" or medium == "GUILD") and not UnitInRaid("player") then medium = "GUILD" end local msg = string.format(fmt, ...) local str = "EPGP:" for _,s in pairs({strsplit(" ", msg)}) do if #str + #s >= 250 then SendChatMessage(str, medium, nil, channel) str = "EPGP:" end str = str .. " " .. s end SendChatMessage(str, medium, nil, channel) end function mod:Announce(fmt, ...) local medium = self.db.profile.medium return mod:AnnounceTo(medium, fmt, ...) end function mod:EPAward(event_name, name, reason, amount, mass) if mass then return end mod:Announce(L["%+d EP (%s) to %s"], amount, reason, name) end function mod:GPAward(event_name, name, reason, amount, mass) if mass then return end mod:Announce(L["%+d GP (%s) to %s"], amount, reason, name) end function mod:BankedItem(event_name, name, reason, amount, mass) mod:Announce(L["%s to %s"], reason, name) end local function MakeCommaSeparated(t) local first = true local awarded = "" for name in pairs(t) do if first then awarded = name first = false else awarded = awarded..", "..name end end return awarded end function mod:MassEPAward(event_name, names, reason, amount, extras_names, extras_reason, extras_amount) local normal = MakeCommaSeparated(names) mod:Announce(L["%+d EP (%s) to %s"], amount, reason, normal) if extras_names then local extras = MakeCommaSeparated(extras_names) mod:Announce(L["%+d EP (%s) to %s"], extras_amount, extras_reason, extras) end end function mod:Decay(event_name, decay_p) mod:Announce(L["Decay of EP/GP by %d%%"], decay_p) end function mod:StartRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) mod:Announce(L["Start recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end function mod:ResumeRecurringAward(event_name, reason, amount, mins) local fmt, val = SecondsToTimeAbbrev(mins * 60) mod:Announce(L["Resume recurring award (%s) %d EP/%s"], reason, amount, fmt:format(val)) end function mod:StopRecurringAward(event_name) mod:Announce(L["Stop recurring award"]) end function mod:EPGPReset(event_name) mod:Announce(L["EP/GP are reset"]) end function mod:GPReset(event_name) mod:Announce(L["GP (not EP) is reset"]) end function mod:GPRescale(event_name) mod:Announce(L["GP is rescaled for the new tier"]) end function mod:LootEpics(event_name, loot) for _, itemLink in ipairs(loot) do local _, _, itemRarity = GetItemInfo(itemLink) if itemRarity >= ITEM_QUALITY_EPIC then mod:Announce(itemLink) AC:SendCommMessage("EPGPCORPSELOOT", tostring(itemLink), "GUILD", nil, "ALERT") end end end mod.dbDefaults = { profile = { enabled = true, medium = "GUILD", events = { ['*'] = true, }, } } function mod:OnInitialize() self.db = EPGP.db:RegisterNamespace("announce", mod.dbDefaults) end mod.optionsName = L["Announce"] mod.optionsDesc = L["Announcement of EPGP actions"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Announces EPGP actions to the specified medium."], }, medium = { order = 10, type = "select", name = L["Announce medium"], desc = L["Sets the announce medium EPGP will use to announce EPGP actions."], values = { ["GUILD"] = CHAT_MSG_GUILD, ["OFFICER"] = CHAT_MSG_OFFICER, ["RAID"] = CHAT_MSG_RAID, ["PARTY"] = CHAT_MSG_PARTY, ["CHANNEL"] = CUSTOM, }, }, channel = { order = 11, type = "input", name = L["Custom announce channel name"], desc = L["Sets the custom announce channel name used to announce EPGP actions."], disabled = function(i) return mod.db.profile.medium ~= "CHANNEL" end, }, events = { order = 12, type = "multiselect", name = L["Announce when:"], values = { EPAward = L["A member is awarded EP"], MassEPAward = L["Guild or Raid are awarded EP"], GPAward = L["A member is credited GP"], BankedItem = L["An item was disenchanted or deposited into the guild bank"], Decay = L["EPGP decay"], StartRecurringAward = L["Recurring awards start"], StopRecurringAward = L["Recurring awards stop"], ResumeRecurringAward = L["Recurring awards resume"], EPGPReset = L["EPGP reset"], GPReset = L["GP (not ep) reset"], GPRescale = L["GP rescale for new tier"], LootEpics = L["Announce epic loot from corpses"], }, width = "full", get = "GetEvent", set = "SetEvent", }, } function mod:GetEvent(i, e) return self.db.profile.events[e] end function mod:SetEvent(i, e, v) if v then Debug("Enabling announce of: %s", e) EPGP.RegisterCallback(self, e) else Debug("Disabling announce of: %s", e) EPGP.UnregisterCallback(self, e) end self.db.profile.events[e] = v end function mod:OnEnable() for e, _ in pairs(mod.optionsArgs.events.values) do if self.db.profile.events[e] then Debug("Enabling announce of: %s (startup)", e) EPGP.RegisterCallback(self, e) end end end function mod:OnDisable() EPGP.UnregisterAllCallbacks(self) end
fix a bug in how AceComm was used
fix a bug in how AceComm was used
Lua
bsd-3-clause
hayword/tfatf_epgp,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,protomech/epgp-dkp-reloaded
1989905bb5b6595262c58ce762191f59e1b2da7c
modules/shipment.lua
modules/shipment.lua
local ev = require'ev' local simplehttp = require'simplehttp' local json = require'json' local math = require'math' local os = require'os' local apiurl = 'http://sporing.bring.no/sporing.json?q=%s&%s' local duration = 60 if(not ivar2.timers) then ivar2.timers = {} end -- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local getCacheBust = function() return math.floor(os.time() / 60) end local eventHandler = function(event) if not event then return nil end local city = event.city if city ~= '' then city = ' ('..city..')' end return string.format('%s %s %s%s', event.displayDate, event.displayTime, event.description, city) end local shipmentTrack = function(self, source, destination, message) local nick = source.nick local comps = split(message, '%S+') -- Couldn't figure out what the user wanted. if #comps < 2 then return self:Msg('privmsg', destination, source, 'Usage: !sporing pakkeid alias') end local pid = comps[1] local alias = comps[2] local id = pid .. nick local runningTimer = self.timers[id] if(runningTimer) then -- cancel existing timer self:Notice(nick, "Canceling existing tracking for alias %s.", alias) self.shipmentEvents[id] = -1 runningTimer:stop(ivar2.Loop) end -- Store the eventcount in the ivar2 global -- if the eventcount increases it means new events on the shipment happened. local eventCount = self.shipmentEvents[id] if not eventCount then self.shipmentEvents[id] = -1 end local timer = ev.Timer.new( function(loop, timer, revents) simplehttp(string.format(apiurl, pid, getCacheBust()), function(data) local info = json.decode(data) local cs = info.consignmentSet if not cs[1] then return else cs = cs[1] end local err = cs['error'] if err then local errmsg = err['message'] if self.shipmentEvents[id] == -1 then self:Msg('privmsg', destination, source, '%s: \002%s\002 %s', nick, alias, errmsg) end self.shipmentEvents[id] = 0 return end local ps = cs['packageSet'][1] local eventset = ps['eventSet'] local newEventCount = #eventset local out = {} for i=newEventCount,self.shipmentEvents[id]+1,-1 do local event = eventset[i] if event then table.insert(out, eventHandler(event)) local status = event.status -- Cancel event if package is delivered if status == 'DELIVERED' then self.timers[id]:stop(ivar2.Loop) self.timers[id] = nil end end end if #out > 0 then self:Msg('privmsg', destination, source, '%s: \002%s\002 %s', nick, alias, table.concat(out, ', ')) end self.shipmentEvents[id] = newEventCount end) end, 1, duration ) self.timers[id] = timer timer:start(ivar2.Loop) end local shipmentLocate = function(self, source, destination, pid) local nick = source.nick simplehttp(string.format(apiurl, pid, getCacheBust()), function(data) local info = json.decode(data) local cs = info.consignmentSet if not cs[1] then return else cs = cs[1] end local err = cs['error'] if err then local errmsg = err['message'] self:Msg('privmsg', destination, source, '%s: %s', nick, errmsg) return end local out = {} local weight = cs["totalWeightInKgs"] local ps = cs['packageSet'][1] for i,event in pairs(ps['eventSet']) do table.insert(out, eventHandler(event)) end self:Msg('privmsg', destination, source, '%s: %s', nick, table.concat(out, ', ')) end) end return { PRIVMSG = { ['^%psporing (.*)$'] = shipmentTrack, ['^%pspor (.*)$'] = shipmentTrack, ['^%ppakke (.*)$'] = shipmentLocate, }, }
local ev = require'ev' local simplehttp = require'simplehttp' local json = require'json' local math = require'math' local os = require'os' local apiurl = 'http://sporing.bring.no/sporing.json?q=%s&%s' local duration = 60 if(not ivar2.timers) then ivar2.timers = {} end -- Abuse the ivar2 global to store out ephemeral event data until we can get some persistant storage if(not ivar2.shipmentEvents) then ivar2.shipmentEvents = {} end local split = function(str, pattern) local out = {} str:gsub(pattern, function(match) table.insert(out, match) end) return out end local getCacheBust = function() return math.floor(os.time() / 60) end local eventHandler = function(event) if not event then return nil end local city = event.city if city ~= '' then city = ' ('..city..')' end return string.format('%s %s %s%s', event.displayDate, event.displayTime, event.description, city) end local shipmentTrack = function(self, source, destination, message) local nick = source.nick local comps = split(message, '%S+') -- Couldn't figure out what the user wanted. if #comps < 2 then return self:Msg('privmsg', destination, source, 'Usage: !sporing pakkeid alias') end local pid = comps[1] local alias = comps[2] local id = pid .. nick local runningTimer = self.timers[id] if(runningTimer) then -- cancel existing timer self:Notice(nick, "Canceling existing tracking for alias %s.", alias) self.shipmentEvents[id] = -1 runningTimer:stop(ivar2.Loop) end -- Store the eventcount in the ivar2 global -- if the eventcount increases it means new events on the shipment happened. local eventCount = self.shipmentEvents[id] if not eventCount then self.shipmentEvents[id] = -1 end local timer = ev.Timer.new( function(loop, timer, revents) simplehttp(string.format(apiurl, pid, getCacheBust()), function(data) local info = json.decode(data) local cs = info.consignmentSet if not cs[1] then return else cs = cs[1] end local err = cs['error'] if err then local errmsg = err['message'] if self.shipmentEvents[id] == -1 then self:Msg('privmsg', destination, source, '%s: \002%s\002 %s', nick, alias, errmsg) end self.shipmentEvents[id] = 0 return end local ps = cs['packageSet'][1] local eventset = ps['eventSet'] local newEventCount = #eventset local out = {} --print('id:',id,'new:',newEventCount,'old:',self.shipmentEvents[id]) if newEventCount < self.shipmentEvents[id] then newEventCount = self.shipmentEvents[id] end for i=self.shipmentEvents[id]+1,newEventCount do --print('loop:',i) local event = eventset[i] if event then table.insert(out, eventHandler(event)) local status = event.status -- Cancel event if package is delivered if status == 'DELIVERED' then self.timers[id]:stop(ivar2.Loop) self.timers[id] = nil end end end if #out > 0 then self:Msg('privmsg', destination, source, '%s: \002%s\002 %s', nick, alias, table.concat(out, ', ')) end self.shipmentEvents[id] = newEventCount end) end, 1, duration ) self.timers[id] = timer timer:start(ivar2.Loop) end local shipmentLocate = function(self, source, destination, pid) local nick = source.nick simplehttp(string.format(apiurl, pid, getCacheBust()), function(data) local info = json.decode(data) local cs = info.consignmentSet if not cs[1] then return else cs = cs[1] end local err = cs['error'] if err then local errmsg = err['message'] self:Msg('privmsg', destination, source, '%s: %s', nick, errmsg) return end local out = {} local weight = cs["totalWeightInKgs"] local ps = cs['packageSet'][1] for i,event in pairs(ps['eventSet']) do table.insert(out, eventHandler(event)) end self:Msg('privmsg', destination, source, '%s: %s', nick, table.concat(out, ', ')) end) end local shipmentHelp = function(self, source, destination) return self:Msg('privmsg', destination, source, 'For lookup: !pakke pakkeid. For tracking: !sporing pakkeid alias') end return { PRIVMSG = { ['^%psporing (.*)$'] = shipmentTrack, ['^%pspor (.*)$'] = shipmentTrack, ['^%ppakke (.*)$'] = shipmentLocate, ['^%psporing$'] = shipmentHelp, ['^%ppakke$'] = shipmentHelp, }, }
Fixes for shipment
Fixes for shipment Former-commit-id: 1bdb3e78ffe491f3116bec956914a19bf5370260 [formerly c9afe6a27c85e406e676a1ef73c2e07c262058a7] Former-commit-id: 2e9982567ed1ef5151a3d5917218b3332e89f42b
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
3cf828cfdb20f5972f3b84717489d6e0061c3792
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
modules/admin-full/luasrc/model/cbi/admin_system/admin.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end --[[ if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end end --]] return m --[[, m2]]--
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.on_commit(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end end --[[ if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 keys.rmempty = false function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) if value then fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end end end --]] return m --[[, m2]]--
fixed indentation
fixed indentation
Lua
apache-2.0
palmettos/test,palmettos/cnLuCI,palmettos/test,palmettos/cnLuCI,palmettos/test,palmettos/cnLuCI,palmettos/test,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/test,palmettos/test,palmettos/test,palmettos/test
904a96b86b985978acaaa3d5f37bedfec38c5d36
plugins/lua/init.lua
plugins/lua/init.lua
require "superstring" ENV = require "env" ::start:: -- -- Indicate that we are ready to receive a packet -- io.write( "\n\x1A" ); io.flush() -- -- Read until EOF -- local code = io.read "a" -- -- Only display errors if the code starts with ">" -- local silent_error = true if code:sub( 1, 1 ) == ">" then code = code:sub( 2 ) silent_error = false end -- -- Try our code with "return " prepended first -- local f, err = load( "return " .. code, "eval", "t", ENV ) if err then f, err = load( code, "eval", "t", ENV ) end -- -- We've been passed invalid Lua -- if err then if not silent_error then io.write( err ) end goto start end local thread = coroutine.create( f ) local start = os.clock() -- -- Install our execution time limiter -- debug.sethook( thread, function() if os.clock() > start + 0.5 then error( "maximum execution time exceeded", 2 ) end end, "", 128 ) -- -- Try to run our function -- local ret = { pcall( coroutine.resume, thread ) } local success, err = ret[ 2 ], ret[ 3 ] if not success then if not silent_error then io.write( err ) end goto start end -- -- Remove pcall success and coroutine success bools -- table.remove( ret, 1 ) table.remove( ret, 1 ) -- -- Transform our ret values in to strings -- for k, v in ipairs( ret ) do ret[ k ] = tostring( v ) end local out = table.concat( ret, "\t" ) if code == out then goto start end io.write( out ) -- -- repl --- goto start
require "superstring" ENV = require "env" ::start:: -- -- Indicate that we are ready to receive a packet -- io.write( "\n\x1A" ); io.flush() -- -- Read until EOF -- local code = io.read "a" -- -- Only display errors if the code starts with ">" -- local silent_error = true if code:sub( 1, 1 ) == ">" then code = code:sub( 2 ) silent_error = false end -- -- Try our code with "return " prepended first -- local f, err = load( "return " .. code, "eval", "t", ENV ) if err then f, err = load( code, "eval", "t", ENV ) end -- -- We've been passed invalid Lua -- if err then if not silent_error then io.write( err ) end goto start end local thread = coroutine.create( f ) local start = os.clock() -- -- Install our execution time limiter -- debug.sethook( thread, function() if os.clock() > start + 0.5 then error( "maximum execution time exceeded", 2 ) end end, "", 128 ) -- -- Try to run our function -- local ret = { pcall( coroutine.resume, thread ) } local success, err = ret[ 2 ], ret[ 3 ] if not success then if not silent_error then io.write( err ) end goto start end -- -- Remove pcall success and coroutine success bools -- table.remove( ret, 1 ) table.remove( ret, 1 ) -- -- Transform our ret values in to strings -- for k, v in ipairs( ret ) do ret[ k ] = tostring( v ) end local out = table.concat( ret, "\t" ) if not silent_error and code:gsub("[\r\n]$", ""):gsub("^['\"]", ""):gsub("['\"]$", "") == out then goto start end io.write( out ) -- -- repl --- goto start
fix useless printing fix
fix useless printing fix
Lua
cc0-1.0
ModMountain/hash.js,mcd1992/hash.js,SwadicalRag/hash.js,meepdarknessmeep/hash.js
0bdc0e44c5f5f34d708ac71c320eaafbae57c890
lua/starfall/libs_sh/file.lua
lua/starfall/libs_sh/file.lua
------------------------------------------------------------------------------- -- File functions ------------------------------------------------------------------------------- --- File functions. Allows modification of files. -- @shared local file_library, _ = SF.Libraries.Register( "file" ) -- Register privileges do local P = SF.Permissions P.registerPrivilege( "file.read", "Read files", "Allows the user to read files from data/sf_scriptdata directory" ) P.registerPrivilege( "file.write", "Write files", "Allows the user to write files to data/sf_scriptdata directory" ) P.registerPrivilege( "file.exists", "File existence check", "Allows the user to determine whether a file in data/sf_scriptdata exists" ) end file.CreateDir( "sf_filedata/" ) --- Reads a file from path -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return Contents, or nil if error -- @return Error message if applicable function file_library.read ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.read" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end local contents = file.Read( "sf_filedata/" .. path, "DATA" ) if contents then return contents else error( "file not found" ) return end end --- Writes to a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if OK, nil if error -- @return Error message if applicable function file_library.write ( path, data ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) SF.CheckType( data, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end file.Write( "sf_filedata/" .. path, data ) return true end --- Appends a string to the end of a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @param data String that will be appended to the file. -- @return Error message if applicable function file_library.append ( path, data ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) SF.CheckType( data, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end file.Append( "sf_filedata/" .. path, data ) return true end --- Checks if a file exists -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if exists, false if not, nil if error -- @return Error message if applicable function file_library.exists ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.exists" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end return file.Exists( "sf_filedata/" .. path, "DATA" ) end --- Deletes a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if successful, nil if error -- @return Error message if applicable function file_library.delete ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end if not file.Exists( "sf_filedata/" .. path, "DATA" ) then error( "doesn't exist" ) return end file.Delete( path ) return true end --- Creates a directory -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return Error message if applicable function file_library.createDir ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then error( "path contains '..'" ) return end return file.CreateDir( "sf_filedata/" .. path ) end
------------------------------------------------------------------------------- -- File functions ------------------------------------------------------------------------------- --- File functions. Allows modification of files. -- @shared local file_library, _ = SF.Libraries.Register( "file" ) -- Register privileges do local P = SF.Permissions P.registerPrivilege( "file.read", "Read files", "Allows the user to read files from data/sf_scriptdata directory" ) P.registerPrivilege( "file.write", "Write files", "Allows the user to write files to data/sf_scriptdata directory" ) P.registerPrivilege( "file.exists", "File existence check", "Allows the user to determine whether a file in data/sf_scriptdata exists" ) end file.CreateDir( "sf_filedata/" ) --- Reads a file from path -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return Contents, or nil if error -- @return Error message if applicable function file_library.read ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.read" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end local contents = file.Read( "sf_filedata/" .. path, "DATA" ) if contents then return contents else SF.throw( "file not found", 2 ) return end end --- Writes to a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if OK, nil if error -- @return Error message if applicable function file_library.write ( path, data ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) SF.CheckType( data, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end file.Write( "sf_filedata/" .. path, data ) return true end --- Appends a string to the end of a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @param data String that will be appended to the file. -- @return Error message if applicable function file_library.append ( path, data ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) SF.CheckType( data, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end file.Append( "sf_filedata/" .. path, data ) return true end --- Checks if a file exists -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if exists, false if not, nil if error -- @return Error message if applicable function file_library.exists ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.exists" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end return file.Exists( "sf_filedata/" .. path, "DATA" ) end --- Deletes a file -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return True if successful, nil if error -- @return Error message if applicable function file_library.delete ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end if not file.Exists( "sf_filedata/" .. path, "DATA" ) then SF.throw( "file not found", 2 ) return end file.Delete( path ) return true end --- Creates a directory -- @param path Filepath relative to data/sf_filedata/. Cannot contain '..' -- @return Error message if applicable function file_library.createDir ( path ) if not SF.Permissions.check( SF.instance.player, path, "file.write" ) then SF.throw( "Insufficient permissions", 2 ) end SF.CheckType( path, "string" ) if path:find( "..", 1, true ) then SF.throw( "path contains '..'", 2 ) return end return file.CreateDir( "sf_filedata/" .. path ) end
fixed file functions not using SF.throw
fixed file functions not using SF.throw
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Xandaros/Starfall,INPStarfall/Starfall
7138b92295eeca5072ae2708632aa37a7a0ab1cc
sketches/dump_to_html.lua
sketches/dump_to_html.lua
function dump_to_html(src_file, grammar, dir) os.execute("mkdir -p " .. dir) local glas = OrderedSet:new() for name, rtn in each(grammar.rtns) do for state in each(rtn:states()) do if state.gla then glas:add(state.gla) end end end local index = io.open(dir .. "/index.html", "w") local title = string.format("Gazelle Grammar Dump: %s", src_file) index:write("<!DOCTYPE html>\n") index:write("<html>\n") index:write(string.format("<head><title>%s</title></head>\n", title)) index:write("<body>\n") index:write("<h1>" .. title .. "</h1>\n") index:write("<ul>\n") index:write("<li><a href='#rules'>Rules</a></li>\n") index:write("<ul>\n") for name, rtn in each(grammar.rtns) do index:write(string.format("<li><a href='#rule_%s'>%s</a></li>", name, name)) end index:write("</ul>\n") index:write("<li><a href='#lookahead'>Lookahead</a></li>\n") index:write("<ul>\n") local gla_num = 1 for gla in each(glas) do index:write(string.format("<li><a href='#gla_%d'>GLA %d</a></li>", gla_num, gla_num)) gla_num = gla_num + 1 end index:write("</ul>\n") index:write("<li><a href='#lexing'>Lexing</a></li>\n") index:write("<ul>\n") local intfa_num = 1 for intfa in each(grammar.master_intfas) do index:write(string.format("<li><a href='#intfa_%d'>IntFA %d</a></li>", intfa_num, intfa_num)) intfa_num = intfa_num + 1 end index:write("</ul>\n") index:write("</ul>") index:write("<h2><a name='rules'>Rules</a></h2>\n") index:write("<p>The states in the grammar are:</p>") local no_gla_breakdown = {} local with_gla_breakdown = {} local lookaheads = Set:new() local total = 0 for name, rtn in each(grammar.rtns) do for state in each(rtn:states()) do total = total + 1 local lookahead if state.gla then lookahead = state.gla.longest_path with_gla_breakdown[lookahead] = with_gla_breakdown[lookahead] or 0 with_gla_breakdown[lookahead] = with_gla_breakdown[lookahead] + 1 else if state:num_transitions() == 1 then lookahead = 0 else lookahead = 1 end no_gla_breakdown[lookahead] = no_gla_breakdown[lookahead] or 0 no_gla_breakdown[lookahead] = no_gla_breakdown[lookahead] + 1 end lookaheads:add(lookahead) end end lookaheads = lookaheads:to_array() table.sort(lookaheads) index:write("<ul>") for lookahead in each(lookaheads) do if no_gla_breakdown[lookahead] then index:write(string.format("<li>%0.1f%% LL(%d) (%d/%d states)</li>\n", no_gla_breakdown[lookahead] / total * 100, lookahead, no_gla_breakdown[lookahead], total)) end end for lookahead in each(lookaheads) do if with_gla_breakdown[lookahead] then local color if lookahead == 1 then color = "#6495ed" elseif lookahead == 2 then color = "#ffd700" else color = "#b22222" end index:write(string.format("<li>%0.1f%% LL(%d) with GLA (%d/%d states): \n" .. "indicated with <span style='background-color: %s'>color</span> below</li>\n", with_gla_breakdown[lookahead] / total * 100, lookahead, with_gla_breakdown[lookahead], total, color)) end end index:write("</ul>") index:write("<table border='1'>\n") for name, rtn in each(grammar.rtns) do local rtn_file = io.open(string.format("%s/%s.dot", dir, name), "w") rtn_file:write("digraph untitled {\n") rtn_file:write(rtn:to_dot(" ", "", grammar.master_intfas, glas)) rtn_file:write("}\n") rtn_file:close() os.execute(string.format("dot -Tpng -o %s/%s.png %s/%s.dot", dir, name, dir, name)) index:write(" <tr><td rowspan='2'>") index:write(string.format("<a name='rule_%s'>%s</td>", name, name)) index:write(string.format(" <td><pre>%s</pre></td></tr>\n", rtn.text)) index:write(string.format(" <tr><td><img src='%s.png'></td></tr>\n", name)) end index:write("</table>\n") index:write("<h2><a name='lookahead'>Lookahead</a></h2>\n") local gla_num = 1 for gla in each(glas) do local dot_file = string.format("%s/gla-%d.dot", dir, gla_num) local png_file = string.format("%s/gla-%d.png", dir, gla_num) local png_file_no_dir = string.format("gla-%d.png", gla_num) local gla_file = io.open(dot_file, "w") gla_file:write("digraph untitled {\n") gla_file:write(" rankdir=\"LR\";\n") gla_file:write(gla:to_dot(" ")) gla_file:write("}\n") gla_file:close() os.execute(string.format("dot -Tpng -o %s %s", png_file, dot_file)) index:write(string.format("<h3><a name='gla_%d'>GLA %d</a></h3>", gla_num, gla_num)) index:write(string.format("<img src='%s'>", png_file_no_dir)) index:write("<br>\n") gla_num = gla_num + 1 end index:write("<h2><a name='lexing'>Lexing</a></h2>\n") index:write(string.format("<p>The grammar's lexer has %d IntFAs, which follow:</p>", grammar.master_intfas:count())) local intfa_num = 1 local have_graphviz = os.execute("mogrify > /dev/null") == 0 for intfa in each(grammar.master_intfas) do local dot_file = string.format("%s/intfa-%d.dot", dir, intfa_num) local png_file = string.format("%s/intfa-%d.png", dir, intfa_num) local png_file_no_dir = string.format("intfa-%d.png", intfa_num) local png_thumb_file = string.format("%s/intfa-%d-thumb.png", dir, intfa_num) local png_thumb_file_no_dir = string.format("intfa-%d-thumb.png", intfa_num) local intfa_file = io.open(dot_file, "w") intfa_file:write("digraph untitled {\n") intfa_file:write(intfa:to_dot(" ")) intfa_file:write("}\n") intfa_file:close() os.execute(string.format("dot -Tpng -o %s %s", png_file, dot_file)) local w = 800 if have_graphviz then local img_info = io.popen(string.format("identify %s", png_file)):read("*a") w, h = string.match(img_info, "[^ ]+ [^ ]+ (%d+)x(%d+)") w = math.floor(w * 0.7) h = math.floor(h * 0.7) os.execute(string.format("convert %s -scale %dx%d %s", png_file, w, h, png_thumb_file)) else os.execute(string.format("cp %s %s", png_file, png_thumb_file)) end index:write(string.format("<h3><a name='intfa_%d'>IntFA %d</a></h3>", intfa_num, intfa_num)) index:write(string.format("<a href='%s'><img style='max-width: %dpx;' src='%s'></a>", png_file_no_dir, w, png_thumb_file_no_dir)) index:write("<br>\n") intfa_num = intfa_num + 1 end index:write("</body>\n") index:write("</html>\n") end
function dump_to_html(src_file, grammar, dir) os.execute("mkdir -p " .. dir) local glas = OrderedSet:new() for name, rtn in each(grammar.rtns) do for state in each(rtn:states()) do if state.gla then glas:add(state.gla) end end end local index = io.open(dir .. "/index.html", "w") local title = string.format("Gazelle Grammar Dump: %s", src_file) index:write("<!DOCTYPE html>\n") index:write("<html>\n") index:write(string.format("<head><title>%s</title></head>\n", title)) index:write("<body>\n") index:write("<h1>" .. title .. "</h1>\n") index:write("<ul>\n") index:write("<li><a href='#rules'>Rules</a></li>\n") index:write("<ul>\n") for name, rtn in each(grammar.rtns) do index:write(string.format("<li><a href='#rule_%s'>%s</a></li>", name, name)) end index:write("</ul>\n") index:write("<li><a href='#lookahead'>Lookahead</a></li>\n") index:write("<ul>\n") local gla_num = 1 for gla in each(glas) do index:write(string.format("<li><a href='#gla_%d'>GLA %d</a></li>", gla_num, gla_num)) gla_num = gla_num + 1 end index:write("</ul>\n") index:write("<li><a href='#lexing'>Lexing</a></li>\n") index:write("<ul>\n") local intfa_num = 1 for intfa in each(grammar.master_intfas) do index:write(string.format("<li><a href='#intfa_%d'>IntFA %d</a></li>", intfa_num, intfa_num)) intfa_num = intfa_num + 1 end index:write("</ul>\n") index:write("</ul>") index:write("<h2><a name='rules'>Rules</a></h2>\n") index:write("<p>The states in the grammar are:</p>") local no_gla_breakdown = {} local with_gla_breakdown = {} local lookaheads = Set:new() local total = 0 for name, rtn in each(grammar.rtns) do for state in each(rtn:states()) do total = total + 1 local lookahead if state.gla then lookahead = state.gla.longest_path with_gla_breakdown[lookahead] = with_gla_breakdown[lookahead] or 0 with_gla_breakdown[lookahead] = with_gla_breakdown[lookahead] + 1 else if state:num_transitions() == 1 then lookahead = 0 else lookahead = 1 end no_gla_breakdown[lookahead] = no_gla_breakdown[lookahead] or 0 no_gla_breakdown[lookahead] = no_gla_breakdown[lookahead] + 1 end lookaheads:add(lookahead) end end lookaheads = lookaheads:to_array() table.sort(lookaheads) index:write("<ul>") for lookahead in each(lookaheads) do if no_gla_breakdown[lookahead] then index:write(string.format("<li>%0.1f%% LL(%d) (%d/%d states)</li>\n", no_gla_breakdown[lookahead] / total * 100, lookahead, no_gla_breakdown[lookahead], total)) end end for lookahead in each(lookaheads) do if with_gla_breakdown[lookahead] then local color if lookahead == 1 then color = "#6495ed" elseif lookahead == 2 then color = "#ffd700" else color = "#b22222" end index:write(string.format("<li>%0.1f%% LL(%d) with GLA (%d/%d states): \n" .. "indicated with <span style='background-color: %s'>color</span> below</li>\n", with_gla_breakdown[lookahead] / total * 100, lookahead, with_gla_breakdown[lookahead], total, color)) end end index:write("</ul>") index:write("<table border='1'>\n") for name, rtn in each(grammar.rtns) do local rtn_file = io.open(string.format("%s/%s.dot", dir, name), "w") rtn_file:write("digraph untitled {\n") rtn_file:write(rtn:to_dot(" ", "", grammar.master_intfas, glas)) rtn_file:write("}\n") rtn_file:close() os.execute(string.format("dot -Tpng -o %s/%s.png %s/%s.dot", dir, name, dir, name)) index:write(" <tr><td rowspan='2'>") index:write(string.format("<a name='rule_%s'>%s</td>", name, name)) index:write(string.format(" <td><pre>%s</pre></td></tr>\n", rtn.text)) index:write(string.format(" <tr><td><img src='%s.png'></td></tr>\n", name)) end index:write("</table>\n") index:write("<h2><a name='lookahead'>Lookahead</a></h2>\n") local gla_num = 1 for gla in each(glas) do local dot_file = string.format("%s/gla-%d.dot", dir, gla_num) local png_file = string.format("%s/gla-%d.png", dir, gla_num) local png_file_no_dir = string.format("gla-%d.png", gla_num) local gla_file = io.open(dot_file, "w") gla_file:write("digraph untitled {\n") gla_file:write(" rankdir=\"LR\";\n") gla_file:write(gla:to_dot(" ")) gla_file:write("}\n") gla_file:close() os.execute(string.format("dot -Tpng -o %s %s", png_file, dot_file)) index:write(string.format("<h3><a name='gla_%d'>GLA %d</a></h3>", gla_num, gla_num)) index:write(string.format("<img src='%s'>", png_file_no_dir)) index:write("<br>\n") gla_num = gla_num + 1 end index:write("<h2><a name='lexing'>Lexing</a></h2>\n") index:write(string.format("<p>The grammar's lexer has %d IntFAs, which follow:</p>", grammar.master_intfas:count())) local intfa_num = 1 local have_imagemagick = os.execute("mogrify > /dev/null 2> /dev/null") == 0 for intfa in each(grammar.master_intfas) do local dot_file = string.format("%s/intfa-%d.dot", dir, intfa_num) local png_file = string.format("%s/intfa-%d.png", dir, intfa_num) local png_file_no_dir = string.format("intfa-%d.png", intfa_num) local png_thumb_file = string.format("%s/intfa-%d-thumb.png", dir, intfa_num) local png_thumb_file_no_dir = string.format("intfa-%d-thumb.png", intfa_num) local intfa_file = io.open(dot_file, "w") intfa_file:write("digraph untitled {\n") intfa_file:write(intfa:to_dot(" ")) intfa_file:write("}\n") intfa_file:close() os.execute(string.format("dot -Tpng -o %s %s", png_file, dot_file)) local w = 800 if have_imagemagick then local img_info = io.popen(string.format("identify %s", png_file)):read("*a") w, h = string.match(img_info, "[^ ]+ [^ ]+ (%d+)x(%d+)") w = math.floor(w * 0.7) h = math.floor(h * 0.7) os.execute(string.format("convert %s -scale %dx%d %s", png_file, w, h, png_thumb_file)) else os.execute(string.format("cp %s %s", png_file, png_thumb_file)) end index:write(string.format("<h3><a name='intfa_%d'>IntFA %d</a></h3>", intfa_num, intfa_num)) index:write(string.format("<a href='%s'><img style='max-width: %dpx;' src='%s'></a>", png_file_no_dir, w, png_thumb_file_no_dir)) index:write("<br>\n") intfa_num = intfa_num + 1 end index:write("</body>\n") index:write("</html>\n") end
Fix bug in dump_to_html detection of ImageMagick.
Fix bug in dump_to_html detection of ImageMagick.
Lua
bsd-3-clause
mbrubeck/gazelle,mbrubeck/gazelle,haberman/gazelle,haberman/gazelle
31e760fdec73454b790f2441b99704b254844af3
nvim/lua/ryankoval/neotree.lua
nvim/lua/ryankoval/neotree.lua
vim.cmd([[ let g:neo_tree_remove_legacy_commands = 1 ]]) require('neo-tree').setup({ close_if_last_window = true, -- Close Neo-tree if it is the last window left in the tab popup_border_style = 'rounded', enable_git_status = true, enable_diagnostics = true, default_component_configs = { container = { enable_character_fade = true, }, indent = { indent_size = 1, padding = 0, -- extra padding on left hand side -- indent guides with_markers = true, indent_marker = '│', last_indent_marker = '└', highlight = 'NeoTreeIndentMarker', -- expander config, needed for nesting files with_expanders = nil, -- if nil and file nesting is enabled, will enable expanders expander_collapsed = '', expander_expanded = '', expander_highlight = 'NeoTreeExpander', }, icon = { folder_closed = '', folder_open = '', folder_empty = 'ﰊ', -- The next two settings are only a fallback, if you use nvim-web-devicons and configure default icons there -- then these will never be used. default = '*', highlight = 'NeoTreeFileIcon', }, modified = { symbol = '[+]', highlight = 'NeoTreeModified', }, name = { trailing_slash = false, use_git_status_colors = true, highlight = 'NeoTreeFileName', }, git_status = { symbols = { -- Change type added = '', -- or "✚", but this is redundant info if you use git_status_colors on the name modified = '', -- or "", but this is redundant info if you use git_status_colors on the name deleted = '✖', -- this can only be used in the git_status source renamed = '', -- this can only be used in the git_status source -- Status type untracked = '', ignored = '', unstaged = '', staged = '', conflict = '', }, }, }, window = { position = 'left', width = 40, mapping_options = { noremap = true, nowait = true, }, mappings = { ['<backspace>'] = 'none', ['<space>'] = 'none', ['<cr>'] = 'open_tabnew', ['S'] = 'open_split', ['s'] = 'open_vsplit', -- ["S"] = "split_with_window_picker", -- ["s"] = "vsplit_with_window_picker", ['t'] = 'open_tabnew', ['C'] = 'close_node', ['ma'] = { 'add', -- some commands may take optional config options, see `:h neo-tree-mappings` for details config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['md'] = 'delete', ['y'] = 'copy_to_clipboard', ['x'] = 'cut_to_clipboard', ['p'] = 'paste_from_clipboard', ['m'] = 'none', ['mc'] = { 'copy', config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['mm'] = { 'move', config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['R'] = 'refresh', ['?'] = 'show_help', }, }, nesting_rules = {}, filesystem = { filtered_items = { visible = true, -- when true, they will just be displayed differently than normal items hide_dotfiles = false, hide_gitignored = true, hide_hidden = true, -- only works on Windows for hidden files/directories hide_by_name = { --"node_modules" }, hide_by_pattern = { -- uses glob style patterns --"*.meta" }, never_show = { -- remains hidden even if visible is toggled to true '.DS_Store', 'node_modules', }, }, follow_current_file = true, -- This will find and focus the file in the active buffer every -- time the current file is changed while the tree is open. group_empty_dirs = false, -- when true, empty folders will be grouped together hijack_netrw_behavior = 'open_default', -- netrw disabled, opening a directory opens neo-tree -- in whatever position is specified in window.position -- "open_current", -- netrw disabled, opening a directory opens within the -- window like netrw would, regardless of window.position -- "disabled", -- netrw left alone, neo-tree does not handle opening dirs use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes -- instead of relying on nvim autocmd events. window = { mappings = { ['<backspace>'] = 'none', ['<space>'] = 'none', ['.'] = 'set_root', ['I'] = 'toggle_hidden', ['/'] = 'none', ['f'] = 'filter_on_submit', ['<c-x>'] = 'clear_filter', ['[c'] = 'prev_git_modified', [']c'] = 'next_git_modified', ['o'] = 'system_open', }, }, }, buffers = { follow_current_file = true, -- This will find and focus the file in the active buffer every -- time the current file is changed while the tree is open. group_empty_dirs = true, -- when true, empty folders will be grouped together show_unloaded = true, window = { mappings = { ['<bs>'] = 'navigate_up', ['.'] = 'set_root', }, }, }, git_status = { window = { position = 'float', mappings = { ['A'] = 'git_add_all', ['gu'] = 'git_unstage_file', ['ga'] = 'git_add_file', ['gr'] = 'git_revert_file', ['gc'] = 'git_commit', ['gp'] = 'git_push', ['gg'] = 'git_commit_and_push', }, }, }, }) vim.keymap.set('n', '<leader>f', '<cmd>Neotree focus<cr>', {}) vim.keymap.set('n', '<leader><S-f>', '<cmd>Neotree toggle show filesystem<cr>', {}) -- close tree if only buffer open in current tab -- see https://github.com/kyazdani42/nvim-tree.lua/issues/1005#issuecomment-1115831363 -- vim.api.nvim_create_autocmd('BufEnter', { -- command = "if tabpagewinnr(tabpagenr(),'$') == 1 && match(bufname(),'NvimTree_') == 0 | quit | endif", -- nested = true, -- })
vim.cmd([[ let g:neo_tree_remove_legacy_commands = 1 ]]) require('neo-tree').setup({ close_if_last_window = true, -- Close Neo-tree if it is the last window left in the tab popup_border_style = 'rounded', enable_git_status = true, enable_diagnostics = true, default_component_configs = { container = { enable_character_fade = true, }, indent = { indent_size = 1, padding = 0, -- extra padding on left hand side -- indent guides with_markers = true, indent_marker = '│', last_indent_marker = '└', highlight = 'NeoTreeIndentMarker', -- expander config, needed for nesting files with_expanders = nil, -- if nil and file nesting is enabled, will enable expanders expander_collapsed = '', expander_expanded = '', expander_highlight = 'NeoTreeExpander', }, icon = { folder_closed = '', folder_open = '', folder_empty = 'ﰊ', -- The next two settings are only a fallback, if you use nvim-web-devicons and configure default icons there -- then these will never be used. default = '*', highlight = 'NeoTreeFileIcon', }, modified = { symbol = '[+]', highlight = 'NeoTreeModified', }, name = { trailing_slash = false, use_git_status_colors = true, highlight = 'NeoTreeFileName', }, git_status = { symbols = { -- Change type added = '', -- or "✚", but this is redundant info if you use git_status_colors on the name modified = '', -- or "", but this is redundant info if you use git_status_colors on the name deleted = '✖', -- this can only be used in the git_status source renamed = '', -- this can only be used in the git_status source -- Status type untracked = '', ignored = '', unstaged = '', staged = '', conflict = '', }, }, }, window = { position = 'left', width = 40, mapping_options = { noremap = true, nowait = true, }, mappings = { ['<backspace>'] = 'none', ['<space>'] = 'none', ['<cr>'] = 'open_tabnew', ['S'] = 'open_split', ['s'] = 'open_vsplit', -- ["S"] = "split_with_window_picker", -- ["s"] = "vsplit_with_window_picker", ['t'] = 'open_tabnew', ['C'] = 'close_node', ['ma'] = { 'add', -- some commands may take optional config options, see `:h neo-tree-mappings` for details config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['md'] = 'delete', ['y'] = 'copy_to_clipboard', ['x'] = 'cut_to_clipboard', ['p'] = 'paste_from_clipboard', ['m'] = 'none', ['mc'] = { 'copy', config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['mm'] = { 'move', config = { show_path = 'absolute', -- "none", "relative", "absolute" }, }, ['R'] = 'refresh', ['?'] = 'show_help', }, }, nesting_rules = {}, filesystem = { filtered_items = { visible = true, -- when true, they will just be displayed differently than normal items hide_dotfiles = false, hide_gitignored = true, hide_hidden = true, -- only works on Windows for hidden files/directories hide_by_name = { --"node_modules" }, hide_by_pattern = { -- uses glob style patterns --"*.meta" }, never_show = { -- remains hidden even if visible is toggled to true '.DS_Store', 'node_modules', }, }, follow_current_file = true, -- This will find and focus the file in the active buffer every -- time the current file is changed while the tree is open. group_empty_dirs = false, -- when true, empty folders will be grouped together hijack_netrw_behavior = 'open_default', -- netrw disabled, opening a directory opens neo-tree -- in whatever position is specified in window.position -- "open_current", -- netrw disabled, opening a directory opens within the -- window like netrw would, regardless of window.position -- "disabled", -- netrw left alone, neo-tree does not handle opening dirs use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes -- instead of relying on nvim autocmd events. window = { mappings = { ['<backspace>'] = 'none', ['<space>'] = 'none', ['.'] = 'set_root', ['I'] = 'toggle_hidden', ['/'] = 'none', ['f'] = 'filter_on_submit', ['<c-x>'] = 'clear_filter', ['[c'] = 'prev_git_modified', [']c'] = 'next_git_modified', ['o'] = 'system_open', }, }, commands = { system_open = function(state) local node = state.tree:get_node() local path = node:get_id() -- macOs specific -- open file in default application in the background vim.api.nvim_command('silent !open -g ' .. path) end, }, }, buffers = { follow_current_file = true, -- This will find and focus the file in the active buffer every -- time the current file is changed while the tree is open. group_empty_dirs = true, -- when true, empty folders will be grouped together show_unloaded = true, window = { mappings = { ['<bs>'] = 'navigate_up', ['.'] = 'set_root', }, }, }, git_status = { window = { position = 'float', mappings = { ['A'] = 'git_add_all', ['gu'] = 'git_unstage_file', ['ga'] = 'git_add_file', ['gr'] = 'git_revert_file', ['gc'] = 'git_commit', ['gp'] = 'git_push', ['gg'] = 'git_commit_and_push', }, }, }, }) vim.keymap.set('n', '<leader>f', '<cmd>Neotree focus<cr>', {}) vim.keymap.set('n', '<leader><S-f>', '<cmd>Neotree toggle show filesystem<cr>', {}) -- close tree if only buffer open in current tab -- see https://github.com/kyazdani42/nvim-tree.lua/issues/1005#issuecomment-1115831363 -- vim.api.nvim_create_autocmd('BufEnter', { -- command = "if tabpagewinnr(tabpagenr(),'$') == 1 && match(bufname(),'NvimTree_') == 0 | quit | endif", -- nested = true, -- })
fixed command
fixed command
Lua
mit
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
41783d133ca12c592c3f5bec016ce7bf91593d5c
src_trunk/resources/admin-system/c_overlay.lua
src_trunk/resources/admin-system/c_overlay.lua
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do local level = getElementData( value, "adminlevel" ) if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end local adminlevel = getElementData( localPlayer, "adminlevel" ) if adminlevel > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false )
local sx, sy = guiGetScreenSize() local localPlayer = getLocalPlayer() local statusLabel = nil local openReports = 0 local handledReports = 0 local unansweredReports = {} local ownReports = {} -- Admin Titles function getAdminTitle(thePlayer) local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0 local text = ({ "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" })[adminLevel] or "Player" local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0 if (hiddenAdmin==1) then text = text .. " (Hidden)" end return text end function getAdminCount() local online, duty, lead, leadduty = 0, 0, 0, 0 for key, value in ipairs(getElementsByType("player")) do local level = getElementData( value, "adminlevel" ) if level >= 1 then online = online + 1 local aod = getElementData( value, "adminduty" ) if aod == 1 then duty = duty + 1 end if level >= 4 then lead = lead + 1 if aod == 1 then leadduty = leadduty + 1 end end end end return online, duty, lead, leadduty end -- update the labels local function updateGUI() if statusLabel then local online, duty, lead, leadduty = getAdminCount() local reporttext = "" if #unansweredReports > 0 then reporttext = ": #" .. table.concat(unansweredReports, ", #") end local ownreporttext = "" if #ownReports > 0 then ownreporttext = ": #" .. table.concat(ownReports, ", #") end guiSetText( statusLabel, getAdminTitle( localPlayer ) .. " :: " .. getElementData( localPlayer, "gameaccountusername" ) .. " :: " .. duty .. "/" .. online .. " Admins :: " .. leadduty .. "/" .. lead .. " Lead+ Admins :: " .. ( openReports - handledReports ) .. " unanswered reports" .. reporttext .. " :: " .. handledReports .. " handled reports" .. ownreporttext ) end end -- create the gui local function createGUI() if statusLabel then destroyElement(statusLabel) statusLabel = nil end local adminlevel = getElementData( localPlayer, "adminlevel" ) if adminlevel then if adminlevel > 0 then statusLabel = guiCreateLabel( 5, sy - 20, sx - 10, 15, "", false ) updateGUI() --guiCreateLabel ( float x, float y, float width, float height, string text, bool relative, [element parent = nil] ) end end end addEventHandler( "onClientResourceStart", getResourceRootElement(), createGUI, false ) addEventHandler( "onClientElementDataChange", localPlayer, function(n) if n == "adminlevel" then createGUI() end end, false ) addEventHandler( "onClientElementDataChange", getRootElement(), function(n) if getElementType(source) == "player" and ( n == "adminlevel" or n == "adminduty" ) then updateGUI() end end ) addEvent( "updateReportsCount", true ) addEventHandler( "updateReportsCount", getLocalPlayer(), function( open, handled, unanswered, own ) openReports = open handledReports = handled unansweredReports = unanswered ownReports = own or {} updateGUI() end, false )
Fixed overlay
Fixed overlay git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1575 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
082d5f1bcd7eb50cd2b37495e5f126041b8ab0d0
aspects/nvim/files/.config/nvim/lua/wincent/lsp.lua
aspects/nvim/files/.config/nvim/lua/wincent/lsp.lua
local nnoremap = wincent.vim.nnoremap local lsp = {} local on_attach = function () nnoremap('<Leader>ld', "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", {buffer = true, silent = true}) nnoremap('<c-]>', '<cmd>lua vim.lsp.buf.definition()<CR>', {buffer = true, silent = true}) nnoremap('K', "<cmd>lua vim.lsp.buf.hover()<CR>", {buffer = true, silent = true}) nnoremap('gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', {buffer = true, silent = true}) vim.wo.signcolumn = 'yes' end lsp.init = function () local capabilities = vim.lsp.protocol.make_client_capabilities() -- UI tweaks from https://github.com/neovim/nvim-lspconfig/wiki/UI-customization local border = { {"🭽", "FloatBorder"}, {"▔", "FloatBorder"}, {"🭾", "FloatBorder"}, {"▕", "FloatBorder"}, {"🭿", "FloatBorder"}, {"▁", "FloatBorder"}, {"🭼", "FloatBorder"}, {"▏", "FloatBorder"}, } local handlers = { ["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {border = border}), ["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {border = border }), } local has_cmp_nvim_lsp, cmp_nvim_lsp = pcall(require, 'cmp_nvim_lsp') if has_cmp_nvim_lsp then capabilities = cmp_nvim_lsp.update_capabilities(capabilities) end require'lspconfig'.clangd.setup{ capabilities = capabilities, cmd = {'clangd', '--background-index'}, handlers = handlers, on_attach = on_attach, } -- If you're feeling brave after reading: -- -- https://github.com/neovim/nvim-lspconfig/issues/319 -- -- Install: -- -- :LspInstall sumneko_lua -- -- After marvelling at the horror that is the installation script: -- -- https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/sumneko_lua.lua -- -- To see path: -- -- :LspInstallInfo sumneko_lua -- -- See: https://github.com/neovim/nvim-lspconfig#sumneko_lua -- -- Failing that; you can install by hand: -- -- https://github.com/sumneko/lua-language-server/wiki/Build-and-Run-(Standalone) -- local cmd = nil if vim.fn.has('mac') == 1 then cmd = vim.fn.expand('~/code/lua-language-server/bin/macOS/lua-language-server') if vim.fn.executable(cmd) == 1 then cmd = {cmd, '-E', vim.fn.expand('~/code/lua-language-server/main.lua')} else cmd = nil end elseif vim.fn.has('unix') == 1 then cmd = '/usr/bin/lua-language-server' if vim.fn.executable(cmd) == 1 then cmd = {cmd} else cmd = nil end else cmd = 'lua-language-server' if vim.fn.executable(cmd) == 1 then cmd = {cmd} else cmd = nil end end if cmd ~= nil then require'lspconfig'.sumneko_lua.setup{ capabilities = capabilities, cmd = cmd, handlers = handlers, on_attach = on_attach, settings = { Lua = { diagnostics = { enable = true, globals = {'vim'}, }, filetypes = {'lua'}, runtime = { path = vim.split(package.path, ';'), version = 'LuaJIT', }, } }, } end require'lspconfig'.ocamlls.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } require'lspconfig'.rust_analyzer.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } require'lspconfig'.solargraph.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } --[[ require'lspconfig'.sorbet.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } --]] require'lspconfig'.tsserver.setup{ capabilities = capabilities, -- cmd = { -- "typescript-language-server", -- "--stdio", -- "--tsserver-log-file", -- "tslog" -- }, handlers = handlers, on_attach = on_attach, } require'lspconfig'.vimls.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } end lsp.set_up_highlights = function () local pinnacle = require'wincent.pinnacle' vim.cmd('highlight DiagnosticError ' .. pinnacle.decorate('italic,underline', 'ModeMsg')) vim.cmd('highlight DiagnosticHint ' .. pinnacle.decorate('bold,italic,underline', 'Type')) vim.cmd('highlight DiagnosticSignHint ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('Type'), })) vim.cmd('highlight DiagnosticSignError ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('ErrorMsg'), })) vim.cmd('highlight DiagnosticSignInformation ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('DiagnosticHint'), })) vim.cmd('highlight DiagnosticSignWarning ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('DiagnosticHint'), })) end return lsp
local nnoremap = wincent.vim.nnoremap local lsp = {} local on_attach = function () nnoremap('<Leader>ld', "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", {buffer = true, silent = true}) nnoremap('<c-]>', '<cmd>lua vim.lsp.buf.definition()<CR>', {buffer = true, silent = true}) nnoremap('K', "<cmd>lua vim.lsp.buf.hover()<CR>", {buffer = true, silent = true}) nnoremap('gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', {buffer = true, silent = true}) vim.wo.signcolumn = 'yes' end lsp.init = function () local capabilities = vim.lsp.protocol.make_client_capabilities() -- UI tweaks from https://github.com/neovim/nvim-lspconfig/wiki/UI-customization local border = { {"🭽", "FloatBorder"}, {"▔", "FloatBorder"}, {"🭾", "FloatBorder"}, {"▕", "FloatBorder"}, {"🭿", "FloatBorder"}, {"▁", "FloatBorder"}, {"🭼", "FloatBorder"}, {"▏", "FloatBorder"}, } local handlers = { ["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {border = border}), ["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {border = border }), } local has_cmp_nvim_lsp, cmp_nvim_lsp = pcall(require, 'cmp_nvim_lsp') if has_cmp_nvim_lsp then capabilities = cmp_nvim_lsp.update_capabilities(capabilities) end require'lspconfig'.clangd.setup{ capabilities = capabilities, cmd = {'clangd', '--background-index'}, handlers = handlers, on_attach = on_attach, } local cmd = nil if vim.fn.has('mac') == 1 then cmd = vim.fn.expand('~/code/lua-language-server/bin/lua-language-server') if vim.fn.executable(cmd) == 1 then cmd = {cmd, '-E', vim.fn.expand('~/code/lua-language-server/main.lua')} else cmd = nil end elseif vim.fn.has('unix') == 1 then cmd = '/usr/bin/lua-language-server' if vim.fn.executable(cmd) == 1 then cmd = {cmd} else cmd = nil end else cmd = 'lua-language-server' if vim.fn.executable(cmd) == 1 then cmd = {cmd} else cmd = nil end end if cmd ~= nil then -- Prerequisite: https://github.com/sumneko/lua-language-server/wiki/Build-and-Run require'lspconfig'.sumneko_lua.setup{ capabilities = capabilities, cmd = cmd, handlers = handlers, on_attach = on_attach, settings = { Lua = { diagnostics = { enable = true, globals = {'vim'}, }, filetypes = {'lua'}, runtime = { path = vim.split(package.path, ';'), version = 'LuaJIT', }, } }, } end require'lspconfig'.ocamlls.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } require'lspconfig'.rust_analyzer.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } require'lspconfig'.solargraph.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } --[[ require'lspconfig'.sorbet.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } --]] require'lspconfig'.tsserver.setup{ capabilities = capabilities, -- cmd = { -- "typescript-language-server", -- "--stdio", -- "--tsserver-log-file", -- "tslog" -- }, handlers = handlers, on_attach = on_attach, } require'lspconfig'.vimls.setup{ capabilities = capabilities, handlers = handlers, on_attach = on_attach, } end lsp.set_up_highlights = function () local pinnacle = require'wincent.pinnacle' vim.cmd('highlight DiagnosticError ' .. pinnacle.decorate('italic,underline', 'ModeMsg')) vim.cmd('highlight DiagnosticHint ' .. pinnacle.decorate('bold,italic,underline', 'Type')) vim.cmd('highlight DiagnosticSignHint ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('Type'), })) vim.cmd('highlight DiagnosticSignError ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('ErrorMsg'), })) vim.cmd('highlight DiagnosticSignInformation ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('DiagnosticHint'), })) vim.cmd('highlight DiagnosticSignWarning ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('DiagnosticHint'), })) end return lsp
chore(nvim): remove stale lua-language-server instructions
chore(nvim): remove stale lua-language-server instructions Seeing as lua-language-server regularly pegs the CPU for me, and it's been a while since I built it, going to see whether a new version fixes it. This change from November 2020: https://github.com/sumneko/lua-language-server/issues/247 looks promising, and I think my build predates that... Fingers crossed. Built using: cd $path_to_clone_of_lua_language_server_repo git pull git submodule update --recursive cd 3rd/luamake ./compile/install.sh cd ../.. ./3rd/luamake/luamake rebuild Then back out unsolicited changes to `~/.zshrc` 🤦 and update path in my config to the built executable (the binary in the `macOS/` subdirectory is there, but won't boot, failing to load "bee.so" which is right next to it).
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
995c9bc341e4acc83c035327585472d3c568ee07
overlay/ast/product/hi-linux/rules.lua
overlay/ast/product/hi-linux/rules.lua
-- HiSilicon Linux SDK package { 'ast-files' } package { 'hi-kernel' } package { 'hi-sdk', 'target', { 'patch', { 'hi-kernel', 'unpack' }, }, { 'prepare', requires = { 'toolchain' } }, { 'hiboot' }, { 'linux' }, { 'common' }, { 'msp' }, { 'component' }, { 'mkload' }, } package { 'hi-drivers', 'target', { 'configure', { 'hi-sdk', 'linux', 'target' } } } package { 'rtl8188eu', 'target', { 'build', { 'hi-sdk', 'linux', 'target' } } } package { 'cmake-modules' } package { 'hi-utils', 'target', { 'configure', { 'cmake-modules', 'unpack' }, { 'hi-sdk', 'component', 'target' } } } package { 'karaoke-player', 'target', { 'configure', requires = { 'chicken-eggs', 'ffmpeg', 'libass', 'libuv', 'soundtouch', }, { 'cmake-modules', 'unpack' }, { 'hi-sdk', 'component', 'target' }, } } package { 'rootfs', 'target', { 'install', requires = { 'busybox', 'connman', 'dropbear', 'hi-drivers', 'hi-utils', 'karaoke-player', 'libnl', 'rtl8188eu', }, { 'ast-files', 'unpack' }, { 'hi-sdk', 'mkload', 'target' } }, } if jagen.flag 'debug' then package { 'strace', 'target' } end
-- HiSilicon Linux SDK package { 'ast-files' } package { 'hi-kernel' } package { 'hi-sdk', 'target', { 'patch', { 'hi-kernel', 'unpack' }, }, { 'prepare', requires = { 'toolchain' } }, { 'hiboot' }, { 'linux' }, { 'common' }, { 'msp' }, { 'component' }, { 'mkload' }, } package { 'hi-drivers', 'target', { 'configure', { 'hi-sdk', 'linux', 'target' } } } package { 'rtl8188eu', 'target', { 'compile', { 'hi-sdk', 'linux', 'target' } } } package { 'cmake-modules' } package { 'hi-utils', 'target', { 'configure', { 'cmake-modules', 'unpack' }, { 'hi-sdk', 'component', 'target' } } } package { 'karaoke-player', 'target', { 'configure', requires = { 'chicken-eggs', 'connman', 'ffmpeg', 'libass', 'libuv', 'soundtouch', }, { 'cmake-modules', 'unpack' }, { 'hi-sdk', 'component', 'target' }, } } package { 'rootfs', 'target', { 'install', requires = { 'busybox', 'dropbear', 'hi-drivers', 'hi-utils', 'karaoke-player', 'rtl8188eu', }, { 'ast-files', 'unpack' }, { 'hi-sdk', 'mkload', 'target' } }, } if jagen.flag 'debug' then package { 'strace', 'target' } end
Misc fixes for hi-linux rule dependencies
Misc fixes for hi-linux rule dependencies
Lua
mit
bazurbat/jagen
01e745f6f2698a1b087f9f93930d463db8e5094d
hikyuu_pywrap/xmake.lua
hikyuu_pywrap/xmake.lua
option("boost-python-suffix") set_default("3X") set_showmenu(true) set_category("hikyuu") set_description("Set suffix of libboost_python. ", "Boost.python 1.67 later use 3x like libboost_python35, ", "but older is libboost_python3", " - 3X autocheck for 35, 36, 37, 3x") option_end() add_includedirs("../hikyuu_cpp") -- Can't use static boost.python lib, the function that using 'arg' will load failed! --add_defines("BOOST_PYTHON_STATIC_LIB") if is_plat("windows") then add_defines("HKU_API=__declspec(dllimport)") add_cxflags("-wd4566") end local cc = get_config("cc") local cxx = get_config("cxx") if (cc and string.find(cc, "clang")) or (cxx and string.find(cxx, "clang")) then add_cxflags("-Wno-error=parentheses-equality -Wno-error=missing-braces") end --on_load("xmake_on_load") target("core") set_kind("shared") if is_mode("debug") then set_default(false) --会默认禁用这个target的编译,除非显示指定xmake build _hikyuu才会去编译,但是target还存在,里面的files会保留到vcproj --set_enable(false) --set_enable(false)会彻底禁用这个target,连target的meta也不会被加载,vcproj不会保留它 end add_packages("fmt", "spdlog") add_deps("hikyuu") if is_plat("windows") then set_filename("core.pyd") add_cxflags("-wd4251") else set_filename("core.so") end add_files("./**.cpp") add_rpathdirs("$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib") on_load(function(target) import("lib.detect.find_tool") if is_plat("windows") then -- detect installed python3 local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0") assert(python.version > "3", python.version .. " python version must > 3.0, please use python3.0 or later!") -- find python include and libs directory local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"") pydir = path.directory(pydir) target:add("includedirs", pydir .. "/include") target:add("linkdirs", pydir .. "/libs") return end if is_plat("macosx") then local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib" target:add("linkdirs", libdir) local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() --local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10)) local python_lib = format("python%s.%s", string.sub(ver,8,8), string.sub(ver,10,10)) target:add("links", python_lib) end -- get python include directory. local pydir = try { function () return os.iorun("python3-config --includes"):trim() end } assert(pydir, "python3-config not found!") target:add("cxflags", pydir) -- get suffix configure for link libboost_pythonX.so local suffix = get_config("boost-python-suffix") if suffix == nil then raise("You need to config --boost-python-suffix specify libboost_python suffix") end suffix = string.upper(suffix) if suffix == "3X" then local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10) target:add("links", boost_python_lib) else target:add("links", "boost_python"..suffix) end end) after_build(function(target) if is_plat("macosx") then local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() local boost_python_lib = format("libboost_python%s%s.dylib", string.sub(ver,8,8), string.sub(ver,10,10)) os.run(format("install_name_tool -change @rpath/libhikyuu.dylib @loader_path/libhikyuu.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_date_time.dylib @loader_path/libboost_date_time.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_filesystem.dylib @loader_path/libboost_filesystem.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_system.dylib @loader_path/libboost_system.dylib %s/%s", target:targetdir(), "core.so")) os.run(format("install_name_tool -change @rpath/libboost_serialization.dylib @loader_path/libboost_serialization.dylib %s/%s", target:targetdir(), "core.so")) os.run(format("install_name_tool -change @rpath/%s @loader_path/%s %s/%s", boost_python_lib, boost_python_lib, target:targetdir(), "core.so")) end local dst_dir = "$(projectdir)/hikyuu/cpp/" if is_plat("windows") then os.cp(target:targetdir() .. '/core.pyd', dst_dir) os.cp(target:targetdir() .. '/hikyuu.dll', dst_dir) elseif is_plat("macosx") then os.cp(target:targetdir() .. '/core.so', dst_dir) os.cp(target:targetdir() .. '/libhikyuu.dylib', dst_dir) else os.cp(target:targetdir() .. '/core.so', dst_dir) os.cp(target:targetdir() .. '/libhikyuu.so', dst_dir) end --os.cp("$(env BOOST_LIB)/boost_date_time*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/boost_filesystem*.dll", dst_dir) os.cp("$(env BOOST_LIB)/boost_python3*.dll", dst_dir) os.cp("$(env BOOST_LIB)/boost_serialization*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/boost_system*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_date_time*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_filesystem*.so.*", dst_dir) os.cp("$(env BOOST_LIB)/libboost_python3*.so.*", dst_dir) os.cp("$(env BOOST_LIB)/libboost_serialization*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_system*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_date_time*.dylib", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_filesystem*.dylib", dst_dir) os.cp("$(env BOOST_LIB)/libboost_python3*.dylib", dst_dir) os.cp("$(env BOOST_LIB)/libboost_serialization*.dylib", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_system*.dylib", dst_dir) if is_plat("windows") then if is_mode("release") then os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) else os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5_D.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) end os.cp("$(projectdir)/hikyuu_extern_libs/pkg/mysql.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) end end)
option("boost-python-suffix") set_default("3X") set_showmenu(true) set_category("hikyuu") set_description("Set suffix of libboost_python. ", "Boost.python 1.67 later use 3x like libboost_python35, ", "but older is libboost_python3", " - 3X autocheck for 35, 36, 37, 3x") option_end() add_includedirs("../hikyuu_cpp") -- Can't use static boost.python lib, the function that using 'arg' will load failed! --add_defines("BOOST_PYTHON_STATIC_LIB") if is_plat("windows") then add_defines("HKU_API=__declspec(dllimport)") add_cxflags("-wd4566") end local cc = get_config("cc") local cxx = get_config("cxx") if (cc and string.find(cc, "clang")) or (cxx and string.find(cxx, "clang")) then add_cxflags("-Wno-error=parentheses-equality -Wno-error=missing-braces") end --on_load("xmake_on_load") target("core") set_kind("shared") if is_mode("debug") then set_default(false) --会默认禁用这个target的编译,除非显示指定xmake build _hikyuu才会去编译,但是target还存在,里面的files会保留到vcproj --set_enable(false) --set_enable(false)会彻底禁用这个target,连target的meta也不会被加载,vcproj不会保留它 end add_packages("fmt", "spdlog") add_deps("hikyuu") if is_plat("windows") then set_filename("core.pyd") add_cxflags("-wd4251") else set_filename("core.so") end add_files("./**.cpp") add_rpathdirs("$ORIGIN", "$ORIGIN/lib", "$ORIGIN/../lib") on_load(function(target) import("lib.detect.find_tool") if is_plat("windows") then -- detect installed python3 local python = assert(find_tool("python", {version = true}), "python not found, please install it first! note: python version must > 3.0") assert(python.version > "3", python.version .. " python version must > 3.0, please use python3.0 or later!") -- find python include and libs directory local pydir = os.iorun("python -c \"import sys; print(sys.executable)\"") pydir = path.directory(pydir) target:add("includedirs", pydir .. "/include") target:add("linkdirs", pydir .. "/libs") return end if is_plat("macosx") then local libdir = os.iorun("python3-config --prefix"):trim() .. "/lib" target:add("linkdirs", libdir) local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() --local python_lib = format("python%s.%sm", string.sub(ver,8,8), string.sub(ver,10,10)) local python_lib = format("python%s.%s", string.sub(ver,8,8), string.sub(ver,10,10)) target:add("links", python_lib) end -- get python include directory. local pydir = try { function () return os.iorun("python3-config --includes"):trim() end } assert(pydir, "python3-config not found!") target:add("cxflags", pydir) -- get suffix configure for link libboost_pythonX.so local suffix = get_config("boost-python-suffix") if suffix == nil then raise("You need to config --boost-python-suffix specify libboost_python suffix") end suffix = string.upper(suffix) if suffix == "3X" then local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() local boost_python_lib = "boost_python"..string.sub(ver,8,8)..string.sub(ver,10,10) target:add("links", boost_python_lib) else target:add("links", "boost_python"..suffix) end end) after_build(function(target) if is_plat("macosx") then local out, err = os.iorun("python3 --version") local ver = (out .. err):trim() local boost_python_lib = format("libboost_python%s%s.dylib", string.sub(ver,8,8), string.sub(ver,10,10)) os.run(format("install_name_tool -change @rpath/libhikyuu.dylib @loader_path/libhikyuu.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_date_time.dylib @loader_path/libboost_date_time.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_filesystem.dylib @loader_path/libboost_filesystem.dylib %s/%s", target:targetdir(), "core.so")) --os.run(format("install_name_tool -change @rpath/libboost_system.dylib @loader_path/libboost_system.dylib %s/%s", target:targetdir(), "core.so")) os.run(format("install_name_tool -change @rpath/libboost_serialization.dylib @loader_path/libboost_serialization.dylib %s/%s", target:targetdir(), "core.so")) os.run(format("install_name_tool -change @rpath/%s @loader_path/%s %s/%s", boost_python_lib, boost_python_lib, target:targetdir(), "core.so")) end local dst_dir = "$(projectdir)/hikyuu/cpp/" if is_plat("windows") then os.cp(target:targetdir() .. '/core.pyd', dst_dir) os.cp(target:targetdir() .. '/hikyuu.dll', dst_dir) os.cp(target:targetdir() .. '/sqlite3.dll', dst_dir) elseif is_plat("macosx") then os.cp(target:targetdir() .. '/core.so', dst_dir) os.cp(target:targetdir() .. '/libhikyuu.dylib', dst_dir) else os.cp(target:targetdir() .. '/core.so', dst_dir) os.cp(target:targetdir() .. '/libhikyuu.so', dst_dir) end --os.cp("$(env BOOST_LIB)/boost_date_time*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/boost_filesystem*.dll", dst_dir) os.cp("$(env BOOST_LIB)/boost_python3*.dll", dst_dir) os.cp("$(env BOOST_LIB)/boost_serialization*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/boost_system*.dll", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_date_time*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_filesystem*.so.*", dst_dir) os.cp("$(env BOOST_LIB)/libboost_python3*.so.*", dst_dir) os.cp("$(env BOOST_LIB)/libboost_serialization*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_system*.so.*", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_date_time*.dylib", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_filesystem*.dylib", dst_dir) os.cp("$(env BOOST_LIB)/libboost_python3*.dylib", dst_dir) os.cp("$(env BOOST_LIB)/libboost_serialization*.dylib", dst_dir) --os.cp("$(env BOOST_LIB)/libboost_system*.dylib", dst_dir) if is_plat("windows") then if is_mode("release") then os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) else os.cp("$(projectdir)/hikyuu_extern_libs/pkg/hdf5_D.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) end os.cp("$(projectdir)/hikyuu_extern_libs/pkg/mysql.pkg/lib/$(mode)/$(plat)/$(arch)/*.dll", dst_dir) end end)
fixed 缺失拷贝sqlite3.dll
fixed 缺失拷贝sqlite3.dll
Lua
mit
fasiondog/hikyuu
69ed20adf7368c47cd657beb6666b0f86b471f51
kong/error_handlers.lua
kong/error_handlers.lua
local kong = kong local find = string.find local fmt = string.format local CONTENT_TYPE = "Content-Type" local ACCEPT = "Accept" local TYPE_JSON = "application/json" local TYPE_GRPC = "application/grpc" local TYPE_HTML = "text/html" local TYPE_XML = "application/xml" local HEADERS_JSON = { [CONTENT_TYPE] = "application/json; charset=utf-8" } local HEADERS_HTML = { [CONTENT_TYPE] = "text/html; charset=utf-8" } local HEADERS_XML = { [CONTENT_TYPE] = "application/xml; charset=utf-8" } local HEADERS_PLAIN = { [CONTENT_TYPE] = "text/plain; charset=utf-8" } local JSON_TEMPLATE = [[ { "message": "%s" } ]] local HTML_TEMPLATE = [[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>Kong Error</title> </head> <body> <h1>Kong Error</h1> <p>%s.</p> </body> </html> ]] local XML_TEMPLATE = [[ <?xml version="1.0" encoding="UTF-8"?> <error> <message>%s</message> </error> ]] local PLAIN_TEMPLATE = "%s\n" local BODIES = { s400 = "Bad request", s404 = "Not found", s408 = "Request timeout", s411 = "Length required", s412 = "Precondition failed", s413 = "Payload too large", s414 = "URI too long", s417 = "Expectation failed", s494 = "Request header or cookie too large", s500 = "An unexpected error occurred", s502 = "An invalid response was received from the upstream server", s503 = "The upstream server is currently unavailable", s504 = "The upstream server is timing out", default = "The upstream server responded with %d" } return function(ctx) local accept_header = kong.request.get_header(ACCEPT) if accept_header == nil then accept_header = kong.request.get_header(CONTENT_TYPE) if accept_header == nil then accept_header = kong.configuration.error_default_type end end local status = kong.response.get_status() local message = BODIES["s" .. status] or fmt(BODIES.default, status) local headers if find(accept_header, TYPE_JSON, nil, true) == 1 then message = fmt(JSON_TEMPLATE, message) headers = HEADERS_JSON elseif find(accept_header, TYPE_GRPC, nil, true) == 1 then message = { message = message } elseif find(accept_header, TYPE_HTML, nil, true) == 1 then message = fmt(HTML_TEMPLATE, message) headers = HEADERS_HTML elseif find(accept_header, TYPE_XML, nil, true) == 1 then message = fmt(XML_TEMPLATE, message) headers = HEADERS_XML else message = fmt(PLAIN_TEMPLATE, message) headers = HEADERS_PLAIN end -- Reset relevant context values kong.ctx.core.buffered_proxying = nil kong.ctx.core.response_body = nil if ctx then ctx.delay_response = nil ctx.delayed_response = nil ctx.delayed_response_callback = nil end return kong.response.exit(status, message, headers) end
local kong = kong local find = string.find local fmt = string.format local CONTENT_TYPE = "Content-Type" local ACCEPT = "Accept" local TYPE_JSON = "application/json" local TYPE_GRPC = "application/grpc" local TYPE_HTML = "text/html" local TYPE_XML = "application/xml" local JSON_TEMPLATE = [[ { "message": "%s" } ]] local HTML_TEMPLATE = [[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>Kong Error</title> </head> <body> <h1>Kong Error</h1> <p>%s.</p> </body> </html> ]] local XML_TEMPLATE = [[ <?xml version="1.0" encoding="UTF-8"?> <error> <message>%s</message> </error> ]] local PLAIN_TEMPLATE = "%s\n" local BODIES = { s400 = "Bad request", s404 = "Not found", s408 = "Request timeout", s411 = "Length required", s412 = "Precondition failed", s413 = "Payload too large", s414 = "URI too long", s417 = "Expectation failed", s494 = "Request header or cookie too large", s500 = "An unexpected error occurred", s502 = "An invalid response was received from the upstream server", s503 = "The upstream server is currently unavailable", s504 = "The upstream server is timing out", default = "The upstream server responded with %d" } return function(ctx) local accept_header = kong.request.get_header(ACCEPT) if accept_header == nil then accept_header = kong.request.get_header(CONTENT_TYPE) if accept_header == nil then accept_header = kong.configuration.error_default_type end end local status = kong.response.get_status() local message = BODIES["s" .. status] or fmt(BODIES.default, status) local headers if find(accept_header, TYPE_JSON, nil, true) == 1 then message = fmt(JSON_TEMPLATE, message) headers = { [CONTENT_TYPE] = "application/json; charset=utf-8" } elseif find(accept_header, TYPE_GRPC, nil, true) == 1 then message = { message = message } elseif find(accept_header, TYPE_HTML, nil, true) == 1 then message = fmt(HTML_TEMPLATE, message) headers = { [CONTENT_TYPE] = "text/html; charset=utf-8" } elseif find(accept_header, TYPE_XML, nil, true) == 1 then message = fmt(XML_TEMPLATE, message) headers = { [CONTENT_TYPE] = "application/xml; charset=utf-8" } else message = fmt(PLAIN_TEMPLATE, message) headers = { [CONTENT_TYPE] = "text/plain; charset=utf-8" } end -- Reset relevant context values kong.ctx.core.buffered_proxying = nil kong.ctx.core.response_body = nil if ctx then ctx.delay_response = nil ctx.delayed_response = nil ctx.delayed_response_callback = nil end return kong.response.exit(status, message, headers) end
fix(errors) use new header tables in error handler (#5673)
fix(errors) use new header tables in error handler (#5673) Create new header tables for each run of the error handler. Previously, HEADERS_JSON and similar were defined at the module level, and the error handler used the same table each time, passing it by reference to kong.response.exit(). The exit-transformer plugin allows kong.response.exit() to modify these tables, resulting in an issue where its modifications would persist for subsequent requests, even if the exit-transformer did not apply to them. Creating new tables for each run of the error handler avoids this.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
5acc3d7000117d98fb4302cfc621d97ce3fdd590
src/soul.lua
src/soul.lua
local soul = {} local conversation = require("conversation") local utils = require("utils") local lfs = require("lfs") commands = {} broadcasts = {} for file in lfs.dir("commands") do local command = file:match("^(.+).lua") if (command) then local path = "commands." .. command package.loaded[path] = nil local status, ret = pcall(require, path) if (status) then commands[command] = ret logger:info("loaded " .. path) else logger:error(ret) end end end soul.tick = function() local group_list = { -1001497094866, -1001126076013, -1001103633366, -1001208316368, -1001487484295 } if lfs.touch("/var/www/server.sforest.in/.emergency") then os.execute("rm /var/www/server.sforest.in/.emergency") for k, v in pairs(group_list) do local ret = bot.sendMessage{ chat_id = v, text = "有人向 @SJoshua 发起了紧急联络请求。如果您能够(在线下)联系到 Master 的话,麻烦使用 /emergency_informed 来删除广播信息,非常感谢。" } table.insert(broadcasts, {chat_id = v, message_id = ret.result.message_id}) end end end soul.onMessageReceive = function(msg) msg.text = msg.text:gsub("@" .. bot.info.username, "") msg.chat.id = math.floor(msg.chat.id) msg.from.id = math.floor(msg.from.id) if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then return true end if os.time() - msg.date > config.ignore then return true end for k, v in pairs(commands) do if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then if v.limit then if v.limit.disable then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, the command is disabled.", reply_to_message_id = msg.message_id } elseif v.limit.master and msg.from.username ~= config.master then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, permission denied.", reply_to_message_id = msg.message_id } elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then return commands.help.func(msg, k) end end return v.func(msg) end end for keyword, reply in pairs(conversation) do local match = false if type(keyword) == "string" then match = msg.text:find(keyword) elseif type(keyword) == "table" then for i = 1, #keyword do match = match or msg.text:find(keyword[i]) end if keyword.reply and not msg.reply_to_message then match = false end elseif type(keyword) == "function" then match = keyword(msg.text) end if match then local ans, rep local rep_type = "Markdown" if type(reply) == "string" then ans = reply elseif type(reply) == "table" then ans = utils.rand(table.unpack(reply)) if reply.reply then rep = msg.message_id elseif reply.reply_to_reply and msg.reply_to_message then rep = msg.reply_to_message.message_id end if reply.type then rep_type = reply.type end elseif type(reply) == "function" then ans = tostring(reply()) end if ans:find("^sticker#%S-$") then return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep) elseif ans:find("^document#%S-$") then return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep) else return bot.sendMessage{ chat_id = msg.chat.id, text = ans, parse_mode = rep_type, reply_to_message_id = rep } end end end end soul.ignore = function(msg) end soul.onEditedMessageReceive = soul.ignore soul.onLeftChatMembersReceive = soul.ignore soul.onNewChatMembersReceive = soul.ignore soul.onPhotoReceive = soul.ignore soul.onAudioReceive = soul.ignore soul.onVoiceReceive = soul.ignore soul.onVideoReceive = soul.ignore soul.onDocumentReceive = soul.ignore soul.onGameReceive = soul.ignore soul.onStickerReceive = soul.ignore soul.onDiceReceive = soul.ignore soul.onVideoNoteReceive = soul.ignore soul.onContactReceive = soul.ignore soul.onLocationReceive = soul.ignore soul.onPinnedMessageReceive = soul.ignore setmetatable(soul, { __index = function(t, key) logger:warn("called undefined processer " .. key) return (function() return false end) end }) return soul
local soul = {} local conversation = require("conversation") local utils = require("utils") local lfs = require("lfs") commands = {} broadcasts = {} for file in lfs.dir("commands") do local command = file:match("^(.+).lua") if (command) then local path = "commands." .. command package.loaded[path] = nil local status, ret = pcall(require, path) if (status) then commands[command] = ret logger:info("loaded " .. path) else logger:error(ret) end end end soul.tick = function() local group_list = { -1001497094866, -1001126076013, -1001103633366, -1001208316368, -1001487484295 } if lfs.touch("/tmp/.emergency") then os.execute("rm /tmp/.emergency") for k, v in pairs(group_list) do local ret = bot.sendMessage{ chat_id = v, text = "有人向 @SJoshua 发起了紧急联络请求。如果您能够(在线下)联系到 Master 的话,麻烦使用 /emergency_informed 来删除广播信息,非常感谢。" } table.insert(broadcasts, {chat_id = v, message_id = ret.result.message_id}) end end end soul.onMessageReceive = function(msg) msg.text = msg.text:gsub("@" .. bot.info.username, "") msg.chat.id = math.floor(msg.chat.id) msg.from.id = math.floor(msg.from.id) if msg.text:find("/(%S+)@(%S+)[Bb][Oo][Tt]") then return true end if os.time() - msg.date > config.ignore then return true end for k, v in pairs(commands) do if msg.text:find("^%s*/" .. k) and not msg.text:find("^%s*/" .. k .. "%S") then if v.limit then if v.limit.disable then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, the command is disabled.", reply_to_message_id = msg.message_id } elseif v.limit.master and msg.from.username ~= config.master then return bot.sendMessage{ chat_id = msg.chat.id, text = "Sorry, permission denied.", reply_to_message_id = msg.message_id } elseif (v.limit.match or v.limit.reply) and not ((v.limit.match and msg.text:find(v.limit.match)) or (v.limit.reply and msg.reply_to_message)) then return commands.help.func(msg, k) end end return v.func(msg) end end for keyword, reply in pairs(conversation) do local match = false if type(keyword) == "string" then match = msg.text:find(keyword) elseif type(keyword) == "table" then for i = 1, #keyword do match = match or msg.text:find(keyword[i]) end if keyword.reply and not msg.reply_to_message then match = false end elseif type(keyword) == "function" then match = keyword(msg.text) end if match then local ans, rep local rep_type = "Markdown" if type(reply) == "string" then ans = reply elseif type(reply) == "table" then ans = utils.rand(table.unpack(reply)) if reply.reply then rep = msg.message_id elseif reply.reply_to_reply and msg.reply_to_message then rep = msg.reply_to_message.message_id end if reply.type then rep_type = reply.type end elseif type(reply) == "function" then ans = tostring(reply()) end if ans:find("^sticker#%S-$") then return bot.sendSticker(msg.chat.id, ans:match("^sticker#(%S-)$"), nil, rep) elseif ans:find("^document#%S-$") then return bot.sendDocument(msg.chat.id, ans:match("^document#(%S-)$"), nil, nil, rep) else return bot.sendMessage{ chat_id = msg.chat.id, text = ans, parse_mode = rep_type, reply_to_message_id = rep } end end end end soul.ignore = function(msg) end soul.onEditedMessageReceive = soul.ignore soul.onLeftChatMembersReceive = soul.ignore soul.onNewChatMembersReceive = soul.ignore soul.onPhotoReceive = soul.ignore soul.onAudioReceive = soul.ignore soul.onVoiceReceive = soul.ignore soul.onVideoReceive = soul.ignore soul.onDocumentReceive = soul.ignore soul.onGameReceive = soul.ignore soul.onStickerReceive = soul.ignore soul.onDiceReceive = soul.ignore soul.onVideoNoteReceive = soul.ignore soul.onContactReceive = soul.ignore soul.onLocationReceive = soul.ignore soul.onPinnedMessageReceive = soul.ignore setmetatable(soul, { __index = function(t, key) logger:warn("called undefined processer " .. key) return (function() return false end) end }) return soul
fix(soul): modified path due to permission issues.
fix(soul): modified path due to permission issues.
Lua
apache-2.0
SJoshua/Project-Small-R
c2f31ea4438145d66bb330cd587be7f8d92ebae6
MapTable.lua
MapTable.lua
local MapTable, parent = torch.class('nn.MapTable', 'nn.Container') function MapTable:__init(module, shared) parent.__init(self) self.shared = shared or true self.sharedparams = {'weight', 'bias', 'gradWeight', 'gradBias'} self.output = {} self.gradInput = {} self:add(module) end function MapTable:_extend(n) self.modules[1] = self.module for i = 2, n do if not self.modules[i] then if shared then self.modules[i] = self.module:clone(table.unpack(self.sharedparams)) else self.modules[i] = self.module:clone(table.unpack(self.sharedparams)) end end end end function MapTable:resize(n) self:_extend(n) for i = n + 1, #self.modules do -- It's not clear why this clearState call is necessary, but it fixes -- https://github.com/torch/nn/issues/1141 . self.modules[i]:clearState() self.modules[i] = nil end end function MapTable:add(module) assert(not self.module, 'Single module required') self.module = module self.modules[1] = self.module return self end function MapTable:updateOutput(input) self.output = {} self:_extend(#input) for i = 1, #input do self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', input[i]) end return self.output end function MapTable:updateGradInput(input, gradOutput) self.gradInput = {} self:_extend(#input) for i = 1, #input do self.gradInput[i] = self:rethrowErrors(self.modules[i], i, 'updateGradInput', input[i], gradOutput[i]) end return self.gradInput end function MapTable:accGradParameters(input, gradOutput, scale) scale = scale or 1 self:_extend(#input) for i = 1, #input do self:rethrowErrors(self.modules[i], i, 'accGradParameters', input[i], gradOutput[i], scale) end end function MapTable:accUpdateGradParameters(input, gradOutput, lr) lr = lr or 1 self:_extend(#input) for i = 1, #input do self:rethrowErrors(self.modules[i], i, 'accUpdateGradParameters', input[i], gradOutput[i], lr) end end function MapTable:zeroGradParameters() if self.module then if self.shared then self.module:zeroGradParameters() else parent.zeroGradParameters(self) end end end function MapTable:updateParameters(learningRate) if self.module then if self.shared then self.module:updateParameters(learningRate) else parent.updateParameters(self, learningRate) end end end function MapTable:clearState() for i = 2, #self.modules do -- It's not clear why this clearState call is necessary, but it fixes -- https://github.com/torch/nn/issues/1141 . self.modules[i]:clearState() self.modules[i] = nil end parent.clearState(self) end function MapTable:__tostring__() local tab = ' ' local line = '\n' local extlast = ' ' local str = torch.type(self) if self.module then str = str .. ' {' .. line .. tab str = str .. tostring(self.module):gsub(line, line .. tab .. extlast) .. line .. '}' else str = str .. ' { }' end return str end
local MapTable, parent = torch.class('nn.MapTable', 'nn.Container') function MapTable:__init(module, shared) parent.__init(self) if shared ~= nil then self.shared = shared else self.shared = true end self.sharedparams = {'weight', 'bias', 'gradWeight', 'gradBias'} self.output = {} self.gradInput = {} self:add(module) end function MapTable:_extend(n) self.modules[1] = self.module for i = 2, n do if not self.modules[i] then if shared then self.modules[i] = self.module:clone(table.unpack(self.sharedparams)) else self.modules[i] = self.module:clone(table.unpack(self.sharedparams)) end end end end function MapTable:resize(n) self:_extend(n) for i = n + 1, #self.modules do -- It's not clear why this clearState call is necessary, but it fixes -- https://github.com/torch/nn/issues/1141 . self.modules[i]:clearState() self.modules[i] = nil end end function MapTable:add(module) assert(not self.module, 'Single module required') self.module = module self.modules[1] = self.module return self end function MapTable:updateOutput(input) self.output = {} self:_extend(#input) for i = 1, #input do self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', input[i]) end return self.output end function MapTable:updateGradInput(input, gradOutput) self.gradInput = {} self:_extend(#input) for i = 1, #input do self.gradInput[i] = self:rethrowErrors(self.modules[i], i, 'updateGradInput', input[i], gradOutput[i]) end return self.gradInput end function MapTable:accGradParameters(input, gradOutput, scale) scale = scale or 1 self:_extend(#input) for i = 1, #input do self:rethrowErrors(self.modules[i], i, 'accGradParameters', input[i], gradOutput[i], scale) end end function MapTable:accUpdateGradParameters(input, gradOutput, lr) lr = lr or 1 self:_extend(#input) for i = 1, #input do self:rethrowErrors(self.modules[i], i, 'accUpdateGradParameters', input[i], gradOutput[i], lr) end end function MapTable:zeroGradParameters() if self.module then if self.shared then self.module:zeroGradParameters() else parent.zeroGradParameters(self) end end end function MapTable:updateParameters(learningRate) if self.module then if self.shared then self.module:updateParameters(learningRate) else parent.updateParameters(self, learningRate) end end end function MapTable:clearState() for i = 2, #self.modules do -- It's not clear why this clearState call is necessary, but it fixes -- https://github.com/torch/nn/issues/1141 . self.modules[i]:clearState() self.modules[i] = nil end parent.clearState(self) end function MapTable:__tostring__() local tab = ' ' local line = '\n' local extlast = ' ' local str = torch.type(self) if self.module then str = str .. ' {' .. line .. tab str = str .. tostring(self.module):gsub(line, line .. tab .. extlast) .. line .. '}' else str = str .. ' { }' end return str end
LittleFix self.shared was always true
LittleFix self.shared was always true
Lua
bsd-3-clause
nicholas-leonard/nn
9ced2e7e5c0441aee082c3aac68dfc3f1485d02b
main.lua
main.lua
io.stdout:setvbuf("no") local reboot, events = false --Internal Callbacks-- function love.load(args) love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run(arg) while true do events = require("Engine.events") events:register("love:reboot",function(args) --events:trigger("love:rebooting",args) reboot = args or {} end) if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(reboot or arg) end reboot = false -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v and v[1] then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end if reboot then for k,v in pairs(package.loaded) do if k ~= "bit" then package.loaded[k] = nil end end--Reset the required packages events = nil --Must undefine this. break --Break our game loop end end end end
io.stdout:setvbuf("no") local reboot, events = false --Internal Callbacks-- function love.load(args) love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS. events:trigger("love:load") end function love.run(arg) while true do events = require("Engine.events") events:register("love:reboot",function(args) --events:trigger("love:rebooting",args) reboot = args or {} end) if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(reboot or arg) end reboot = false -- We don't want the first frame's dt to include time taken by love.load. if love.timer then love.timer.step() end local dt = 0 -- Main loop time. while true do -- Process events. if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then local r = events:trigger("love:quit") for k,v in pairs(r) do if v and v[1] then r = nil break end end if r then return a end else events:trigger("love:"..name,a,b,c,d,e,f) end end end -- Update dt, as we'll be passing it to update if love.timer then love.timer.step() dt = love.timer.getDelta() end -- Call update and draw events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled if love.graphics and love.graphics.isActive() then events:trigger("love:graphics") end if love.timer then love.timer.sleep(0.001) end if reboot then for k,v in pairs(package.loaded) do if k ~= "bit" then package.loaded[k] = nil end end--Reset the required packages love.graphics.reset() --Reset the GPU events = nil --Must undefine this. break --Break our game loop end end end end
Glitch Fix
Glitch Fix
Lua
mit
RamiLego4Game/LIKO-12
9994f71e28b924edca27188e2da2ff4a2043992b
spinach/brokers/redis_scripts/register_periodic_tasks.lua
spinach/brokers/redis_scripts/register_periodic_tasks.lua
local broker_id = ARGV[1] local now = ARGV[2] local periodic_tasks_hash = ARGV[3] local periodic_tasks_queue = ARGV[4] -- tasks to register starting at ARGV[5] local function contains(t, e) return t[e] end local old_task_names = redis.call('hkeys', periodic_tasks_hash) local new_task_names = {} for i=5, #ARGV do local task_json = ARGV[i] local task = cjson.decode(task_json) local next_event_time = now + task["periodicity"] new_task_names[task["name"]] = true if redis.call('hexists', periodic_tasks_hash, task["name"]) == 0 then redis.call('zadd', periodic_tasks_queue, next_event_time, task["name"]) end redis.call('hset', periodic_tasks_hash, task["name"], task_json) end for i=1, #old_task_names do local old_task_name = old_task_names[i] if not contains(new_task_names, old_task_name) then redis.call('hdel', periodic_tasks_hash, old_task_name) end end
local broker_id = ARGV[1] local now = ARGV[2] local periodic_tasks_hash = ARGV[3] local periodic_tasks_queue = ARGV[4] -- tasks to register starting at ARGV[5] local function contains(t, e) return t[e] end local old_task_names = redis.call('hkeys', periodic_tasks_hash) local new_task_names = {} for i=5, #ARGV do local task_json = ARGV[i] local task = cjson.decode(task_json) local next_event_time = now + task["periodicity"] new_task_names[task["name"]] = true if redis.call('hexists', periodic_tasks_hash, task["name"]) == 0 then -- the periodic task is new, add it to the queue redis.call('zadd', periodic_tasks_queue, next_event_time, task["name"]) else local existing_task_json = redis.call('hget', periodic_tasks_hash, task["name"]) local existing_task = cjson.decode(existing_task_json) if existing_task["periodicity"] ~= task["periodicity"] then -- the periodic task already existed but the periodicity changed -- so it is reset redis.call('zadd', periodic_tasks_queue, next_event_time, task["name"]) end end -- unconditionnally override the task in the hash redis.call('hset', periodic_tasks_hash, task["name"], task_json) end for i=1, #old_task_names do local old_task_name = old_task_names[i] if not contains(new_task_names, old_task_name) then redis.call('hdel', periodic_tasks_hash, old_task_name) redis.call('zrem', periodic_tasks_queue, old_task_name) end end
Reset periodic task score when periodicity is changed
Reset periodic task score when periodicity is changed When the periodicity of a periodic task was changed, it has to wait until the next planed execution before being changed. Thus switching from 1 week periodicity to 1 second meant waiting one full week before seeing the change reflected. This commit fixes this issue by completely reseting a periodic task when its periodicity changes.
Lua
bsd-2-clause
NicolasLM/spinach
d3e02d05c62bcbbe5492c4d37a27aa585a19742e
frontend/ui/elements/screen_dpi_menu_table.lua
frontend/ui/elements/screen_dpi_menu_table.lua
local _ = require("gettext") local Device = require("device") local Screen = Device.screen local T = require("ffi/util").template local function isAutoDPI() return Device.screen_dpi_override == nil end local function dpi() return Screen:getDPI() end local function custom() return G_reader_settings:readSetting("custom_screen_dpi") end local function setDPI(_dpi) local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") UIManager:show(InfoMessage:new{ text = _dpi and T(_("DPI set to %1. This will take effect after restarting."), _dpi) or _("DPI set to auto. This will take effect after restarting."), }) G_reader_settings:saveSetting("screen_dpi", _dpi) Device:setScreenDPI(_dpi) end local dpi_auto = Screen.device.screen_dpi local dpi_small = 120 local dpi_medium = 160 local dpi_large = 240 local dpi_xlarge = 320 local dpi_xxlarge = 480 local dpi_xxxlarge = 640 return { text = _("Screen DPI"), sub_item_table = { { text = dpi_auto and T(_("Auto DPI (%1)"), dpi_auto) or _("Auto DPI"), help_text = _("The DPI of your screen is automatically detected so items can be drawn with the right amount of pixels. This will usually display at (roughly) the same size on different devices, while remaining sharp. Increasing the DPI setting will result in larger text and icons, while a lower DPI setting will look smaller on the screen."), checked_func = isAutoDPI, callback = function() setDPI() end }, { text = T(_("Small (%1)"), dpi_small), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi <= 140 and _dpi ~= _custom end, callback = function() setDPI(dpi_small) end }, { text = T(_("Medium (%1)"), dpi_medium), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 140 and _dpi <= 200 and _dpi ~= _custom end, callback = function() setDPI(dpi_medium) end }, { text = T(_("Large (%1)"), dpi_large), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 200 and _dpi <= 280 and _dpi ~= _custom end, callback = function() setDPI(dpi_large) end }, { text = T(_("Extra large (%1)"), dpi_xlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 280 and _dpi <= 400 and _dpi ~= _custom end, callback = function() setDPI(dpi_xlarge) end }, { text = T(_("Extra-Extra Large (%1)"), dpi_xxlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 400 and _dpi <= 560 and _dpi ~= _custom end, callback = function() setDPI(dpi_xxlarge) end }, { text = T(_("Extra-Extra-Extra Large (%1)"), dpi_xxxlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 560 and _dpi ~= _custom end, callback = function() setDPI(dpi_xxxlarge) end }, { text_func = function() return T(_("Custom DPI: %1 (hold to set)"), custom() or dpi_auto) end, checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _custom and _dpi == _custom end, callback = function() setDPI(custom() or dpi_auto) end, hold_input = { title = _("Enter custom screen DPI"), type = "number", hint = "(90 - 900)", callback = function(input) local _dpi = tonumber(input) _dpi = _dpi < 90 and 90 or _dpi _dpi = _dpi > 900 and 900 or _dpi G_reader_settings:saveSetting("custom_screen_dpi", _dpi) setDPI(_dpi) end, ok_text = _("Set custom DPI"), }, }, } }
local _ = require("gettext") local Device = require("device") local Screen = Device.screen local T = require("ffi/util").template local function isAutoDPI() return Device.screen_dpi_override == nil end local function dpi() return Screen:getDPI() end local function custom() return G_reader_settings:readSetting("custom_screen_dpi") end local function setDPI(_dpi) local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") UIManager:show(InfoMessage:new{ text = _dpi and T(_("DPI set to %1. This will take effect after restarting."), _dpi) or _("DPI set to auto. This will take effect after restarting."), }) G_reader_settings:saveSetting("screen_dpi", _dpi) Device:setScreenDPI(_dpi) end local function spinWidgetSetDPI(touchmenu_instance) local SpinWidget = require("ui/widget/spinwidget") local UIManager = require("ui/uimanager") local items = SpinWidget:new{ width = Screen:getWidth() * 0.6, value = custom() or dpi(), value_min = 90, value_max = 900, value_step = 10, value_hold_step = 50, ok_text = _("Set DPI"), title_text = _("Set custom screen DPI"), callback = function(spin) G_reader_settings:saveSetting("custom_screen_dpi", spin.value) setDPI(spin.value) touchmenu_instance:updateItems() end } UIManager:show(items) end local dpi_auto = Screen.device.screen_dpi local dpi_small = 120 local dpi_medium = 160 local dpi_large = 240 local dpi_xlarge = 320 local dpi_xxlarge = 480 local dpi_xxxlarge = 640 return { text = _("Screen DPI"), sub_item_table = { { text = dpi_auto and T(_("Auto DPI (%1)"), dpi_auto) or _("Auto DPI"), help_text = _("The DPI of your screen is automatically detected so items can be drawn with the right amount of pixels. This will usually display at (roughly) the same size on different devices, while remaining sharp. Increasing the DPI setting will result in larger text and icons, while a lower DPI setting will look smaller on the screen."), checked_func = isAutoDPI, callback = function() setDPI() end }, { text = T(_("Small (%1)"), dpi_small), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi <= 140 and _dpi ~= _custom end, callback = function() setDPI(dpi_small) end }, { text = T(_("Medium (%1)"), dpi_medium), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 140 and _dpi <= 200 and _dpi ~= _custom end, callback = function() setDPI(dpi_medium) end }, { text = T(_("Large (%1)"), dpi_large), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 200 and _dpi <= 280 and _dpi ~= _custom end, callback = function() setDPI(dpi_large) end }, { text = T(_("Extra large (%1)"), dpi_xlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 280 and _dpi <= 400 and _dpi ~= _custom end, callback = function() setDPI(dpi_xlarge) end }, { text = T(_("Extra-Extra Large (%1)"), dpi_xxlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 400 and _dpi <= 560 and _dpi ~= _custom end, callback = function() setDPI(dpi_xxlarge) end }, { text = T(_("Extra-Extra-Extra Large (%1)"), dpi_xxxlarge), checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _dpi and _dpi > 560 and _dpi ~= _custom end, callback = function() setDPI(dpi_xxxlarge) end }, { text_func = function() local custom_dpi = custom() or dpi_auto if custom_dpi then return T(_("Custom DPI: %1 (hold to set)"), custom() or dpi_auto) else return _("Custom DPI") end end, checked_func = function() if isAutoDPI() then return false end local _dpi, _custom = dpi(), custom() return _custom and _dpi == _custom end, callback = function(touchmenu_instance) if custom() then setDPI(custom() or dpi_auto) else spinWidgetSetDPI(touchmenu_instance) end end, hold_callback = function(touchmenu_instance) spinWidgetSetDPI(touchmenu_instance) end, }, } }
Fix: set custom screen DPI (#5165)
Fix: set custom screen DPI (#5165) Settings -> Screen -> Screen DPI When custom DPI is not set we see ugly information with %1:
Lua
agpl-3.0
poire-z/koreader,NiLuJe/koreader,koreader/koreader,mwoz123/koreader,poire-z/koreader,pazos/koreader,koreader/koreader,Frenzie/koreader,Frenzie/koreader,Hzj-jie/koreader,mihailim/koreader,NiLuJe/koreader,Markismus/koreader
8e329b2c4e06f795f2a9cd81f77e9dc2d3339460
docker/notelauncher.lua
docker/notelauncher.lua
-- -- Module for managing notebook container instances running with the docker module -- -- author: Steve Chan sychan@lbl.gov -- -- Copyright 2013 The Regents of the University of California, -- Lawrence Berkeley National Laboratory -- United States Department of Energy -- The DOE Systems Biology Knowledgebase (KBase) -- Made available under the KBase Open Source License -- local M = {} local docker = require('docker') local json = require('json') local p = require('pl.pretty') local lfs = require('lfs') -- This is the repository name, can be set by whoever instantiates a notelauncher M.repository_image = 'kbase/narrative' -- This is the tag to use, defaults to latest M.repository_version = 'latest' -- This is the port that should be exposed from the container, the service in the container -- should have a listener on here configured M.private_port = 8888 -- This is the path to the syslog Unix socket listener in the host environment -- it is imported into the container via a Volumes argument M.syslog_src = '/dev/log' -- -- Query the docker container for a list of containers and -- return a list of the container names that have listeners on -- port 8888. Keyed on container name, value is IP:Port that can -- be fed into an nginx proxy target local function get_notebooks() local ok, res = pcall(docker.client.containers,docker.client) local portmap = {} ngx.log( ngx.DEBUG, string.format("list containers result: %s",p.write(res.body))) if ok then for index,container in pairs(res.body) do -- we only care about containers matching repository_image and listening on the proper port first,last = string.find(container.Image,M.repository_image) if first == 1 then name = string.sub(container.Names[1],2,-1) portmap[name]={} for i, v in pairs(container.Ports) do if v.PrivatePort == M.private_port then portmap[name] = string.format("127.0.0.1:%u", v.PublicPort) end end end end return portmap else local msg = string.format("Failed to fetch list of containers: %s",p.write(res.body)) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Actually launch a new docker container. -- local function launch_notebook( name ) -- don't wrap this in a pcall, if it fails let it propagate to -- the caller portmap = get_notebooks() assert(portmap[name] == nil, "Notebook by this name already exists: " .. name) local conf = docker.config() local bind_syslog = nil conf.Image = string.format("%s:%s",M.repository_image,M.repository_version) conf.Cmd={name} conf.PortSpecs = {tostring(M.private_port)} ngx.log(ngx.INFO,string.format("Spinning up instance of %s on port %d",conf.Image, M.private_port)) -- we wrap the next call in pcall because we want to trap the case where we get an -- error and try deleting the old container and creating a new one again local ok,res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) if not ok and res.response.status >= 409 then -- conflict, try to delete it and then create it again ngx.log(ngx.ERR,string.format("conflicting notebook, removing notebook named: %s",name)) ok, res = pcall( docker.client.remove_container, docker.client, { id = name }) ngx.log(ngx.ERR,string.format("response from remove_container: %s", p.write(res.response))) -- ignore the response and retry the create, and if it still errors, let that propagate ok, res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) end if ok then assert(res.status == 201, "Failed to create container: " .. json.encode(res.body)) local id = res.body.Id if M.syslog_src then -- Make sure it exists and is writeable local stat = lfs.attributes(M.syslog_src) if stat ~= nil and stat.mode == 'socket' then bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") } --ngx.log(ngx.ERR,string.format("Binding %s in container %s", bind_syslog[1], name)) else --ngx.log(ngx.ERR,string.format("%s is not writeable, not mounting in container %s",M.syslog_src, name)) end end if bind_syslog ~= nil then res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true, Binds = bind_syslog }} else res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true }} end assert(res.status == 204, "Failed to start container " .. id .. " : " .. json.encode(res.body)) -- get back the container info to pull out the port mapping res = docker.client:inspect_container{ id=id} --p.dump(res) assert(res.status == 200, "Could not inspect new container: " .. id) local ports = res.body.NetworkSettings.Ports local ThePort = string.format("%d/tcp", M.private_port) local log, occ = string.gsub(res.body.HostsPath, "hosts", "root/tmp/kbase-narrative.log") local count = 5 local ready = false while (count > 0 and not ready) do ngx.log(ngx.INFO, "Testing for presense of kbase-narrative log file.") local f = io.open(name, "r") if f ~= nil then io.close(f) ready = true end ct = ct - 1 ngx.sleep(2) end if not ready then local msg = "Time out starting container: " .. id ngx.log(ngx.ERR,msg) error(msg) end assert(ports[ThePort] ~= nil, string.format("Port binding for port %s not found!",ThePort)) return(string.format("%s:%d","127.0.0.1", ports[ThePort][1].HostPort)) else local msg = "Failed to create container: " .. p.write(res) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Kill and remove an existing docker container. -- local function remove_notebook( name ) local portmap = get_notebooks() assert(portmap[name], "Notebook by this name does not exist: " .. name) local id = string.format('/%s',name) --ngx.log(ngx.INFO,string.format("removing notebook named: %s",id)) local res = docker.client:stop_container{ id = id } --ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to stop container: " .. json.encode(res.body)) res = docker.client:remove_container{ id = id} --ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to remove container " .. id .. " : " .. json.encode(res.body)) return true end M.docker = docker M.get_notebooks = get_notebooks M.launch_notebook = launch_notebook M.remove_notebook = remove_notebook return M
-- -- Module for managing notebook container instances running with the docker module -- -- author: Steve Chan sychan@lbl.gov -- -- Copyright 2013 The Regents of the University of California, -- Lawrence Berkeley National Laboratory -- United States Department of Energy -- The DOE Systems Biology Knowledgebase (KBase) -- Made available under the KBase Open Source License -- local M = {} local docker = require('docker') local json = require('json') local p = require('pl.pretty') local lfs = require('lfs') -- This is the repository name, can be set by whoever instantiates a notelauncher M.repository_image = 'kbase/narrative' -- This is the tag to use, defaults to latest M.repository_version = 'latest' -- This is the port that should be exposed from the container, the service in the container -- should have a listener on here configured M.private_port = 8888 -- This is the path to the syslog Unix socket listener in the host environment -- it is imported into the container via a Volumes argument M.syslog_src = '/dev/log' -- -- Query the docker container for a list of containers and -- return a list of the container names that have listeners on -- port 8888. Keyed on container name, value is IP:Port that can -- be fed into an nginx proxy target local function get_notebooks() local ok, res = pcall(docker.client.containers,docker.client) local portmap = {} ngx.log( ngx.DEBUG, string.format("list containers result: %s",p.write(res.body))) if ok then for index,container in pairs(res.body) do -- we only care about containers matching repository_image and listening on the proper port first,last = string.find(container.Image,M.repository_image) if first == 1 then name = string.sub(container.Names[1],2,-1) portmap[name]={} for i, v in pairs(container.Ports) do if v.PrivatePort == M.private_port then portmap[name] = string.format("127.0.0.1:%u", v.PublicPort) end end end end return portmap else local msg = string.format("Failed to fetch list of containers: %s",p.write(res.body)) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Actually launch a new docker container. -- local function launch_notebook( name ) -- don't wrap this in a pcall, if it fails let it propagate to -- the caller portmap = get_notebooks() assert(portmap[name] == nil, "Notebook by this name already exists: " .. name) local conf = docker.config() local bind_syslog = nil conf.Image = string.format("%s:%s",M.repository_image,M.repository_version) conf.Cmd={name} conf.PortSpecs = {tostring(M.private_port)} ngx.log(ngx.INFO,string.format("Spinning up instance of %s on port %d",conf.Image, M.private_port)) -- we wrap the next call in pcall because we want to trap the case where we get an -- error and try deleting the old container and creating a new one again local ok,res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) if not ok and res.response.status >= 409 then -- conflict, try to delete it and then create it again ngx.log(ngx.ERR,string.format("conflicting notebook, removing notebook named: %s",name)) ok, res = pcall( docker.client.remove_container, docker.client, { id = name }) ngx.log(ngx.ERR,string.format("response from remove_container: %s", p.write(res.response))) -- ignore the response and retry the create, and if it still errors, let that propagate ok, res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) end if ok then assert(res.status == 201, "Failed to create container: " .. json.encode(res.body)) local id = res.body.Id if M.syslog_src then -- Make sure it exists and is writeable local stat = lfs.attributes(M.syslog_src) if stat ~= nil and stat.mode == 'socket' then bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") } --ngx.log(ngx.ERR,string.format("Binding %s in container %s", bind_syslog[1], name)) else --ngx.log(ngx.ERR,string.format("%s is not writeable, not mounting in container %s",M.syslog_src, name)) end end if bind_syslog ~= nil then res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true, Binds = bind_syslog }} else res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true }} end assert(res.status == 204, "Failed to start container " .. id .. " : " .. json.encode(res.body)) -- get back the container info to pull out the port mapping res = docker.client:inspect_container{ id=id} --p.dump(res) assert(res.status == 200, "Could not inspect new container: " .. id) local ports = res.body.NetworkSettings.Ports local ThePort = string.format("%d/tcp", M.private_port) local log_file, occ = string.gsub(res.body.HostsPath, "hosts", "root/tmp/kbase-narrative.log") local count = 5 local ready = false while (count > 0 and not ready) do ngx.log(ngx.INFO, "Testing for presense of kbase-narrative log file.") local f = io.open(log_file, "r") if f ~= nil then io.close(f) ready = true end ct = ct - 1 ngx.sleep(2) end if not ready then local msg = "Time out starting container: " .. id ngx.log(ngx.ERR,msg) error(msg) end assert(ports[ThePort] ~= nil, string.format("Port binding for port %s not found!",ThePort)) return(string.format("%s:%d","127.0.0.1", ports[ThePort][1].HostPort)) else local msg = "Failed to create container: " .. p.write(res) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Kill and remove an existing docker container. -- local function remove_notebook( name ) local portmap = get_notebooks() assert(portmap[name], "Notebook by this name does not exist: " .. name) local id = string.format('/%s',name) --ngx.log(ngx.INFO,string.format("removing notebook named: %s",id)) local res = docker.client:stop_container{ id = id } --ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to stop container: " .. json.encode(res.body)) res = docker.client:remove_container{ id = id} --ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to remove container " .. id .. " : " .. json.encode(res.body)) return true end M.docker = docker M.get_notebooks = get_notebooks M.launch_notebook = launch_notebook M.remove_notebook = remove_notebook return M
More bugfixes in Lua.
More bugfixes in Lua.
Lua
mit
briehl/narrative,scanon/narrative,aekazakov/narrative,rsutormin/narrative,mlhenderson/narrative,psnovichkov/narrative,briehl/narrative,mlhenderson/narrative,kbase/narrative,kbase/narrative,msneddon/narrative,psnovichkov/narrative,kbase/narrative,scanon/narrative,mlhenderson/narrative,aekazakov/narrative,nlharris/narrative,nlharris/narrative,mlhenderson/narrative,jmchandonia/narrative,rsutormin/narrative,aekazakov/narrative,msneddon/narrative,scanon/narrative,psnovichkov/narrative,nlharris/narrative,briehl/narrative,nlharris/narrative,jmchandonia/narrative,kbase/narrative,pranjan77/narrative,msneddon/narrative,briehl/narrative,mlhenderson/narrative,aekazakov/narrative,jmchandonia/narrative,scanon/narrative,scanon/narrative,psnovichkov/narrative,psnovichkov/narrative,pranjan77/narrative,jmchandonia/narrative,pranjan77/narrative,aekazakov/narrative,msneddon/narrative,aekazakov/narrative,nlharris/narrative,psnovichkov/narrative,kbase/narrative,briehl/narrative,nlharris/narrative,jmchandonia/narrative,rsutormin/narrative,rsutormin/narrative,kbase/narrative,briehl/narrative,pranjan77/narrative,pranjan77/narrative,nlharris/narrative,mlhenderson/narrative,pranjan77/narrative,rsutormin/narrative,pranjan77/narrative,scanon/narrative,msneddon/narrative,psnovichkov/narrative,jmchandonia/narrative,rsutormin/narrative,msneddon/narrative,jmchandonia/narrative,briehl/narrative,msneddon/narrative
43330972e959de2b23c3f405381f6d2e49107022
wget.lua
wget.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 --]] -- WGet zpm.wget = { } zpm.wget.downloadUrl = zpm.config.wget.downloadUrl function zpm.wget.downloadWget(destination) local setupFile = path.join(zpm.temp, "wget.exe") if not os.isfile(setupFile) then print("wget not detected - start downloading") if os.is("windows") then os.executef( 'powershell -command "Invoke-WebRequest -Uri %s -OutFile %s"', zpm.wget.downloadUrl, setupFile ) else http.download(zpm.wget.downloadUrl, setupFile) end else print("wget archive detected - start exctracting") end local installDir = path.join(path.getdirectory(destination), "/temp/wget/") os.executef("%s /VERYSILENT /NORESTART /DIR=\"%s\"", setupFile, installDir) local eay32 = path.join(zpm.cache, "libeay32.dll") local iconv2 = path.join(zpm.cache, "libiconv2.dll") local intl3 = path.join(zpm.cache, "libintl3.dll") local ssl32 = path.join(zpm.cache, "libssl32.dll") zpm.assert(os.rename(path.join(installDir, "bin/wget.exe"), destination)) zpm.assert(os.rename(path.join(installDir, "bin/libeay32.dll"), eay32)) zpm.assert(os.rename(path.join(installDir, "bin/libiconv2.dll"), iconv2)) zpm.assert(os.rename(path.join(installDir, "bin/libintl3.dll"), intl3)) zpm.assert(os.rename(path.join(installDir, "bin/libssl32.dll"), ssl32)) zpm.assert(os.isfile(destination), "Wget is not installed!") print("wget succesfully installed") end function zpm.wget.initialise() local dest = path.join(zpm.cache, "wget.exe") if os.get() == "windows" then if not os.isfile(dest) then print("\nLoading wget...") zpm.wget.downloadWget(dest) end zpm.wget.location = dest else zpm.wget.location = "wget" end end function zpm.wget.get(url, header) if header == nil or not header then return os.outputof(zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul") end return os.outputof(zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul") end function zpm.wget.download(destination, url, header) if header == nil or not header then os.execute(zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate") else os.execute(zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\"") end end function zpm.wget.downloadFile(destination, url, header) if header == nil or not header then os.execute(zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate") else os.execute(zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate --header \"" .. header .. "\"") end 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 --]] -- WGet zpm.wget = { } zpm.wget.downloadUrl = zpm.config.wget.downloadUrl function zpm.wget.downloadWget(destination) local setupFile = path.join(zpm.temp, "wget.exe") if not os.isfile(setupFile) then print("wget not detected - start downloading") if os.is("windows") then os.executef( 'powershell -command "Invoke-WebRequest -Uri %s -OutFile %s -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::FireFox"', zpm.wget.downloadUrl, setupFile ) else http.download(zpm.wget.downloadUrl, setupFile) end else print("wget archive detected - start exctracting") end local installDir = path.join(path.getdirectory(destination), "/temp/wget/") os.executef("%s /VERYSILENT /NORESTART /DIR=\"%s\"", setupFile, installDir) local eay32 = path.join(zpm.cache, "libeay32.dll") local iconv2 = path.join(zpm.cache, "libiconv2.dll") local intl3 = path.join(zpm.cache, "libintl3.dll") local ssl32 = path.join(zpm.cache, "libssl32.dll") zpm.assert(os.rename(path.join(installDir, "bin/wget.exe"), destination)) zpm.assert(os.rename(path.join(installDir, "bin/libeay32.dll"), eay32)) zpm.assert(os.rename(path.join(installDir, "bin/libiconv2.dll"), iconv2)) zpm.assert(os.rename(path.join(installDir, "bin/libintl3.dll"), intl3)) zpm.assert(os.rename(path.join(installDir, "bin/libssl32.dll"), ssl32)) zpm.assert(os.isfile(destination), "Wget is not installed!") print("wget succesfully installed") end function zpm.wget.initialise() local dest = path.join(zpm.cache, "wget.exe") if os.get() == "windows" then if not os.isfile(dest) then print("\nLoading wget...") zpm.wget.downloadWget(dest) end zpm.wget.location = dest else zpm.wget.location = "wget" end end function zpm.wget.get(url, header) if header == nil or not header then return os.outputof(zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate 2> nul") end return os.outputof(zpm.wget.location .. " -nv -qO- " .. url .. " --no-check-certificate --header \"" .. header .. "\" 2> nul") end function zpm.wget.download(destination, url, header) if header == nil or not header then os.execute(zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate") else os.execute(zpm.wget.location .. " -N " .. url .. " -O " .. destination .. " --no-check-certificate --header \"" .. header .. "\"") end end function zpm.wget.downloadFile(destination, url, header) if header == nil or not header then os.execute(zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate") else os.execute(zpm.wget.location .. " -N " .. url .. " -P " .. destination .. " --no-check-certificate --header \"" .. header .. "\"") end end
Fixed useragent
Fixed useragent
Lua
mit
Zefiros-Software/ZPM
e802e17b9954788a5ab0f345cda054e625547733
modules/awesomejapan.lua
modules/awesomejapan.lua
local ev = require'ev' local _FLIGHT = ivar2.config.awesomejapan.flight local getDiff = function() local _END = os.date('*t', _FLIGHT) local _NOW = os.date('*t', os.time()) local flipped if(os.time(_END) < os.time(_NOW)) then flipped = true _END, _NOW = _NOW, _END end local _MAX = {60,60,24,os.date('*t',os.time{year=_NOW.year,month=_NOW.month+1,day=0}).day,12} local diff = {} local order = {'sec','min','hour','day','month','year'} for i, v in ipairs(order) do diff[v] = _END[v] - _NOW[v] + (carry and -1 or 0) carry = diff[v] < 0 if(carry) then diff[v] = diff[v] + _MAX[i] end end return diff, flipped end local isOwner = function(source) if(ivar2.config.owners) then for _, mask in next, ivar2.config.owners do if(mask == source.mask) then return true end end end end do local self = ivar2 if(not ivar2.timers) then ivar2.timers = {} end local name = 'Awesome Japan' if(not self.timers[name]) then local today = os.date('*t', os.time()) local midnight = os.time{year = today.year, month = today.month, day = today.day + 1, hour = 0} local now = os.time() local timer = ev.Timer.new( function(loop, timer, revents) local _NOW = os.time() local days, flipped if(_FLIGHT < _NOW) then flipped = true days = math.floor((_NOW - _FLIGHT) / 86400) else days = math.floor((_FLIGHT - _NOW) / 86400) end if(self.config.awesomejapan.chans) then for k, dest in next, self.config.awesomejapan.chans do local locale = 'dag' if(days > 1) then locale = 'dager' end if(flipped) then self:Privmsg(dest, 'Bare %s %s siden awesome guys dro til Japan! *tease*', days, locale) else self:Privmsg(dest, 'Bare %s %s til the awesome guyz drar til Japan!', days, locale) end end end end, midnight - now, 86400 ) self.timers[name] = timer timer:start(ivar2.Loop) end end return { PRIVMSG = { ["^\.awesomejapan%s*$"] = function(self, source, dest) local relative = {} local nor = {'sekund', 'sekunder', 'minutt', 'minutter', 'time', 'timer', 'dag', 'dager', 'måned', 'måneder', 'år', 'år'} local order = {'sec','min','hour','day','month','year'} local diff, flipped = getDiff() for i=#order, 1, -1 do local field = order[i] local d = diff[field] if(d > 0) then local L = (d ~= 1 and i * 2) or (i * 2) - 1 table.insert(relative, string.format('%d %s', d, nor[L])) end end local att = self.config.awesomejapan.guyz local awesome if(att) then local nick = source.nick for _, guy in next, att do if(nick == guy) then awesome = true break end end end if(flipped) then if(awesome) then self:Msg('privmsg', dest, source, 'Bare %s siden DU satt deg på flyet mot Japan. LOL FAIL HOTEL LONER', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Bare %s siden Awesomegjengen satt seg på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end else if(awesome) then self:Msg('privmsg', dest, source, 'Om %s sitter DU og Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Om %s sitter Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end end end, ["^\.awesomejapan stop$"] = function(self, source, dest) if(isOwner(source)) then local name = 'Awesome Japan' self.timers[name]:stop(self.Loop) self.timers[name] = nil end end, } }
local ev = require'ev' local _FLIGHT = ivar2.config.awesomejapan.flight local getDiff = function() local _END = os.date('*t', _FLIGHT) local _NOW = os.date('*t', os.time()) local flipped if(os.time(_END) < os.time(_NOW)) then flipped = true _END, _NOW = _NOW, _END end local _MAX = {60,60,24,os.date('*t',os.time{year=_NOW.year,month=_NOW.month+1,day=0}).day,12} local diff = {} local order = {'sec','min','hour','day','month','year'} for i, v in ipairs(order) do diff[v] = _END[v] - _NOW[v] + (carry and -1 or 0) carry = diff[v] < 0 if(carry) then diff[v] = diff[v] + _MAX[i] end end return diff, flipped end local isOwner = function(source) if(ivar2.config.owners) then for _, mask in next, ivar2.config.owners do if(mask == source.mask) then return true end end end end do local self = ivar2 if(not ivar2.timers) then ivar2.timers = {} end local name = 'Awesome Japan' if(not self.timers[name]) then local today = os.date('*t', os.time()) local midnight = os.time{year = today.year, month = today.month, day = today.day + 1, hour = 0} local now = os.time() local timer = ev.Timer.new( function(loop, timer, revents) local _NOW = os.time() local days, flipped if(_FLIGHT < _NOW) then flipped = true days = math.floor((_NOW - _FLIGHT) / 86400) else days = math.floor((_FLIGHT - _NOW) / 86400) end if(self.config.awesomejapan.chans) then for k, dest in next, self.config.awesomejapan.chans do local locale = 'dag' if(days > 1) then locale = 'dager' end if(flipped) then self:Privmsg(dest, 'Bare %s %s siden awesome guys dro til Japan! *tease*', days, locale) else self:Privmsg(dest, 'Bare %s %s til the awesome guyz drar til Japan!', days, locale) end end end end, midnight - now, 86400 ) self.timers[name] = timer timer:start(ivar2.Loop) end end return { PRIVMSG = { <<<<<<< HEAD ["^\.awesomejapan%s*$"] = function(self, source, dest) ======= ["^%pawesomejapan%s*$"] = function(self, source, dest) >>>>>>> bfd2093... awesomejapan: Fix pattern. local relative = {} local nor = {'sekund', 'sekunder', 'minutt', 'minutter', 'time', 'timer', 'dag', 'dager', 'måned', 'måneder', 'år', 'år'} local order = {'sec','min','hour','day','month','year'} local diff, flipped = getDiff() for i=#order, 1, -1 do local field = order[i] local d = diff[field] if(d > 0) then local L = (d ~= 1 and i * 2) or (i * 2) - 1 table.insert(relative, string.format('%d %s', d, nor[L])) end end local att = self.config.awesomejapan.guyz local awesome if(att) then local nick = source.nick for _, guy in next, att do if(nick == guy) then awesome = true break end end end if(flipped) then if(awesome) then self:Msg('privmsg', dest, source, 'Bare %s siden DU satt deg på flyet mot Japan. LOL FAIL HOTEL LONER', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Bare %s siden Awesomegjengen satt seg på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end else if(awesome) then self:Msg('privmsg', dest, source, 'Om %s sitter DU og Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Om %s sitter Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end end end, ["^%pawesomejapan stop$"] = function(self, source, dest) if(isOwner(source)) then local name = 'Awesome Japan' self.timers[name]:stop(self.Loop) self.timers[name] = nil end end, } }
awesomejapan: Fix pattern.
awesomejapan: Fix pattern. Former-commit-id: 4c298af943f80c8c0629597f635a28ab2d12a6d8 [formerly 0c0e49788fb28d317c534e5b10145529c80ef2e4] Former-commit-id: 91137c2aac8527a3017565ca0c50d11ad618c07f
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
6db6aca3b18c41fe71a2d5baf4fd17d32369f7ff
games/starDash/unit.lua
games/starDash/unit.lua
-- Unit: A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.stardash.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- @classmod Unit local Unit = class(GameObject) -- initializes a Unit with basic logic as provided by the Creer code generator function Unit:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- Whether or not this Unit has performed its action this turn. self.acted = false --- The x value this unit is dashing to. self.dashX = 0 --- The y value this unit is dashing to. self.dashY = 0 --- The remaining health of a unit. self.energy = 0 --- The amount of Generium ore carried by this unit. (0 to job carry capacity - other carried items). self.genarium = 0 --- Tracks wheither or not the ship is dashing. self.isDashing = false --- The Job this Unit has. self.job = nil --- The amount of Legendarium ore carried by this unit. (0 to job carry capacity - other carried items). self.legendarium = 0 --- The distance this unit can still move. self.moves = 0 --- The amount of Mythicite carried by this unit. (0 to job carry capacity - other carried items). self.mythicite = 0 --- The Player that owns and can control this Unit. self.owner = nil --- The martyr ship that is currently shielding this ship if any. self.protector = nil --- The amount of Rarium carried by this unit. (0 to job carry capacity - other carried items). self.rarium = 0 --- The sheild that a martyr ship has. self.shield = 0 --- The x value this unit is on. self.x = 0 --- The y value this unit is on. self.y = 0 --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- Attacks the specified unit. -- @tparam Unit enemy The Unit being attacked. -- @treturn bool True if successfully attacked, false otherwise. function Unit:attack(enemy) return not not (self:_runOnServer("attack", { enemy = enemy, })) end --- Causes the unit to dash towards the designated destination. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:dash(x, y) return not not (self:_runOnServer("dash", { x = x, y = y, })) end --- allows a miner to mine a asteroid -- @tparam Body body The object to be mined. -- @treturn bool True if successfully acted, false otherwise. function Unit:mine(body) return not not (self:_runOnServer("mine", { body = body, })) end --- Moves this Unit from its current location to the new location specified. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:move(x, y) return not not (self:_runOnServer("move", { x = x, y = y, })) end --- tells you if your ship can be at that location. -- @tparam number x The x position of the location you wish to check. -- @tparam number y The y position of the location you wish to check. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:safe(x, y) return not not (self:_runOnServer("safe", { x = x, y = y, })) end --- Attacks the specified projectile. -- @tparam Projectile missile The projectile being shot down. -- @treturn bool True if successfully attacked, false otherwise. function Unit:shootDown(missile) return not not (self:_runOnServer("shootDown", { missile = missile, })) end --- Grab materials from a friendly unit. Doesn't use a action. -- @tparam Unit unit The unit you are grabbing the resources from. -- @tparam number amount The amount of materials to you with to grab. Amounts <= 0 will pick up all the materials that the unit can. -- @tparam string material The material the unit will pick up. 'resource1', 'resource2', or 'resource3'. -- @treturn bool True if successfully taken, false otherwise. function Unit:transfer(unit, amount, material) return not not (self:_runOnServer("transfer", { unit = unit, amount = amount, material = material, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Unit:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Unit
-- Unit: A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.stardash.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A unit in the game. May be a corvette, missleboat, martyr, transport, miner. -- @classmod Unit local Unit = class(GameObject) -- initializes a Unit with basic logic as provided by the Creer code generator function Unit:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- Whether or not this Unit has performed its action this turn. self.acted = false --- The x value this unit is dashing to. self.dashX = 0 --- The y value this unit is dashing to. self.dashY = 0 --- The remaining health of a unit. self.energy = 0 --- The amount of Genarium ore carried by this unit. (0 to job carry capacity - other carried items). self.genarium = 0 --- Tracks wheither or not the ship is dashing. self.isDashing = false --- The Job this Unit has. self.job = nil --- The amount of Legendarium ore carried by this unit. (0 to job carry capacity - other carried items). self.legendarium = 0 --- The distance this unit can still move. self.moves = 0 --- The amount of Mythicite carried by this unit. (0 to job carry capacity - other carried items). self.mythicite = 0 --- The Player that owns and can control this Unit. self.owner = nil --- The martyr ship that is currently shielding this ship if any. self.protector = nil --- The amount of Rarium carried by this unit. (0 to job carry capacity - other carried items). self.rarium = 0 --- The sheild that a martyr ship has. self.shield = 0 --- The x value this unit is on. self.x = 0 --- The y value this unit is on. self.y = 0 --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- Attacks the specified unit. -- @tparam Unit enemy The Unit being attacked. -- @treturn bool True if successfully attacked, false otherwise. function Unit:attack(enemy) return not not (self:_runOnServer("attack", { enemy = enemy, })) end --- Causes the unit to dash towards the designated destination. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:dash(x, y) return not not (self:_runOnServer("dash", { x = x, y = y, })) end --- tells you if your ship dash to that location. -- @tparam number x The x position of the location you wish to arrive. -- @tparam number y The y position of the location you wish to arrive. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:dashable(x, y) return not not (self:_runOnServer("dashable", { x = x, y = y, })) end --- allows a miner to mine a asteroid -- @tparam Body body The object to be mined. -- @treturn bool True if successfully acted, false otherwise. function Unit:mine(body) return not not (self:_runOnServer("mine", { body = body, })) end --- Moves this Unit from its current location to the new location specified. -- @tparam number x The x value of the destination's coordinates. -- @tparam number y The y value of the destination's coordinates. -- @treturn bool True if it moved, false otherwise. function Unit:move(x, y) return not not (self:_runOnServer("move", { x = x, y = y, })) end --- tells you if your ship can move to that location. -- @tparam number x The x position of the location you wish to arrive. -- @tparam number y The y position of the location you wish to arrive. -- @treturn bool True if pathable by this unit, false otherwise. function Unit:safe(x, y) return not not (self:_runOnServer("safe", { x = x, y = y, })) end --- Attacks the specified projectile. -- @tparam Projectile missile The projectile being shot down. -- @treturn bool True if successfully attacked, false otherwise. function Unit:shootDown(missile) return not not (self:_runOnServer("shootDown", { missile = missile, })) end --- Grab materials from a friendly unit. Doesn't use a action. -- @tparam Unit unit The unit you are grabbing the resources from. -- @tparam number amount The amount of materials to you with to grab. Amounts <= 0 will pick up all the materials that the unit can. -- @tparam string material The material the unit will pick up. 'resource1', 'resource2', or 'resource3'. -- @treturn bool True if successfully taken, false otherwise. function Unit:transfer(unit, amount, material) return not not (self:_runOnServer("transfer", { unit = unit, amount = amount, material = material, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Unit:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Unit
Added additional functions that tell the user if it is possible to move or dash to coordinates. Fixed typo.
Added additional functions that tell the user if it is possible to move or dash to coordinates. Fixed typo.
Lua
mit
siggame/Joueur.lua,siggame/Joueur.lua
1d68bdb910132b16593300cbe96529df89f5d4d4
premake5.lua
premake5.lua
local force_cpp = { } function cppforce(inFiles) for _, val in ipairs(inFiles) do for _, fname in ipairs(os.matchfiles(val)) do table.insert(force_cpp, path.getabsolute(fname)) end end end -- gmake premake.override(path, "iscfile", function(base, fname) if table.contains(force_cpp, fname) then return false else return base(fname) end end) -- Visual Studio premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition) if cfg.abspath then if table.contains(force_cpp, cfg.abspath) then _p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition) end end return base(cfg, condition) end) function link_libponyc() configuration "gmake" linkoptions { llvm_config("--ldflags") } configuration "vs*" libdirs { llvm_config("--libdir") } configuration "*" links { "libponyc", "libponyrt" } local output = llvm_config("--libs") for lib in string.gmatch(output, "-l(%S+)") do links { lib } end end function llvm_config(opt) --expect symlink of llvm-config to your config version (e.g llvm-config-3.4) local stream = assert(io.popen("llvm-config " .. opt)) local output = "" --llvm-config contains '\n' while true do local curr = stream:read("*l") if curr == nil then break end output = output .. curr end stream:close() return output end function testsuite() kind "ConsoleApp" language "C++" links "gtest" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "*" if (_OPTIONS["run-tests"]) then configuration "gmake" postbuildcommands { "$(TARGET)" } configuration "vs*" postbuildcommands { "\"$(TargetPath)\"" } configuration "*" end end solution "ponyc" configurations { "Debug", "Release", "Profile" } location( _OPTIONS["to"] ) flags { "FatalWarnings", "MultiProcessorCompile", "ReleaseRuntime" --for all configs } configuration "Debug" targetdir "build/debug" objdir "build/debug/obj" defines "DEBUG" flags { "Symbols" } configuration "Release" targetdir "build/release" objdir "build/release/obj" configuration "Profile" targetdir "build/profile" objdir "build/profile/obj" configuration "Release or Profile" defines "NDEBUG" optimize "Speed" --flags { "LinkTimeOptimization" } if not os.is("windows") then linkoptions { "-flto", "-fuse-ld=gold" } end configuration { "Profile", "gmake" } buildoptions "-pg" linkoptions "-pg" configuration { "Profile", "vs*" } buildoptions "/PROFILE" configuration "vs*" local version = os.outputof("git describe --tags --always") debugdir "." defines { -- disables warnings for vsnprintf "_CRT_SECURE_NO_WARNINGS", "PONY_VERSION=\"" .. string.gsub(version, "\n", "") .. "\"" } configuration { "not windows" } linkoptions { "-pthread" } configuration { "macosx", "gmake" } toolset "clang" buildoptions "-Qunused-arguments" linkoptions "-Qunused-arguments" configuration "gmake" buildoptions { "-march=native" } configuration "vs*" architecture "x64" project "libponyc" targetname "ponyc" kind "StaticLib" language "C" includedirs { llvm_config("--includedir"), "src/common" } files { "src/common/*.h", "src/libponyc/**.c*", "src/libponyc/**.h" } configuration "gmake" buildoptions{ "-std=gnu11" } defines { "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS" } excludes { "src/libponyc/**.cc" } configuration "vs*" defines { "PONY_USE_BIGINT" } cppforce { "src/libponyc/**.c*" } configuration "*" project "libponyrt" targetname "ponyrt" kind "StaticLib" language "C" includedirs { "src/common/", "src/libponyrt/" } files { "src/libponyrt/**.c", "src/libponyrt/**.h" } configuration "gmake" buildoptions { "-std=gnu11" } configuration "vs*" cppforce { "src/libponyrt/**.c" } configuration "*" project "ponyc" kind "ConsoleApp" language "C++" includedirs { "src/common/" } files { "src/ponyc/**.h", "src/ponyc/**.c" } configuration "gmake" buildoptions "-std=gnu11" configuration "vs*" cppforce { "src/ponyc/**.c" } configuration "*" link_libponyc() if ( _OPTIONS["with-tests"] or _OPTIONS["run-tests"] ) then project "gtest" targetname "gtest" language "C++" kind "StaticLib" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "*" includedirs { "utils/gtest" } files { "lib/gtest/gtest-all.cc", "lib/gtest/gtest_main.cc" } project "testc" targetname "testc" testsuite() includedirs { "lib/gtest", "src/common", "src/libponyc" } files { "test/libponyc/**.h", "test/libponyc/**.cc" } link_libponyc() configuration "vs*" defines { "PONY_USE_BIGINT" } configuration "*" project "testrt" targetname "testrt" testsuite() links "libponyrt" includedirs { "lib/gtest", "src/common", "src/libponyrt" } files { "test/libponyrt/**.cc" } end if _ACTION == "clean" then os.rmdir("build") end -- Allow for out-of-source builds. newoption { trigger = "to", value = "path", description = "Set output location for generated files." } newoption { trigger = "with-tests", description = "Compile test suite for every build." } newoption { trigger = "run-tests", description = "Run the test suite on every successful build." }
local force_cpp = { } function cppforce(inFiles) for _, val in ipairs(inFiles) do for _, fname in ipairs(os.matchfiles(val)) do table.insert(force_cpp, path.getabsolute(fname)) end end end -- gmake premake.override(path, "iscfile", function(base, fname) if table.contains(force_cpp, fname) then return false else return base(fname) end end) -- Visual Studio premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition) if cfg.abspath then if table.contains(force_cpp, cfg.abspath) then _p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition) end end return base(cfg, condition) end) function link_libponyc() configuration "gmake" linkoptions { llvm_config("--ldflags") } configuration "vs*" libdirs { llvm_config("--libdir") } configuration "*" links { "libponyc", "libponyrt" } local output = llvm_config("--libs") for lib in string.gmatch(output, "-l(%S+)") do links { lib } end end function llvm_config(opt) --expect symlink of llvm-config to your config version (e.g llvm-config-3.4) local stream = assert(io.popen("llvm-config " .. opt)) local output = "" --llvm-config contains '\n' while true do local curr = stream:read("*l") if curr == nil then break end output = output .. curr end stream:close() return output end function testsuite() kind "ConsoleApp" language "C++" links "gtest" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "*" if (_OPTIONS["run-tests"]) then configuration "gmake" postbuildcommands { "$(TARGET)" } configuration "vs*" postbuildcommands { "\"$(TargetPath)\"" } configuration "*" end end solution "ponyc" configurations { "Debug", "Release", "Profile" } location( _OPTIONS["to"] ) flags { "FatalWarnings", "MultiProcessorCompile", "ReleaseRuntime" --for all configs } configuration "Debug" targetdir "build/debug" objdir "build/debug/obj" defines "DEBUG" flags { "Symbols" } configuration "Release" targetdir "build/release" objdir "build/release/obj" configuration "Profile" targetdir "build/profile" objdir "build/profile/obj" configuration "Release or Profile" defines "NDEBUG" optimize "Speed" --flags { "LinkTimeOptimization" } if not os.is("windows") then linkoptions { "-flto", "-fuse-ld=gold" } end configuration { "Profile", "gmake" } buildoptions "-pg" linkoptions "-pg" configuration { "Profile", "vs*" } buildoptions "/PROFILE" configuration "vs*" local version, exitcode = os.outputof("git describe --tags --always") if exitcode != 0 then version = os.outputof("cat VERSION") end debugdir "." defines { -- disables warnings for vsnprintf "_CRT_SECURE_NO_WARNINGS", "PONY_VERSION=\"" .. string.gsub(version, "\n", "") .. "\"" } configuration { "not windows" } linkoptions { "-pthread" } configuration { "macosx", "gmake" } toolset "clang" buildoptions "-Qunused-arguments" linkoptions "-Qunused-arguments" configuration "gmake" buildoptions { "-march=native" } configuration "vs*" architecture "x64" project "libponyc" targetname "ponyc" kind "StaticLib" language "C" includedirs { llvm_config("--includedir"), "src/common" } files { "src/common/*.h", "src/libponyc/**.c*", "src/libponyc/**.h" } configuration "gmake" buildoptions{ "-std=gnu11" } defines { "__STDC_CONSTANT_MACROS", "__STDC_FORMAT_MACROS", "__STDC_LIMIT_MACROS" } excludes { "src/libponyc/**.cc" } configuration "vs*" defines { "PONY_USE_BIGINT" } cppforce { "src/libponyc/**.c*" } configuration "*" project "libponyrt" targetname "ponyrt" kind "StaticLib" language "C" includedirs { "src/common/", "src/libponyrt/" } files { "src/libponyrt/**.c", "src/libponyrt/**.h" } configuration "gmake" buildoptions { "-std=gnu11" } configuration "vs*" cppforce { "src/libponyrt/**.c" } configuration "*" project "ponyc" kind "ConsoleApp" language "C++" includedirs { "src/common/" } files { "src/ponyc/**.h", "src/ponyc/**.c" } configuration "gmake" buildoptions "-std=gnu11" configuration "vs*" cppforce { "src/ponyc/**.c" } configuration "*" link_libponyc() if ( _OPTIONS["with-tests"] or _OPTIONS["run-tests"] ) then project "gtest" targetname "gtest" language "C++" kind "StaticLib" configuration "gmake" buildoptions { "-std=gnu++11" } configuration "*" includedirs { "utils/gtest" } files { "lib/gtest/gtest-all.cc", "lib/gtest/gtest_main.cc" } project "testc" targetname "testc" testsuite() includedirs { "lib/gtest", "src/common", "src/libponyc" } files { "test/libponyc/**.h", "test/libponyc/**.cc" } link_libponyc() configuration "vs*" defines { "PONY_USE_BIGINT" } configuration "*" project "testrt" targetname "testrt" testsuite() links "libponyrt" includedirs { "lib/gtest", "src/common", "src/libponyrt" } files { "test/libponyrt/**.cc" } end if _ACTION == "clean" then os.rmdir("build") end -- Allow for out-of-source builds. newoption { trigger = "to", value = "path", description = "Set output location for generated files." } newoption { trigger = "with-tests", description = "Compile test suite for every build." } newoption { trigger = "run-tests", description = "Run the test suite on every successful build." }
fix reading version number in premake5 file for windows builds
fix reading version number in premake5 file for windows builds
Lua
bsd-2-clause
ponylang/ponyc,lukecheeseman/ponyta,doublec/ponyc,kulibali/ponyc,kulibali/ponyc,Theodus/ponyc,malthe/ponyc,doublec/ponyc,ryanai3/ponyc,kulibali/ponyc,dckc/ponyc,cquinn/ponyc,Perelandric/ponyc,pap/ponyc,lukecheeseman/ponyta,jupvfranco/ponyc,jonas-l/ponyc,lukecheeseman/ponyta,malthe/ponyc,boemmels/ponyc,ponylang/ponyc,Perelandric/ponyc,Theodus/ponyc,mkfifo/ponyc,malthe/ponyc,mkfifo/ponyc,pap/ponyc,cquinn/ponyc,boemmels/ponyc,sgebbie/ponyc,jonas-l/ponyc,Theodus/ponyc,ponylang/ponyc,Theodus/ponyc,darach/ponyc,jupvfranco/ponyc,Praetonus/ponyc,Praetonus/ponyc,pap/ponyc,jupvfranco/ponyc,jemc/ponyc,mkfifo/ponyc,CausalityLtd/ponyc,CausalityLtd/ponyc,Praetonus/ponyc,dckc/ponyc,Theodus/ponyc,boemmels/ponyc,jemc/ponyc,boemmels/ponyc,jemc/ponyc,cquinn/ponyc,malthe/ponyc,dipinhora/ponyc,Praetonus/ponyc,cquinn/ponyc,CausalityLtd/ponyc,jupvfranco/ponyc,jupvfranco/ponyc,sgebbie/ponyc,ryanai3/ponyc,boemmels/ponyc,sgebbie/ponyc,mkfifo/ponyc,mkfifo/ponyc,jonas-l/ponyc,dipinhora/ponyc,kulibali/ponyc,Perelandric/ponyc,darach/ponyc,shlomif/ponyc,sgebbie/ponyc,Perelandric/ponyc,ryanai3/ponyc,dipinhora/ponyc,shlomif/ponyc,sgebbie/ponyc,doublec/ponyc,darach/ponyc,Perelandric/ponyc
a697e6f2d9049cd89385f67eb22f46d380e9b7ab
InstanceNormalization.lua
InstanceNormalization.lua
require 'nn' _ = [[ An implementation for https://arxiv.org/abs/1607.08022 ]] local InstanceNormalization, parent = torch.class('nn.InstanceNormalization', 'nn.Module') function InstanceNormalization:__init(nOutput, eps, momentum, affine) self.running_mean = torch.zeros(nOutput) self.running_var = torch.ones(nOutput) if affine then self.weight = torch.Tensor(nOutput) self.bias = torch.Tensor(nOutput) self.gradWeight = torch.Tensor(nOutput) self.gradBias = torch.Tensor(nOutput) end self.eps = eps or 1e-5 self.momentum = momentum or 0.1 self.affine = affine self.nOutput = nOutput self.prev_batch_size = -1 end function InstanceNormalization:updateOutput(input) self.output = self.output or input.new() assert(input:size(2) == self.nOutput) local batch_size = input:size(1) if batch_size ~= self.prev_batch_size or (self.bn and self:type() ~= self.bn:type()) then self.bn = nn.SpatialBatchNormalization(input:size(1)*input:size(2), self.eps, self.momentum, self.affine) self.bn:type(self:type()) self.prev_batch_size = input:size(1) end -- Set params for BN self.bn.running_mean:copy(self.running_mean:repeatTensor(batch_size)) self.bn.running_var:copy(self.running_var:repeatTensor(batch_size)) if self.affine then self.bn.weight:copy(self.weight:repeatTensor(batch_size)) self.bn.bias:copy(self.bias:repeatTensor(batch_size)) end -- local input_1obj = input:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) self.output = self.bn:forward(input_1obj):viewAs(input) return self.output end function InstanceNormalization:updateGradInput(input, gradOutput) self.gradInput = self.gradInput or gradOutput.new() assert(self.bn) local input_1obj = input:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) local gradOutput_1obj = gradOutput:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) self.gradInput = self.bn:backward(input_1obj, gradOutput_1obj):viewAs(input) if self.affine then self.gradWeight:add(self.bn.gradWeight:view(input:size(1),self.nOutput):sum(1)) self.gradBias:add(self.bn.gradBias:view(input:size(1),self.nOutput):sum(1)) end return self.gradInput end function InstanceNormalization:clearState() self.output = self.output.new() self.gradInput = self.gradInput.new() self.bn:clearState() end
require 'nn' _ = [[ An implementation for https://arxiv.org/abs/1607.08022 ]] local InstanceNormalization, parent = torch.class('nn.InstanceNormalization', 'nn.Module') function InstanceNormalization:__init(nOutput, eps, momentum, affine) parent.__init(self) self.running_mean = torch.zeros(nOutput) self.running_var = torch.ones(nOutput) self.eps = eps or 1e-5 self.momentum = momentum or 0.1 if affine ~= nil then assert(type(affine) == 'boolean', 'affine has to be true/false') self.affine = affine else self.affine = true end self.nOutput = nOutput self.prev_batch_size = -1 if self.affine then self.weight = torch.Tensor(nOutput):uniform() self.bias = torch.Tensor(nOutput):uniform():div(10):zero() self.gradWeight = torch.Tensor(nOutput) self.gradBias = torch.Tensor(nOutput) end end function InstanceNormalization:updateOutput(input) self.output = self.output or input.new() assert(input:size(2) == self.nOutput) local batch_size = input:size(1) if batch_size ~= self.prev_batch_size or (self.bn and self:type() ~= self.bn:type()) then self.bn = nn.SpatialBatchNormalization(input:size(1)*input:size(2), self.eps, self.momentum, self.affine) self.bn:type(self:type()) self.bn.running_mean:copy(self.running_mean:repeatTensor(batch_size)) self.bn.running_var:copy(self.running_var:repeatTensor(batch_size)) self.prev_batch_size = input:size(1) end -- Get statistics self.running_mean:copy(self.bn.running_mean:view(input:size(1),self.nOutput):mean(1)) self.running_var:copy(self.bn.running_var:view(input:size(1),self.nOutput):mean(1)) -- Set params for BN if self.affine then self.bn.weight:copy(self.weight:repeatTensor(batch_size)) self.bn.bias:copy(self.bias:repeatTensor(batch_size)) end local input_1obj = input:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) self.output = self.bn:forward(input_1obj):viewAs(input) return self.output end function InstanceNormalization:updateGradInput(input, gradOutput) self.gradInput = self.gradInput or gradOutput.new() assert(self.bn) local input_1obj = input:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) local gradOutput_1obj = gradOutput:view(1,input:size(1)*input:size(2),input:size(3),input:size(4)) if self.affine then self.bn.gradWeight:zero() self.bn.gradBias:zero() end self.gradInput = self.bn:backward(input_1obj, gradOutput_1obj):viewAs(input) if self.affine then self.gradWeight:add(self.bn.gradWeight:view(input:size(1),self.nOutput):sum(1)) self.gradBias:add(self.bn.gradBias:view(input:size(1),self.nOutput):sum(1)) end return self.gradInput end function InstanceNormalization:clearState() self.output = self.output.new() self.gradInput = self.gradInput.new() self.bn:clearState() end
fix bugs
fix bugs
Lua
apache-2.0
DmitryUlyanov/texture_nets
9d6096a5f4810430b976dc9cc7d24581e2085d25
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.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.tools.webadmin") require("luci.model.uci") require("luci.util") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) local uci = luci.model.uci.cursor() uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] s:depends("interface", section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) s:depends("interface", section[".name"]) end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true s:option(Flag, "dynamicdhcp").rmempty = true s:option(Value, "name", translate("name")).optional = true ignore = s:option(Flag, "ignore") ignore.optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true s:option(DynamicList, "dhcp_option").optional = true for i, n in ipairs(s.children) do if n ~= iface and n ~= ignore then n:depends("ignore", "") end end return m
--[[ 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.tools.webadmin") require("luci.model.uci") require("luci.util") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.tools.webadmin.cbi_add_networks(iface) local uci = luci.model.uci.cursor() uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] s:depends("interface", section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) s:depends("interface", section[".name"]) end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true local dd = s:option(Flag, "dynamicdhcp") dd.rmempty = false function dd.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "1" end s:option(Value, "name", translate("name")).optional = true ignore = s:option(Flag, "ignore") ignore.optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true s:option(DynamicList, "dhcp_option").optional = true for i, n in ipairs(s.children) do if n ~= iface and n ~= ignore then n:depends("ignore", "") end end return m
Fix behaviour of dynamicdhcp field (thanks to Fabio Mercuri)
Fix behaviour of dynamicdhcp field (thanks to Fabio Mercuri)
Lua
apache-2.0
daofeng2015/luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,thess/OpenWrt-luci,joaofvieira/luci,obsy/luci,harveyhu2012/luci,Hostle/luci,LuttyYang/luci,rogerpueyo/luci,zhaoxx063/luci,fkooman/luci,florian-shellfire/luci,cshore/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,lcf258/openwrtcn,Noltari/luci,jchuang1977/luci-1,tcatm/luci,nmav/luci,opentechinstitute/luci,oneru/luci,keyidadi/luci,dismantl/luci-0.12,florian-shellfire/luci,obsy/luci,rogerpueyo/luci,jchuang1977/luci-1,nmav/luci,Noltari/luci,thess/OpenWrt-luci,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,fkooman/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,florian-shellfire/luci,joaofvieira/luci,Kyklas/luci-proto-hso,bittorf/luci,oyido/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,forward619/luci,NeoRaider/luci,rogerpueyo/luci,chris5560/openwrt-luci,rogerpueyo/luci,mumuqz/luci,daofeng2015/luci,slayerrensky/luci,ollie27/openwrt_luci,maxrio/luci981213,taiha/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,zhaoxx063/luci,dismantl/luci-0.12,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,Hostle/luci,sujeet14108/luci,thesabbir/luci,oneru/luci,jorgifumi/luci,kuoruan/luci,ff94315/luci-1,deepak78/new-luci,openwrt/luci,openwrt/luci,oneru/luci,fkooman/luci,keyidadi/luci,RuiChen1113/luci,jorgifumi/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,cshore/luci,dwmw2/luci,ollie27/openwrt_luci,joaofvieira/luci,deepak78/new-luci,dismantl/luci-0.12,Wedmer/luci,LuttyYang/luci,marcel-sch/luci,NeoRaider/luci,palmettos/test,openwrt/luci,harveyhu2012/luci,ff94315/luci-1,Hostle/luci,thesabbir/luci,nwf/openwrt-luci,remakeelectric/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,dismantl/luci-0.12,MinFu/luci,981213/luci-1,forward619/luci,slayerrensky/luci,tcatm/luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,hnyman/luci,joaofvieira/luci,nmav/luci,palmettos/test,fkooman/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,dwmw2/luci,wongsyrone/luci-1,remakeelectric/luci,tcatm/luci,opentechinstitute/luci,keyidadi/luci,forward619/luci,wongsyrone/luci-1,maxrio/luci981213,joaofvieira/luci,obsy/luci,openwrt/luci,wongsyrone/luci-1,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,florian-shellfire/luci,Kyklas/luci-proto-hso,harveyhu2012/luci,NeoRaider/luci,slayerrensky/luci,marcel-sch/luci,hnyman/luci,david-xiao/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,palmettos/cnLuCI,ff94315/luci-1,oyido/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,hnyman/luci,zhaoxx063/luci,kuoruan/luci,MinFu/luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,hnyman/luci,cshore/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,cappiewu/luci,ff94315/luci-1,nmav/luci,palmettos/test,Sakura-Winkey/LuCI,obsy/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,NeoRaider/luci,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,teslamint/luci,deepak78/new-luci,tcatm/luci,urueedi/luci,forward619/luci,shangjiyu/luci-with-extra,jorgifumi/luci,schidler/ionic-luci,urueedi/luci,dwmw2/luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,artynet/luci,cshore/luci,marcel-sch/luci,aa65535/luci,kuoruan/luci,kuoruan/luci,remakeelectric/luci,Wedmer/luci,palmettos/test,remakeelectric/luci,daofeng2015/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,forward619/luci,jlopenwrtluci/luci,jorgifumi/luci,Noltari/luci,ff94315/luci-1,Noltari/luci,Hostle/luci,Kyklas/luci-proto-hso,LuttyYang/luci,male-puppies/luci,artynet/luci,lbthomsen/openwrt-luci,urueedi/luci,kuoruan/lede-luci,zhaoxx063/luci,jorgifumi/luci,kuoruan/lede-luci,teslamint/luci,palmettos/test,teslamint/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,RuiChen1113/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,bittorf/luci,rogerpueyo/luci,david-xiao/luci,Sakura-Winkey/LuCI,joaofvieira/luci,urueedi/luci,oyido/luci,thesabbir/luci,dwmw2/luci,male-puppies/luci,openwrt/luci,florian-shellfire/luci,hnyman/luci,cappiewu/luci,thesabbir/luci,cappiewu/luci,aa65535/luci,schidler/ionic-luci,schidler/ionic-luci,shangjiyu/luci-with-extra,NeoRaider/luci,schidler/ionic-luci,981213/luci-1,cappiewu/luci,aa65535/luci,Hostle/luci,Noltari/luci,RedSnake64/openwrt-luci-packages,981213/luci-1,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,taiha/luci,schidler/ionic-luci,obsy/luci,jchuang1977/luci-1,thesabbir/luci,hnyman/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,deepak78/new-luci,bright-things/ionic-luci,bright-things/ionic-luci,male-puppies/luci,palmettos/cnLuCI,palmettos/cnLuCI,cshore/luci,mumuqz/luci,remakeelectric/luci,mumuqz/luci,sujeet14108/luci,forward619/luci,wongsyrone/luci-1,wongsyrone/luci-1,urueedi/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,david-xiao/luci,aa65535/luci,ollie27/openwrt_luci,981213/luci-1,jchuang1977/luci-1,taiha/luci,RuiChen1113/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,taiha/luci,wongsyrone/luci-1,oyido/luci,mumuqz/luci,Sakura-Winkey/LuCI,tobiaswaldvogel/luci,nmav/luci,mumuqz/luci,LuttyYang/luci,ff94315/luci-1,opentechinstitute/luci,fkooman/luci,rogerpueyo/luci,jorgifumi/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,deepak78/new-luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,lcf258/openwrtcn,marcel-sch/luci,nwf/openwrt-luci,thesabbir/luci,palmettos/test,teslamint/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,NeoRaider/luci,obsy/luci,palmettos/test,chris5560/openwrt-luci,deepak78/new-luci,remakeelectric/luci,zhaoxx063/luci,kuoruan/lede-luci,jorgifumi/luci,NeoRaider/luci,sujeet14108/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,981213/luci-1,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,cappiewu/luci,fkooman/luci,cshore-firmware/openwrt-luci,bittorf/luci,forward619/luci,david-xiao/luci,shangjiyu/luci-with-extra,oneru/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,jorgifumi/luci,Noltari/luci,bittorf/luci,harveyhu2012/luci,MinFu/luci,slayerrensky/luci,kuoruan/lede-luci,slayerrensky/luci,RuiChen1113/luci,palmettos/cnLuCI,cappiewu/luci,MinFu/luci,bittorf/luci,male-puppies/luci,Wedmer/luci,jchuang1977/luci-1,artynet/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,marcel-sch/luci,opentechinstitute/luci,remakeelectric/luci,oyido/luci,palmettos/cnLuCI,MinFu/luci,oyido/luci,dwmw2/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,Kyklas/luci-proto-hso,obsy/luci,remakeelectric/luci,ff94315/luci-1,opentechinstitute/luci,Wedmer/luci,male-puppies/luci,RuiChen1113/luci,tcatm/luci,LuttyYang/luci,kuoruan/luci,bright-things/ionic-luci,keyidadi/luci,daofeng2015/luci,tcatm/luci,daofeng2015/luci,nwf/openwrt-luci,oneru/luci,Noltari/luci,urueedi/luci,lcf258/openwrtcn,jchuang1977/luci-1,chris5560/openwrt-luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,male-puppies/luci,lcf258/openwrtcn,thess/OpenWrt-luci,bright-things/ionic-luci,openwrt/luci,chris5560/openwrt-luci,maxrio/luci981213,teslamint/luci,RuiChen1113/luci,urueedi/luci,Wedmer/luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,oyido/luci,artynet/luci,opentechinstitute/luci,nmav/luci,marcel-sch/luci,sujeet14108/luci,jchuang1977/luci-1,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,palmettos/test,lcf258/openwrtcn,david-xiao/luci,mumuqz/luci,jlopenwrtluci/luci,thesabbir/luci,lbthomsen/openwrt-luci,981213/luci-1,dwmw2/luci,mumuqz/luci,openwrt-es/openwrt-luci,dwmw2/luci,joaofvieira/luci,jlopenwrtluci/luci,bittorf/luci,aa65535/luci,deepak78/new-luci,artynet/luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,openwrt-es/openwrt-luci,oneru/luci,teslamint/luci,slayerrensky/luci,cshore/luci,cshore-firmware/openwrt-luci,Wedmer/luci,aa65535/luci,Hostle/luci,daofeng2015/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,keyidadi/luci,keyidadi/luci,shangjiyu/luci-with-extra,Noltari/luci,Hostle/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,hnyman/luci,schidler/ionic-luci,tobiaswaldvogel/luci,ff94315/luci-1,sujeet14108/luci,male-puppies/luci,forward619/luci,artynet/luci,harveyhu2012/luci,deepak78/new-luci,zhaoxx063/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,bittorf/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,oneru/luci,hnyman/luci,florian-shellfire/luci,obsy/luci,thess/OpenWrt-luci,marcel-sch/luci,david-xiao/luci,cappiewu/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,urueedi/luci,openwrt-es/openwrt-luci,981213/luci-1,palmettos/cnLuCI,male-puppies/luci,sujeet14108/luci,chris5560/openwrt-luci,Wedmer/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,Hostle/luci,joaofvieira/luci,openwrt/luci,nmav/luci,thess/OpenWrt-luci,kuoruan/luci,RuiChen1113/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,Wedmer/luci,bright-things/ionic-luci,jlopenwrtluci/luci,jlopenwrtluci/luci,artynet/luci,cappiewu/luci,maxrio/luci981213,daofeng2015/luci,maxrio/luci981213,schidler/ionic-luci,mumuqz/luci,nmav/luci,teslamint/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,taiha/luci,cshore/luci,daofeng2015/luci,NeoRaider/luci,wongsyrone/luci-1,slayerrensky/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,kuoruan/lede-luci,sujeet14108/luci,dismantl/luci-0.12,maxrio/luci981213,nmav/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,harveyhu2012/luci,thess/OpenWrt-luci,david-xiao/luci,cshore-firmware/openwrt-luci,MinFu/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,keyidadi/luci,bright-things/ionic-luci,artynet/luci,kuoruan/luci,marcel-sch/luci,nwf/openwrt-luci,opentechinstitute/luci,keyidadi/luci,tobiaswaldvogel/luci,teslamint/luci,florian-shellfire/luci,taiha/luci,maxrio/luci981213,Kyklas/luci-proto-hso,aa65535/luci,nwf/openwrt-luci,LuttyYang/luci,slayerrensky/luci
bdfc0a9c86b15e8b75239b43df541a91a1798e0d
mod_register_redirect/mod_register_redirect.lua
mod_register_redirect/mod_register_redirect.lua
-- (C) 2010-2011 Marco Cirillo (LW.Org) -- (C) 2011 Kim Alvefur -- -- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration. local st = require "util.stanza" local cman = configmanager function reg_redirect(event) local stanza, origin = event.stanza, event.origin local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" } local url = module:get_option_string("registration_url", nil) local inst_text = module:get_option_string("registration_text", nil) local oob = module:get_option_boolean("registration_oob", true) local admins_g = cman.get("*", "core", "admins") local admins_l = cman.get(module:get_host(), "core", "admins") local no_wl = module:get_option_boolean("no_registration_whitelist", false) local test_ip = false if type(admins_g) ~= "table" then admins_g = nil end if type(admins_l) ~= "table" then admins_l = nil end -- perform checks to set default responses and sanity checks. if not inst_text then if url and oob then if url:match("^%w+[:].*$") then if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then inst_text = "Please visit "..url.." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "mailto" then inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "xmpp" then inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$") else module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.") module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,") module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end else module:log("error", "Please check your configuration, the URL you specified is invalid") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end else if admins_l then local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else if admins_g then local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...") module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end end end elseif inst_text and url and oob then if not url:match("^%w+[:].*$") then module:log("error", "Please check your configuration, the URL specified is not valid.") origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request. end end if not no_wl then for i,ip in ipairs(ip_wl) do if origin.ip == ip then test_ip = true end break end end -- Prepare replies. local reply = st.reply(event.stanza) if oob then reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() :tag("x", {xmlns = "jabber:x:oob"}) :tag("url"):text(url); else reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() end if stanza.attr.type == "get" then origin.send(reply) else origin.send(st.error_reply(stanza, "cancel", "not-authorized")) end return true end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
-- (C) 2010-2011 Marco Cirillo (LW.Org) -- (C) 2011 Kim Alvefur -- -- Registration Redirect module for Prosody -- -- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration. local st = require "util.stanza" local cman = configmanager function reg_redirect(event) local stanza, origin = event.stanza, event.origin local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" } local url = module:get_option_string("registration_url", nil) local inst_text = module:get_option_string("registration_text", nil) local oob = module:get_option_boolean("registration_oob", true) local admins_g = cman.get("*", "core", "admins") local admins_l = cman.get(module:get_host(), "core", "admins") local no_wl = module:get_option_boolean("no_registration_whitelist", false) local test_ip = false if type(admins_g) ~= "table" then admins_g = nil end if type(admins_l) ~= "table" then admins_l = nil end -- perform checks to set default responses and sanity checks. if not inst_text then if url and oob then if url:match("^%w+[:].*$") then if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then inst_text = "Please visit "..url.." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "mailto" then inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server." elseif url:match("^(%w+)[:].*$") == "xmpp" then inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$") else module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.") module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,") module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end else module:log("error", "Please check your configuration, the URL you specified is invalid") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end else if admins_l then local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else if admins_g then local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid else module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...") module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end end end elseif inst_text and url and oob then if not url:match("^%w+[:].*$") then module:log("error", "Please check your configuration, the URL specified is not valid.") return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request. end end if not no_wl then for i,ip in ipairs(ip_wl) do if origin.ip == ip then test_ip = true end break end end -- Prepare replies. local reply = st.reply(event.stanza) if oob then reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() :tag("x", {xmlns = "jabber:x:oob"}) :tag("url"):text(url); else reply:query("jabber:iq:register") :tag("instructions"):text(inst_text):up() end if stanza.attr.type == "get" then return origin.send(reply) else return origin.send(st.error_reply(stanza, "cancel", "not-authorized")) end end module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
Lua
mit
prosody-modules/import,heysion/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,Craige/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,apung/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,obelisk21/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,prosody-modules/import,jkprg/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,apung/prosody-modules,olax/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,prosody-modules/import,dhotson/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules
d11100412bd2a2f240e41d44aa26d822dae6212f
premake5.lua
premake5.lua
local build_dir = "build/" .. _ACTION -------------------------------------------------------------------------------- solution "Libs" configurations { "Release", "Debug" } architecture "x64" location (build_dir) objdir (build_dir .. "/obj") warnings "Extra" configuration { "Debug" } targetdir (build_dir .. "/bin/Debug") configuration { "Release" } targetdir (build_dir .. "/bin/Release") configuration { "Debug" } defines { "_DEBUG" } symbols "On" configuration { "Release" } defines { "NDEBUG" } symbols "Off" optimize "Full" -- On ==> -O2 -- Full ==> -O3 configuration { "gmake" } buildoptions { "-march=native", "-std=c++14", "-Wformat", -- "-Wsign-compare", -- "-Wsign-conversion", -- "-pedantic", -- "-fvisibility=hidden", "-fno-exceptions", -- "-fno-rtti", -- "-fno-omit-frame-pointer", -- "-ftime-report", } configuration { "gmake", "Debug", "not Windows" } buildoptions { "-fno-omit-frame-pointer", "-fsanitize=undefined", "-fsanitize=address", -- "-fsanitize=memory", -- "-fsanitize-memory-track-origins", } linkoptions { "-fsanitize=undefined", "-fsanitize=address", -- "-fsanitize=memory", } configuration { "vs*" } buildoptions { "/std:c++latest", -- "/arch:AVX2", -- "/GR-", } -- defines { -- "_CRT_SECURE_NO_WARNINGS=1", -- "_SCL_SECURE_NO_WARNINGS=1", -- } configuration { "windows" } characterset "Unicode" -------------------------------------------------------------------------------- group "Libs" project "fmtxx" language "C++" kind "SharedLib" files { "src/double-conversion/**.h", "src/double-conversion/**.cc", "src/Dtoa.h", "src/Dtoa.cc", "src/Format.h", "src/Format.cc", } defines { "FMTXX_SHARED", "FMTXX_EXPORT", } includedirs { "src/", } links { "double-conversion", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-Wold-style-cast", "-pedantic", "-fvisibility=hidden", } project "fmtxx-static" language "C++" kind "StaticLib" files { "src/double-conversion/**.h", "src/double-conversion/**.cc", "src/Dtoa.h", "src/Dtoa.cc", "src/Format.h", "src/Format.cc", } includedirs { "src/", } links { "double-conversion", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-Wold-style-cast", "-pedantic", "-fvisibility=hidden", } project "fmt" language "C++" kind "SharedLib" files { "test/ext/fmt/fmt/*.cc", "test/ext/fmt/fmt/*.h", } defines { "FMT_SHARED", "FMT_EXPORT", } includedirs { "test/ext/fmt/", } project "fmt-static" language "C++" kind "StaticLib" files { "test/ext/fmt/fmt/*.cc", "test/ext/fmt/fmt/*.h", } includedirs { "test/ext/fmt/", } -------------------------------------------------------------------------------- group "Tests" project "Test" language "C++" kind "ConsoleApp" files { "test/Test.cc", } defines { "FMTXX_SHARED", } includedirs { "src/", } links { "fmtxx", } project "TestBignum" language "C++" kind "ConsoleApp" files { "test/TestBignum.cc", } links { "fmtxx-static", } project "TestPerf" language "C++" kind "ConsoleApp" files { "test/TestPerf.cc", } defines { "FMTXX_SHARED", "FMT_SHARED" } includedirs { "src/", "test/ext/", "test/ext/fmt/", } links { "fmtxx", "fmt", }
local build_dir = "build/" .. _ACTION -------------------------------------------------------------------------------- solution "Libs" configurations { "Release", "Debug" } architecture "x64" location (build_dir) objdir (build_dir .. "/obj") warnings "Extra" configuration { "Debug" } targetdir (build_dir .. "/bin/Debug") configuration { "Release" } targetdir (build_dir .. "/bin/Release") configuration { "Debug" } defines { "_DEBUG" } symbols "On" configuration { "Release" } defines { "NDEBUG" } symbols "Off" optimize "Full" -- On ==> -O2 -- Full ==> -O3 configuration { "gmake" } buildoptions { "-march=native", "-std=c++14", "-Wformat", -- "-Wsign-compare", -- "-Wsign-conversion", -- "-pedantic", -- "-fvisibility=hidden", "-fno-exceptions", -- "-fno-rtti", -- "-fno-omit-frame-pointer", -- "-ftime-report", } configuration { "gmake", "Debug", "not Windows" } buildoptions { "-fno-omit-frame-pointer", "-fsanitize=undefined", "-fsanitize=address", -- "-fsanitize=memory", -- "-fsanitize-memory-track-origins", } linkoptions { "-fsanitize=undefined", "-fsanitize=address", -- "-fsanitize=memory", } configuration { "vs*" } buildoptions { "/std:c++latest", -- "/arch:AVX2", -- "/GR-", } -- defines { -- "_CRT_SECURE_NO_WARNINGS=1", -- "_SCL_SECURE_NO_WARNINGS=1", -- } configuration { "windows" } characterset "Unicode" -------------------------------------------------------------------------------- group "Libs" project "fmtxx" language "C++" kind "SharedLib" files { "src/double-conversion/**.h", "src/double-conversion/**.cc", "src/Dtoa.h", "src/Dtoa.cc", "src/Format.h", "src/Format.cc", } defines { "FMTXX_SHARED", "FMTXX_EXPORT", } includedirs { "src/", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-Wold-style-cast", "-pedantic", "-fvisibility=hidden", } project "fmtxx-static" language "C++" kind "StaticLib" files { "src/double-conversion/**.h", "src/double-conversion/**.cc", "src/Dtoa.h", "src/Dtoa.cc", "src/Format.h", "src/Format.cc", } includedirs { "src/", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-Wold-style-cast", "-pedantic", "-fvisibility=hidden", } project "fmt" language "C++" kind "SharedLib" files { "test/ext/fmt/fmt/*.cc", "test/ext/fmt/fmt/*.h", } defines { "FMT_SHARED", "FMT_EXPORT", } includedirs { "test/ext/fmt/", } project "fmt-static" language "C++" kind "StaticLib" files { "test/ext/fmt/fmt/*.cc", "test/ext/fmt/fmt/*.h", } includedirs { "test/ext/fmt/", } -------------------------------------------------------------------------------- group "Tests" project "Test" language "C++" kind "ConsoleApp" files { "test/Test.cc", } defines { "FMTXX_SHARED", } includedirs { "src/", } links { "fmtxx", } project "TestBignum" language "C++" kind "ConsoleApp" files { "test/TestBignum.cc", } links { "fmtxx-static", } project "TestPerf" language "C++" kind "ConsoleApp" files { "test/TestPerf.cc", } defines { "FMTXX_SHARED", "FMT_SHARED" } includedirs { "src/", "test/ext/", "test/ext/fmt/", } links { "fmtxx", "fmt", }
Fix build script
Fix build script
Lua
mit
abolz/Format
7c09d4c3a9d6bbf9fbfad5a0a8d23c9252af08e8
src/Ship.lua
src/Ship.lua
require ("lib.lclass") class "Ship" function Ship:Ship () self.gfx = { ship = love.graphics.newImage ("gfx/schiff.png"), jetflame = love.graphics.newImage ("gfx/flamme.png") } self.r = 255 self.g = 255 self.b = 255 self.x = 200 self.y = 200 self.rot = { w = self.gfx.ship:getWidth () / 2, h = self.gfx.ship:getHeight () / 2, v = 0 } self.scale = 1 self.jetflame = { x = 0, y = 0 } self.rotationSpeed = 10 self.accelerationSpeed = 32 self.MAX_ACCELERATION = 32 self.acceleration = 0 self.MAX_ROTATION = 2 * math.pi self.rotation = 0 self.momentum = setmetatable ({x = 0, y = 0}, { __tostring = function (self) return "{" .. self.x .. "," .. self.y .. "}" end }) self.isAccelerating = 0 self.isRotating = 0 self.reactions = { KeyboardKeyDownEvent = function (event) local switch = { w = function () self.isAccelerating = self.isAccelerating + 1 end, s = function () self.isAccelerating = self.isAccelerating - 1 end, a = function () self.isRotating = self.isRotating - 1 end, d = function () self.isRotating = self.isRotating + 1 end } local case = switch[event:Key ()] if case then case () end end, KeyboardKeyUpEvent = function (event) local switch = { w = function () self.isAccelerating = self.isAccelerating - 1 end, s = function () self.isAccelerating = self.isAccelerating + 1 end, a = function () self.isRotating = self.isRotating + 1 end, d = function () self.isRotating = self.isRotating - 1 end } local case = switch[event:Key ()] if case then case () end end } end function Ship:onUpdate (dt) self.rot.v = self.rot.v + (self.isRotating * self.rotationSpeed * dt) self.rot.v = self.rot.v % self.MAX_ROTATION self.momentum.x = self.momentum.x + (math.sin (self.rot.v) * self.isAccelerating * self.accelerationSpeed) self.momentum.y = self.momentum.y + (-math.cos (self.rot.v) * self.isAccelerating * self.accelerationSpeed) self.x = self.x + (self.momentum.x * dt) self.y = self.y + (self.momentum.y * dt) if self.x > love.graphics.getWidth() then self.x = 0 end if self.y > love.graphics.getHeight() then self.y = 0 end if self.x < 0 then self.x = love.graphics.getWidth() end if self.y < 0 then self.y = love.graphics.getHeight() end end function Ship:onRender () love.graphics.setColor (self.r, self.g, self.b, 255) love.graphics.push () local rotx = self.x + self.rot.w local roty = self.y + self.rot.h -- rotate around the center of the ship (position) love.graphics.translate (rotx, roty) love.graphics.rotate (self.rot.v) love.graphics.translate (-rotx, -roty) love.graphics.draw ( self.gfx.ship, self.x, self.y ) if not (self.isAccelerating == 0) then love.graphics.draw ( self.gfx.jetflame, self.x, self.y + self.rot.h * 2 ) end love.graphics.pop() love.graphics.setColor (255, 255, 255, 255) local py = 42 local pyoff = 16 love.graphics.print ("rot.v: " .. self.rot.v, 42, py + 0 * pyoff) love.graphics.print ("acc: " .. self.acceleration, 42, py + 1 * pyoff) love.graphics.print ("mom: " .. tostring (self.momentum), 42, py + 2 * pyoff) end function Ship:handle (event) local reaction = self.reactions[event:getClass()] if reaction then reaction (event) end end
require ("lib.lclass") class "Ship" function Ship:Ship () self.gfx = { ship = love.graphics.newImage ("gfx/schiff.png"), jetflame = love.graphics.newImage ("gfx/flamme.png") } self.r = 255 self.g = 255 self.b = 255 self.x = 200 self.y = 200 self.rot = { w = self.gfx.ship:getWidth () / 2, h = self.gfx.ship:getHeight () / 2, v = 0 } self.scale = 1 self.jetflame = { x = 0, y = 0 } self.rotationSpeed = 10 self.accelerationSpeed = 32 self.MAX_ACCELERATION = 32 self.acceleration = 0 self.MAX_ROTATION = 2 * math.pi self.rotation = 0 self.momentum = setmetatable ({x = 0, y = 0}, { __tostring = function (self) return "{" .. self.x .. "," .. self.y .. "}" end }) self.isAccelerating = 0 self.isRotating = 0 self.reactions = { KeyboardKeyDownEvent = function (event) local switch = { w = function () self.isAccelerating = self.isAccelerating + 1 end, a = function () self.isRotating = self.isRotating - 1 end, d = function () self.isRotating = self.isRotating + 1 end } local case = switch[event:Key ()] if case then case () end end, KeyboardKeyUpEvent = function (event) local switch = { w = function () self.isAccelerating = self.isAccelerating - 1 end, a = function () self.isRotating = self.isRotating + 1 end, d = function () self.isRotating = self.isRotating - 1 end } local case = switch[event:Key ()] if case then case () end end } end function Ship:onUpdate (dt) self.rot.v = self.rot.v + (self.isRotating * self.rotationSpeed * dt) self.rot.v = self.rot.v % self.MAX_ROTATION self.momentum.x = self.momentum.x + (math.sin (self.rot.v) * self.isAccelerating * self.accelerationSpeed) self.momentum.y = self.momentum.y + (-math.cos (self.rot.v) * self.isAccelerating * self.accelerationSpeed) self.x = self.x + (self.momentum.x * dt) self.y = self.y + (self.momentum.y * dt) if self.x > love.graphics.getWidth() then self.x = 0 end if self.y > love.graphics.getHeight() then self.y = 0 end if self.x < 0 then self.x = love.graphics.getWidth() end if self.y < 0 then self.y = love.graphics.getHeight() end end function Ship:onRender () love.graphics.setColor (self.r, self.g, self.b, 255) love.graphics.push () local rotx = self.x + self.rot.w local roty = self.y + self.rot.h -- rotate around the center of the ship (position) love.graphics.translate (rotx, roty) love.graphics.rotate (self.rot.v) love.graphics.translate (-rotx, -roty) love.graphics.draw ( self.gfx.ship, self.x, self.y ) if not (self.isAccelerating == 0) then love.graphics.draw ( self.gfx.jetflame, self.x, self.y + self.rot.h * 2 ) end love.graphics.pop() love.graphics.setColor (255, 255, 255, 255) local py = 42 local pyoff = 16 love.graphics.print ("rot.v: " .. self.rot.v, 42, py + 0 * pyoff) love.graphics.print ("acc: " .. self.acceleration, 42, py + 1 * pyoff) love.graphics.print ("mom: " .. tostring (self.momentum), 42, py + 2 * pyoff) end function Ship:handle (event) local reaction = self.reactions[event:getClass()] if reaction then reaction (event) end end
removed backwards acceleration, fixes #5
removed backwards acceleration, fixes #5
Lua
mit
BlurryRoots/weltraumsteinekaputtmachen
a0dd19311a129fc265fe28375462ec915a4214ad
OS/CartOS/Programs/cd.lua
OS/CartOS/Programs/cd.lua
--Enter a specifiec directory/path/drive local args = {...} --Get the arguments passed to this program if #args < 1 then color(9) print("\nMust provide the path") return end local tar = table.concat(args," ") --The path may include whitespaces local term = require("C://terminal") print("") --A new line local d, p = tar:match("(.+)://(.+)") if d then term.setpath(tar) return end local d = tar:match("(.+):") --ex: cd D: if d then term.setpath(d..":///") return end local d = tar:match("/(.+)") if d then term.setdirectory(tar) return end if tar == ".." then local fld = {} --A list of folders in the path for p in string.gmatch(term.getdirectory(),"/(.+)/") do table.insert(fld,p) end if #fld == 0 then return end table.remove(fld, #fld) term.setdirectory("/"..table.concat(fld,"/")) return end term.setdirectory(term.getdirectory()..tar)
--Enter a specifiec directory/path/drive local args = {...} --Get the arguments passed to this program if #args < 1 then color(9) print("\nMust provide the path") return end local tar = table.concat(args," ") --The path may include whitespaces local term = require("C://terminal") print("") --A new line local function tcall(func,...) local ok, err = pcall(func,...) if not ok then color(9) print(tostring(err)) return false end return true end local d, p = tar:match("(.+)://(.+)") if d then tcall(term.setpath,tar) return end local d = tar:match("(.+):") --ex: cd D: if d then tcall(term.setpath,d..":///") return end local d = tar:match("/(.+)") if d then tcall(term.setdirectory,tar) return end if tar == ".." then local fld = {} --A list of folders in the path for p in string.gmatch(term.getdirectory(),"(.-)/") do table.insert(fld,p) end if #fld == 0 then return end table.remove(fld, #fld) tcall(term.setdirectory,"/"..table.concat(fld,"/")) return end tcall(term.setdirectory,term.getdirectory()..tar)
Bugfixes
Bugfixes
Lua
mit
RamiLego4Game/LIKO-12
4fce8fd70188bc3a221e182d11794743a75a60a9
Modules/Gui/RoundedBacking/RoundedBackingBuilder.lua
Modules/Gui/RoundedBacking/RoundedBackingBuilder.lua
--- Construct a rounded backing with a shadow -- @classmod RoundedBackingBuilder local RoundedBackingBuilder = {} RoundedBackingBuilder.__index = RoundedBackingBuilder RoundedBackingBuilder.ClassName = "RoundedBackingBuilder" function RoundedBackingBuilder.new() local self = setmetatable({}, RoundedBackingBuilder) return self end function RoundedBackingBuilder:CreateBacking(gui) local backing = Instance.new("ImageLabel") backing.Name = "Backing" backing.Size = UDim2.new(1, 0, 1, 0) backing.Image = "rbxassetid://735637144" backing.SliceCenter = Rect.new(4, 4, 16, 16) backing.ImageColor3 = gui.BackgroundColor3 backing.ScaleType = Enum.ScaleType.Slice backing.BackgroundTransparency = 1 backing.ZIndex = math.max(2, gui.ZIndex - 1) backing.Parent = gui gui.BackgroundTransparency = 1 return backing end --- Only top two corners are rounded function RoundedBackingBuilder:CreateTopBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(20, 16) backing.SliceCenter = Rect.new(4, 4, 16, 16) return backing end function RoundedBackingBuilder:CreateLeftBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(16, 20) backing.SliceCenter = Rect.new(4, 4, 16, 16) return backing end function RoundedBackingBuilder:CreateRightBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(16, 20) backing.SliceCenter = Rect.new(4, 4, 16, 16) backing.ImageRectOffset = Vector2.new(4, 0) return backing end --- Only bottom two corners are rounded function RoundedBackingBuilder:CreateBottomBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectOffset = Vector2.new(0, 4) backing.ImageRectSize = Vector2.new(20, 16) backing.SliceCenter = Rect.new(4, 4, 16, 16) return backing end function RoundedBackingBuilder:CreateShadow(backing) local shadow = Instance.new("ImageLabel") shadow.Name = "Shadow" shadow.Size = UDim2.new(1, 6, 1, 6) shadow.AnchorPoint = Vector2.new(0.5, 0.5) shadow.Position = UDim2.new(0.5, 0, 0.5, 1) shadow.Image = "rbxassetid://735644155" shadow.SliceCenter = Rect.new(16, 16, 64, 64) shadow.ImageColor3 = Color3.new(0, 0, 0) shadow.ScaleType = Enum.ScaleType.Slice shadow.BackgroundTransparency = 1 shadow.ImageTransparency = 0.7 shadow.ZIndex = backing.ZIndex - 1 shadow.Parent = backing.Parent return shadow end function RoundedBackingBuilder:Create(gui) local backing = self:CreateBacking(gui) self:CreateShadow(backing) return backing end return RoundedBackingBuilder
--- Construct a rounded backing with a shadow -- @classmod RoundedBackingBuilder local RoundedBackingBuilder = {} RoundedBackingBuilder.__index = RoundedBackingBuilder RoundedBackingBuilder.ClassName = "RoundedBackingBuilder" function RoundedBackingBuilder.new() local self = setmetatable({}, RoundedBackingBuilder) return self end function RoundedBackingBuilder:Create(gui) local backing = self:CreateBacking(gui) self:CreateShadow(backing) return backing end function RoundedBackingBuilder:CreateBacking(gui) local backing = Instance.new("ImageLabel") backing.Name = "Backing" backing.Size = UDim2.new(1, 0, 1, 0) backing.Image = "rbxassetid://735637144" backing.SliceCenter = Rect.new(4, 4, 16, 16) backing.ImageColor3 = gui.BackgroundColor3 backing.ScaleType = Enum.ScaleType.Slice backing.BackgroundTransparency = 1 backing.ZIndex = math.max(2, gui.ZIndex - 1) backing.Parent = gui gui.BackgroundTransparency = 1 return backing end --- Only top two corners are rounded function RoundedBackingBuilder:CreateTopBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(20, 16) backing.SliceCenter = Rect.new(4, 4, 16, 16) return backing end function RoundedBackingBuilder:CreateLeftBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(16, 20) backing.SliceCenter = Rect.new(4, 4, 16, 16) return backing end function RoundedBackingBuilder:CreateRightBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(16, 20) backing.SliceCenter = Rect.new(4, 4, 16, 16) backing.ImageRectOffset = Vector2.new(4, 0) return backing end --- Only bottom two corners are rounded function RoundedBackingBuilder:CreateBottomBacking(gui) local backing = self:CreateBacking(gui) backing.ImageRectSize = Vector2.new(20, 16) backing.ImageRectOffset = Vector2.new(0, 4) backing.SliceCenter = Rect.new(4, 4, 12, 12) return backing end function RoundedBackingBuilder:CreateShadow(backing) local shadow = Instance.new("ImageLabel") shadow.Name = "Shadow" shadow.Size = UDim2.new(1, 6, 1, 6) shadow.AnchorPoint = Vector2.new(0.5, 0.5) shadow.Position = UDim2.new(0.5, 0, 0.5, 1) shadow.Image = "rbxassetid://735644155" shadow.SliceCenter = Rect.new(16, 16, 64, 64) shadow.ImageColor3 = Color3.new(0, 0, 0) shadow.ScaleType = Enum.ScaleType.Slice shadow.BackgroundTransparency = 1 shadow.ImageTransparency = 0.7 shadow.ZIndex = backing.ZIndex - 1 shadow.Parent = backing.Parent return shadow end return RoundedBackingBuilder
Fix CreateBottomBacking and move :Create() API to the top
Fix CreateBottomBacking and move :Create() API to the top
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
5c79dcfb71cfbab79ed4f51b3e7a8dc3ea5eef30
config/nvim/lua/finder.lua
config/nvim/lua/finder.lua
local utils = require "nutils" keymap = utils.map local actions = require("telescope.actions") require("telescope").load_extension("fzy_native") require("telescope").load_extension("fzf_writer") require("telescope").setup { defaults = { vimgrep_arguments = {"rg", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case"}, prompt_prefix = " ", selection_caret = " ", entry_prefix = " ", scroll_strategy = "cycle", prompt_position = "top", initial_mode = "insert", selection_strategy = "reset", sorting_strategy = "ascending", layout_strategy = "horizontal", file_ignore_patterns = {}, shorten_path = true, winblend = 0, width = 0.75, preview_cutoff = 120, results_height = 1, results_width = 0.8, border = {}, borderchars = {"─", "│", "─", "│", "╭", "╮", "╯", "╰"}, color_devicons = true, use_less = true, set_env = {["COLORTERM"] = "truecolor"}, -- default = nil, file_sorter = require("telescope.sorters").get_fzy_sorter, file_previewer = require "telescope.previewers".vim_buffer_cat.new, grep_previewer = require "telescope.previewers".vim_buffer_vimgrep.new, qflist_previewer = require "telescope.previewers".vim_buffer_qflist.new, color_devicons = true, mappings = { i = { ["<C-x>"] = false, ["<C-q>"] = actions.send_to_qflist, ["<esc>"] = actions.close, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous } } }, extensions = { fzy_native = { override_generic_sorter = false, override_file_sorter = true }, fzf_writer = { minimum_grep_characters = 2, use_highlighter = true } } } keymap("n", "<leader>a", ":Telescope fzf_writer staged_grep<CR>") keymap("n", "<leader>p", ":Telescope fzf_writer files<Cr>") keymap("n", "<leader>b", ":Telescope buffers<Cr>") keymap("n", "<leader>ca", ":Telescope lsp_code_actions<CR>") keymap("v", "<leader>ca", ":Telescope lsp_range_code_actions<CR>") -- Create a new vsplit, switch to it and open CtrlP keymap("n", "<leader>w", "<C-w>v<C-w>l :Telescope find_files<cr>") -- Create a new split, switch to it and open CtrlP keymap("n", "<leader>s", "<C-w>s<C-w>j :Telescope find_files<cr>") keymap("n", "<F3>", ":Telescope lsp_references<CR>")
local utils = require "nutils" keymap = utils.map local actions = require("telescope.actions") require("telescope").load_extension("fzy_native") require("telescope").setup { defaults = { vimgrep_arguments = {"rg", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case"}, prompt_prefix = " ", selection_caret = " ", entry_prefix = " ", scroll_strategy = "cycle", prompt_position = "top", initial_mode = "insert", selection_strategy = "reset", sorting_strategy = "ascending", layout_strategy = "horizontal", file_ignore_patterns = {}, shorten_path = true, winblend = 0, width = 0.75, preview_cutoff = 120, results_height = 1, results_width = 0.8, border = {}, borderchars = {"─", "│", "─", "│", "╭", "╮", "╯", "╰"}, color_devicons = true, use_less = true, set_env = {["COLORTERM"] = "truecolor"}, -- default = nil, file_sorter = require("telescope.sorters").fuzzy_with_index_bias, file_previewer = require "telescope.previewers".vim_buffer_cat.new, grep_previewer = require "telescope.previewers".vim_buffer_vimgrep.new, qflist_previewer = require "telescope.previewers".vim_buffer_qflist.new, color_devicons = true, mappings = { i = { ["<C-x>"] = false, ["<C-q>"] = actions.send_to_qflist, ["<esc>"] = actions.close, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous } } }, extensions = { fzy_native = { override_generic_sorter = false, override_file_sorter = true }, fzf_writer = { minimum_grep_characters = 2, use_highlighter = true } } } keymap("n", "<leader>a", ":Telescope fzf_writer staged_grep<CR>") keymap("n", "<leader>p", ":Telescope fzf_writer files<Cr>") keymap("n", "<leader>b", ":Telescope buffers<Cr>") keymap("n", "<leader>ca", ":Telescope lsp_code_actions<CR>") keymap("v", "<leader>ca", ":Telescope lsp_range_code_actions<CR>") -- Create a new vsplit, switch to it and open CtrlP keymap("n", "<leader>w", "<C-w>v<C-w>l :Telescope find_files<cr>") -- Create a new split, switch to it and open CtrlP keymap("n", "<leader>s", "<C-w>s<C-w>j :Telescope find_files<cr>") keymap("n", "<F3>", ":Telescope lsp_references<CR>")
Fix telescope
Fix telescope
Lua
mit
gblock0/dotfiles
1ff2486d05013f65bd98e1f85bb6f64c0bf951d2
util/async.lua
util/async.lua
local log = require "util.logger".init("util.async"); local function runner_continue(thread) -- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure) if coroutine.status(thread) ~= "suspended" then -- This should suffice return false; end local ok, state, runner = coroutine.resume(thread); if not ok then local level = 0; while debug.getinfo(thread, level, "") do level = level + 1; end ok, runner = debug.getlocal(thread, level-1, 1); local error_handler = runner.watchers.error; if error_handler then error_handler(runner, debug.traceback(thread, state)); end elseif state == "ready" then -- If state is 'ready', it is our responsibility to update runner.state from 'waiting'. -- We also have to :run(), because the queue might have further items that will not be -- processed otherwise. FIXME: It's probably best to do this in a nexttick (0 timer). runner.state = "ready"; runner:run(); end return true; end local function waiter(num) local thread = coroutine.running(); if not thread then error("Not running in an async context, see http://prosody.im/doc/developers/async"); end num = num or 1; local waiting; return function () if num == 0 then return; end -- already done waiting = true; coroutine.yield("wait"); end, function () num = num - 1; if num == 0 and waiting then runner_continue(thread); elseif num < 0 then error("done() called too many times"); end end; end local runner_mt = {}; runner_mt.__index = runner_mt; local function runner_create_thread(func, self) local thread = coroutine.create(function (self) while true do func(coroutine.yield("ready", self)); end end); assert(coroutine.resume(thread, self)); -- Start it up, it will return instantly to wait for the first input return thread; end local empty_watchers = {}; local function runner(func, watchers, data) return setmetatable({ func = func, thread = false, state = "ready", notified_state = "ready", queue = {}, watchers = watchers or empty_watchers, data = data } , runner_mt); end function runner_mt:run(input) if input ~= nil then table.insert(self.queue, input); end if self.state ~= "ready" then return true, self.state, #self.queue; end local q, thread = self.queue, self.thread; if not thread or coroutine.status(thread) == "dead" then thread = runner_create_thread(self.func, self); self.thread = thread; end local n, state, err = #q, self.state, nil; self.state = "running"; while n > 0 and state == "ready" do local consumed; for i = 1,n do local input = q[i]; local ok, new_state = coroutine.resume(thread, input); if not ok then consumed, state, err = i, "ready", debug.traceback(thread, new_state); self.thread = nil; break; elseif new_state == "wait" then consumed, state = i, "waiting"; break; end end if not consumed then consumed = n; end if q[n+1] ~= nil then n = #q; end for i = 1, n do q[i] = q[consumed+i]; end n = #q; end self.state = state; if state ~= self.notified_state then self.notified_state = state; local handler = self.watchers[state]; if handler then handler(self, err); end end return true, state, n; end function runner_mt:enqueue(input) table.insert(self.queue, input); end return { waiter = waiter, runner = runner };
local log = require "util.logger".init("util.async"); local function runner_continue(thread) -- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure) if coroutine.status(thread) ~= "suspended" then -- This should suffice return false; end local ok, state, runner = coroutine.resume(thread); if not ok then local level = 0; while debug.getinfo(thread, level, "") do level = level + 1; end ok, runner = debug.getlocal(thread, level-1, 1); local error_handler = runner.watchers.error; if error_handler then error_handler(runner, debug.traceback(thread, state)); end elseif state == "ready" then -- If state is 'ready', it is our responsibility to update runner.state from 'waiting'. -- We also have to :run(), because the queue might have further items that will not be -- processed otherwise. FIXME: It's probably best to do this in a nexttick (0 timer). runner.state = "ready"; runner:run(); end return true; end local function waiter(num) local thread = coroutine.running(); if not thread then error("Not running in an async context, see http://prosody.im/doc/developers/async"); end num = num or 1; local waiting; return function () if num == 0 then return; end -- already done waiting = true; coroutine.yield("wait"); end, function () num = num - 1; if num == 0 and waiting then runner_continue(thread); elseif num < 0 then error("done() called too many times"); end end; end local runner_mt = {}; runner_mt.__index = runner_mt; local function runner_create_thread(func, self) local thread = coroutine.create(function (self) while true do func(coroutine.yield("ready", self)); end end); assert(coroutine.resume(thread, self)); -- Start it up, it will return instantly to wait for the first input return thread; end local empty_watchers = {}; local function runner(func, watchers, data) return setmetatable({ func = func, thread = false, state = "ready", notified_state = "ready", queue = {}, watchers = watchers or empty_watchers, data = data } , runner_mt); end function runner_mt:run(input) if input ~= nil then table.insert(self.queue, input); end if self.state ~= "ready" then return true, self.state, #self.queue; end local q, thread = self.queue, self.thread; if not thread or coroutine.status(thread) == "dead" then thread = runner_create_thread(self.func, self); self.thread = thread; end local n, state, err = #q, self.state, nil; self.state = "running"; while n > 0 and state == "ready" do local consumed; for i = 1,n do local input = q[i]; local ok, new_state = coroutine.resume(thread, input); if not ok then consumed, state, err = i, "ready", debug.traceback(thread, new_state); self.thread = nil; break; elseif new_state == "wait" then consumed, state = i, "waiting"; break; end end if not consumed then consumed = n; end if q[n+1] ~= nil then n = #q; end for i = 1, n do q[i] = q[consumed+i]; end n = #q; end self.state = state; if err or state ~= self.notified_state then if err then state = "error" else self.notified_state = state; end local handler = self.watchers[state]; if handler then handler(self, err); end end return true, state, n; end function runner_mt:enqueue(input) table.insert(self.queue, input); end return { waiter = waiter, runner = runner };
util.async: Fix logic bug that prevented error watcher being called for runners
util.async: Fix logic bug that prevented error watcher being called for runners
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
26546845f4c755d934c19c2c256b5efb90917700
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local lineEmitter = LineEmitter:new() local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id -- Print the payload. The p() is intentional, Ryan :D log("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local lineEmitter = LineEmitter:new() local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: tests: fixtures: server re-add print
monitoring: tests: fixtures: server re-add print re-add the print that Ryan removed accidently with a comment.
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
b0711b318af2fd5e819889424140d0f32788e08d
nyagos.d/suffix.lua
nyagos.d/suffix.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local newext="."..suffix local orgpathext = nyagos.env.PATHEXT if orgpathext then if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.env.PATHEXT = orgpathext..";"..newext end else nyagos.env.PATHEXT = newext end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local m = string.match(args[0],"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local path=nyagos.which(args[0]) if not path then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} share._setsuffix = function(suffix,cmdline) suffix=string.gsub(string.lower(suffix),"^%.","") if not share._suffixes[suffix] then local newext="."..suffix local orgpathext = nyagos.env.PATHEXT if orgpathext then if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.env.PATHEXT = orgpathext..";"..newext end else nyagos.env.PATHEXT = newext end end share._suffixes[suffix]=cmdline end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local m = string.match(args[0],"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local path=nyagos.which(args[0]) if not path then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end
nyagos.d/suffix.lua: optimize
nyagos.d/suffix.lua: optimize
Lua
bsd-3-clause
zetamatta/nyagos,tsuyoshicho/nyagos
612971e628f6aad5b71662a820cfb065944273c1
site/email.lua
site/email.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. ]]-- -- This is email.lua - a script for fetching a document (email) local JSON = require 'cjson' local elastic = require 'lib/elastic' local aaa = require 'lib/aaa' local user = require 'lib/user' function handle(r) r.content_type = "application/json" local get = r:parseargs() local eid = (get.id or ""):gsub("\"", "") local doc = elastic.get("mbox", eid or "hmm") -- Try searching by mid if not found, for backward compat if not doc or not doc.subject then local docs = elastic.find("message-id:\"" .. r:escape(eid) .. "\"", 1, "mbox") if #docs == 1 then doc = docs[1] end end if doc then local canAccess = false if doc.private then local account = user.get(r) if account then local lid = doc.list_raw:match("<[^.]+%.(.-)>") for k, v in pairs(aaa.rights(r, account.credentials.uid or account.credentials.email)) do if v == "*" or v == lid then canAccess = true break end end else r:puts(JSON.encode{ error = "You must be logged in to view this email" }) return apache2.OK end else canAccess = true end if canAccess then doc.tid = doc.request_id if get.attachment then local hash = r:escape(get.file) local fdoc = elastic.get("attachment", hash) if fdoc and fdoc.source then local out = r:base64_decode(fdoc.source) local ct = "application/binary" local fn = "unknown" local fs = 0 for k, v in pairs(doc.attachments or {}) do if v.hash == hash then ct = v.content_type or "application/binary" fn = v.filename fs = v.size break end end r.content_type = ct r.headers_out['Content-Length'] = fs if not (ct:match("image") or ct:match("text")) then r.headers_out['Content-Disposition'] = ("attachment; filename=\"%s\";"):format(fn) end r:write(out) return apache2.OK end else r:puts(JSON.encode(doc)) end else r:puts(JSON.encode{ error = "You do not have access to view this email, sorry." }) return apache2.OK end else r:puts[[{}]] end return apache2.OK end
--[[ 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. ]]-- -- This is email.lua - a script for fetching a document (email) local JSON = require 'cjson' local elastic = require 'lib/elastic' local aaa = require 'lib/aaa' local user = require 'lib/user' function handle(r) r.content_type = "application/json" local get = r:parseargs() local eid = (get.id or ""):gsub("\"", "") local doc = elastic.get("mbox", eid or "hmm") -- Try searching by mid if not found, for backward compat if not doc or not doc.subject then local docs = elastic.find("message-id:\"" .. r:escape(eid) .. "\"", 1, "mbox") if #docs == 1 then doc = docs[1] end end if doc then local canAccess = false if doc.private then local account = user.get(r) if account then local lid = doc.list_raw:match("<[^.]+%.(.-)>") for k, v in pairs(aaa.rights(r, account.credentials.uid or account.credentials.email)) do if v == "*" or v == lid then canAccess = true break end end else r:puts(JSON.encode{ error = "You must be logged in to view this email" }) return apache2.OK end else canAccess = true end if canAccess then doc.tid = doc.request_id if get.attachment then local hash = r:escape(get.file) local fdoc = elastic.get("attachment", hash) if fdoc and fdoc.source then local out = r:base64_decode(fdoc.source:gsub("\n", "")) -- bug in mod_lua? local ct = "application/binary" local fn = "unknown" local fs = 0 for k, v in pairs(doc.attachments or {}) do if v.hash == hash then ct = v.content_type or "application/binary" fn = v.filename fs = v.size break end end r.content_type = ct r.headers_out['Content-Length'] = fs if not (ct:match("image") or ct:match("text")) then r.headers_out['Content-Disposition'] = ("attachment; filename=\"%s\";"):format(fn) end r:write(out) return apache2.OK end else r:puts(JSON.encode(doc)) end else r:puts(JSON.encode{ error = "You do not have access to view this email, sorry." }) return apache2.OK end else r:puts[[{}]] end return apache2.OK end
got ourselves a lua bug!
got ourselves a lua bug!
Lua
apache-2.0
quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail,quenda/ponymail,Humbedooh/ponymail,rbowen/ponymail,jimjag/ponymail,Humbedooh/ponymail,rbowen/ponymail,jimjag/ponymail,jimjag/ponymail,rbowen/ponymail,quenda/ponymail
ba1435b60c0746cf9393946f467b756374c2cdde
plugins/ninegag.lua
plugins/ninegag.lua
--[[ Copyright 2017 Matthew Hesketh <wrxck0@gmail.com> This code is licensed under the MIT. See LICENSE for details. ]] local ninegag = {} local mattata = require('mattata') local http = require('socket.http') local json = require('dkjson') function ninegag:init() ninegag.commands = mattata.commands(self.info.username):command('ninegag').table ninegag.help = '/ninegag - Returns a random image from the latest 9gag posts.' end function ninegag:on_inline_query(inline_query, configuration) local jstr, res = http.request('http://api-9gag.herokuapp.com/') if res ~= 200 then return end local jdat = json.decode(jstr) local results_list = {} local id = 1 for n in pairs(jdat) do if jdat[n].src and jdat[n].title then table.insert( results_list, { ['type'] = 'photo', ['id'] = tostring(id), ['photo_url'] = jdat[n].src, ['thumb_url'] = jdat[n].src, ['caption'] = jdat[n].title:gsub('"', '\\"') } ) id = id + 1 end end return mattata.answer_inline_query( inline_query.id, json.encode(results_list) ) end function ninegag:on_message(message, configuration, language) local jstr, res = http.request('http://api-9gag.herokuapp.com/') if res ~= 200 then return mattata.send_reply( message, language['errors']['connection'] ) end mattata.send_chat_action( message.chat.id, 'upload_photo' ) local jdat = json.decode(jstr) return mattata.send_photo( message.chat.id, jdat[jrnd].src, jdat[jrnd].title, false, nil, mattata.inline_keyboard():row( mattata.row():url_button( language['ninegag']['1'], jdat[math.random(#jdat)].url ) ) ) end return ninegag
--[[ Copyright 2017 Matthew Hesketh <wrxck0@gmail.com> This code is licensed under the MIT. See LICENSE for details. ]] local ninegag = {} local mattata = require('mattata') local http = require('socket.http') local json = require('dkjson') function ninegag:init() ninegag.commands = mattata.commands(self.info.username):command('ninegag').table ninegag.help = '/ninegag - Returns a random image from the latest 9gag posts.' end function ninegag:on_inline_query(inline_query, configuration) local jstr, res = http.request('http://api-9gag.herokuapp.com/') if res ~= 200 then return end local jdat = json.decode(jstr) local results_list = {} local id = 1 for n in pairs(jdat) do if jdat[n].src and jdat[n].title then table.insert( results_list, { ['type'] = 'photo', ['id'] = tostring(id), ['photo_url'] = jdat[n].src, ['thumb_url'] = jdat[n].src, ['caption'] = jdat[n].title:gsub('"', '\\"') } ) id = id + 1 end end return mattata.answer_inline_query( inline_query.id, json.encode(results_list) ) end function ninegag:on_message(message, configuration, language) local jstr, res = http.request('http://api-9gag.herokuapp.com/') if res ~= 200 then return mattata.send_reply( message, language['errors']['connection'] ) end mattata.send_chat_action( message.chat.id, 'upload_photo' ) local jdat = json.decode(jstr) local jrnd = math.random(#jdat) return mattata.send_photo( message.chat.id, jdat[jrnd].src, jdat[jrnd].title, false, nil, mattata.inline_keyboard():row( mattata.row():url_button( language['ninegag']['1'], jdat[jrnd].url ) ) ) end return ninegag
[v21] Minor bug fix
[v21] Minor bug fix
Lua
mit
barreeeiroo/BarrePolice
5dd1c6cf7a4c4aad5b316c377c367270f8d1bb7b
fusion/Modules/Lua/test_cryptomatte_utilities.lua
fusion/Modules/Lua/test_cryptomatte_utilities.lua
--[[ Requires : Fusion 9.0.2+ Optional : cjson Created by : Cédric Duriau [duriau.cedric@live.be] Kristof Indeherberge [xmnr0x23@gmail.com] Andrew Hazelden [andrew@andrewhazelden.com] Version : 1.2.8 --]] local cryptoutils = require("cryptomatte_utilities") -- utils function collect_tests(module) --[[ Returns function names detected as test. Functions with names starting with "test_" will be picked up. :param module: Module to collect test function names of. :type module: table[string, function] :rtype: table[stri] ]] local tests = {} local substr = "test_" for name, _ in pairs(module) do if string.sub(name, 1, string.len(substr)) == substr then table.insert(tests, name) end end table.sort(tests) return tests end function run_tests(module) --[[ Detects and runs all test functions of a module. :param module: Module to run all tests for. :type module: table[string, function] ]] -- collect all tests from module print("collectings test(s) ...") local tests = collect_tests(module) local ntests = #tests print(string.format("detected %s test(s) ...", ntests)) local count = 0 for _, name in ipairs(tests) do count = count + 1 local percentage = (count / ntests) * 100 local percentage_str = string.format("%.0f%%", percentage) local padding = string.rep(" ", 4 - string.len(percentage_str)) percentage_str = string.format("%s%s", padding, percentage_str) local report = string.format("[%s] %s ... ", percentage_str, name) local status, err = pcall(module[name]) if status then report = string.format("%s [%s]", report, "OK") else report = string.format("%s [%s]\n%s", report, "FAILED", err) end print(report) end end function assert_equal(x, y) --[[ Tests the equality of two variables. :rtype: boolean ]] if x == y then return true else error(string.format("%s\nassertion failed: %s != %s", debug.traceback(), x, y)) end end -- mock funtions storage = {} function mock_print(msg) storage["print_return"] = msg end function mock_log_level_unset() return nil end function mock_log_level_error() return "0" end function mock_log_level_warning() return "1" end function mock_log_level_info() return "2" end function mock_node() return {Name="NODE1"} end -- tests module = {} function module.test__format_log() old_self = self self = mock_node() local result = cryptoutils._format_log("LEVEL", "MESSAGE") self = old_self assert_equal(result, "[Cryptomatte][NODE1][LEVEL] MESSAGE") end function module.test__get_log_level() old_get_env = os.getenv -- mock log level not set in environment os.getenv = mock_log_level_unset local r1 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r1, 0) -- mock log level info set in environment (string -> number cast) os.getenv = mock_log_level_info local r2 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r2, 2) end function module.test__string_starts_with() assert_equal(cryptoutils._string_starts_with("foo_bar", "foo_"), true) assert_equal(cryptoutils._string_starts_with("foo_bar", "bar"), false) end function module.test__string_ends_with() assert_equal(cryptoutils._string_ends_with("foo_bar", "_bar"), true) assert_equal(cryptoutils._string_ends_with("foo_bar", "foo"), false) end function module.test__string_split() result = cryptoutils._string_split("foo, bar,bunny", "([^,]+),?%s*") assert_equal(#result, 3) expected = {"foo", "bar", "bunny"} for i, v in ipairs(result) do assert_equal(v, expected[i]) end end function module.test__solve_channel_name() -- r assert_equal(cryptoutils._solve_channel_name("r"), "r") assert_equal(cryptoutils._solve_channel_name("R"), "r") assert_equal(cryptoutils._solve_channel_name("red"), "r") assert_equal(cryptoutils._solve_channel_name("RED"), "r") -- g assert_equal(cryptoutils._solve_channel_name("g"), "g") assert_equal(cryptoutils._solve_channel_name("G"), "g") assert_equal(cryptoutils._solve_channel_name("green"), "g") assert_equal(cryptoutils._solve_channel_name("GREEN"), "g") -- b assert_equal(cryptoutils._solve_channel_name("b"), "b") assert_equal(cryptoutils._solve_channel_name("B"), "b") assert_equal(cryptoutils._solve_channel_name("blue"), "b") assert_equal(cryptoutils._solve_channel_name("BLUE"), "b") -- a assert_equal(cryptoutils._solve_channel_name("a"), "a") assert_equal(cryptoutils._solve_channel_name("A"), "a") assert_equal(cryptoutils._solve_channel_name("alpha"), "a") assert_equal(cryptoutils._solve_channel_name("ALPHA"), "a") end function module.test__get_channel_hierarchy() -- TODO end function module.test__get_absolute_position() local x, y = cryptoutils._get_absolute_position(10, 10, 0.5, 0.5) assert_equal(x, 5) assert_equal(y, 5) end function module.test__is_position_in_rect() -- NOTE: fusion rectangles follow mathematical convention, (origin=left,bottom) local rect = {left=0, top=10, right=10, bottom=0} assert_equal(cryptoutils._is_position_in_rect(rect, 5, 5), true) assert_equal(cryptoutils._is_position_in_rect(rect, 12, 5), false) assert_equal(cryptoutils._is_position_in_rect(rect, 5, 12), false) end function module.test__hex_to_float() assert_equal(cryptoutils._hex_to_float("3f800000"), 1.0) assert_equal(cryptoutils._hex_to_float("bf800000"), -1.0) end function module.test_log_error() -- TODO end function module.test_log_warning() -- TODO end function module.test_log_info() -- TODO end function module.test_get_cryptomatte_metadata() -- TODO end function module.test_read_manifest_file() -- TODO end function module.test_decode_manifest() -- TODO end function module.test_get_matte_names() -- TODO end run_tests(module)
--[[ Requires : Fusion 9.0.2+ Optional : cjson Created by : Cédric Duriau [duriau.cedric@live.be] Kristof Indeherberge [xmnr0x23@gmail.com] Andrew Hazelden [andrew@andrewhazelden.com] Version : 1.2.8 --]] local cryptoutils = require("cryptomatte_utilities") -- utils function collect_tests(module) --[[ Returns function names detected as test. Functions with names starting with "test_" will be picked up. :param module: Module to collect test function names of. :type module: table[string, function] :rtype: table[stri] ]] local tests = {} local substr = "test_" for name, _ in pairs(module) do if string.sub(name, 1, string.len(substr)) == substr then table.insert(tests, name) end end table.sort(tests) return tests end function run_tests(module) --[[ Detects and runs all test functions of a module. :param module: Module to run all tests for. :type module: table[string, function] ]] -- collect all tests from module print("collectings test(s) ...") local tests = collect_tests(module) local ntests = #tests print(string.format("detected %s test(s) ...", ntests)) local count = 0 for _, name in ipairs(tests) do count = count + 1 local percentage = (count / ntests) * 100 local percentage_str = string.format("%.0f%%", percentage) local padding = string.rep(" ", 4 - string.len(percentage_str)) percentage_str = string.format("%s%s", padding, percentage_str) local report = string.format("[%s] %s ... ", percentage_str, name) local status, err = pcall(module[name]) if status then report = string.format("%s [%s]", report, "OK") else report = string.format("%s [%s]\n%s", report, "FAILED", err) end print(report) end end function assert_equal(x, y) --[[ Tests the equality of two variables. :rtype: boolean ]] if x == y then return true else error(string.format("%s\nassertion failed: %s != %s", debug.traceback(), x, y)) end end -- mock funtions storage = {} function mock_print(message) storage["print_return"] = message end function mock_log_level_unset() return nil end function mock_log_level_error() return "0" end function mock_log_level_warning() return "1" end function mock_log_level_info() return "2" end function mock_self_node() return {Name="NODE1"} end -- tests module = {} function module.test__format_log() local old_self = self self = mock_self_node() assert_equal(cryptoutils._format_log("LEVEL", "MESSAGE"), "[Cryptomatte][NODE1][LEVEL] MESSAGE") self = old_self end function module.test__get_log_level() old_get_env = os.getenv -- mock log level not set in environment os.getenv = mock_log_level_unset local r1 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r1, 0) -- mock log level info set in environment (string -> number cast) os.getenv = mock_log_level_info local r2 = cryptoutils._get_log_level() os.getenv = old_get_env assert_equal(r2, 2) end function module.test__string_starts_with() assert_equal(cryptoutils._string_starts_with("foo_bar", "foo_"), true) assert_equal(cryptoutils._string_starts_with("foo_bar", "bar"), false) end function module.test__string_ends_with() assert_equal(cryptoutils._string_ends_with("foo_bar", "_bar"), true) assert_equal(cryptoutils._string_ends_with("foo_bar", "foo"), false) end function module.test__string_split() result = cryptoutils._string_split("foo, bar,bunny", "([^,]+),?%s*") assert_equal(#result, 3) expected = {"foo", "bar", "bunny"} for i, v in ipairs(result) do assert_equal(v, expected[i]) end end function module.test__solve_channel_name() -- r assert_equal(cryptoutils._solve_channel_name("r"), "r") assert_equal(cryptoutils._solve_channel_name("R"), "r") assert_equal(cryptoutils._solve_channel_name("red"), "r") assert_equal(cryptoutils._solve_channel_name("RED"), "r") -- g assert_equal(cryptoutils._solve_channel_name("g"), "g") assert_equal(cryptoutils._solve_channel_name("G"), "g") assert_equal(cryptoutils._solve_channel_name("green"), "g") assert_equal(cryptoutils._solve_channel_name("GREEN"), "g") -- b assert_equal(cryptoutils._solve_channel_name("b"), "b") assert_equal(cryptoutils._solve_channel_name("B"), "b") assert_equal(cryptoutils._solve_channel_name("blue"), "b") assert_equal(cryptoutils._solve_channel_name("BLUE"), "b") -- a assert_equal(cryptoutils._solve_channel_name("a"), "a") assert_equal(cryptoutils._solve_channel_name("A"), "a") assert_equal(cryptoutils._solve_channel_name("alpha"), "a") assert_equal(cryptoutils._solve_channel_name("ALPHA"), "a") end function module.test__get_channel_hierarchy() -- TODO end function module.test__get_absolute_position() local x, y = cryptoutils._get_absolute_position(10, 10, 0.5, 0.5) assert_equal(x, 5) assert_equal(y, 5) end function module.test__is_position_in_rect() -- NOTE: fusion rectangles follow mathematical convention, (origin=left,bottom) local rect = {left=0, top=10, right=10, bottom=0} assert_equal(cryptoutils._is_position_in_rect(rect, 5, 5), true) assert_equal(cryptoutils._is_position_in_rect(rect, 12, 5), false) assert_equal(cryptoutils._is_position_in_rect(rect, 5, 12), false) end function module.test__hex_to_float() assert_equal(cryptoutils._hex_to_float("3f800000"), 1.0) assert_equal(cryptoutils._hex_to_float("bf800000"), -1.0) end function module.test_log_error() -- TODO end function module.test_log_warning() -- TODO end function module.test_log_info() -- TODO end function module.test_get_cryptomatte_metadata() -- TODO end function module.test_read_manifest_file() -- TODO end function module.test_decode_manifest() -- TODO end function module.test_get_matte_names() -- TODO end run_tests(module)
fix format test
fix format test
Lua
bsd-3-clause
Psyop/Cryptomatte
863f5a69f4a927bd621a9925a14f39ee2dc38e2b
src/patch/ui/hooks/common/protocol_kickunpatched.lua
src/patch/ui/hooks/common/protocol_kickunpatched.lua
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- 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. if _mpPatch and _mpPatch.loaded then local playerMap = {} local isPatched = {} local chatActive = {} local chatQueue = {} local function sendChat(playerId, fn) if chatActive[playerId] then fn() else if not chatQueue[playerId] then chatQueue[playerId] = {} end table.insert(chatQueue[playerId], fn) end end local function setChatActive(playerId) chatQueue[playerId] = true if chatQueue[playerId] then for _, fn in ipairs(chatQueue[playerId]) do fn() end end end local getPlayerName, joinWarning1Ending function _mpPatch.hooks.protocol_kickunpached_init(pGetPlayerName, pIsInGame) getPlayerName = pGetPlayerName joinWarning1Ending = Locale.Lookup(isInGame and "TXT_KEY_MPPATCH_JOIN_WARNING_1_INGAME" or "TXT_KEY_MPPATCH_JOIN_WARNING_1_STAGING") end local website = _mpPatch.version.info["mppatch.website"] or "<unknown>" local function getHeader(playerId) local header = "" if getPlayerName then local name = getPlayerName(playerId) if name then header = "@"..tostring(name)..": " end end return header end function _mpPatch.hooks.protocol_kickunpached_installHooks() _mpPatch.addResetHook(function() playerMap = {} isPatched = {} chatActive = {} chatQueue = {} end) _mpPatch.net.clientIsPatched.registerHandler(function(protocolVersion, playerId) if Matchmaking.IsHost() then if protocolVersion == _mpPatch.protocolVersion then playerMap[playerId] = nil isPatched[playerId] = true else local header = getHeader(playerId) sendChat(playerId, function() _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_OUTDATED").." ".. joinWarning1Ending) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end) end end end) local function checkPlayerId(player, reason) if playerMap[player] then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch. ("..reason..")") Matchmaking.KickPlayer(player) playerMap[player] = nil end end _mpPatch.event.kickIfUnpatched.registerHandler(function(player, reason) if Matchmaking.IsHost() then checkPlayerId(player, reason) end end) _mpPatch.event.kickAllUnpatched.registerHandler(function(reason) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do checkPlayerId(player, reason) end end end) end function _mpPatch.hooks.protocol_kickunpached_onUpdate(timeDiff) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do playerMap[player] = playerMap[player] - timeDiff if playerMap[player] <= 0 then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch.") Matchmaking.KickPlayer(player) playerMap[player] = nil end end end end function _mpPatch.hooks.protocol_kickunpached_chatActive(playerId) setChatActive(playerId) end function _mpPatch.hooks.protocol_kickunpached_onJoin(playerId) if Matchmaking.IsHost() and not playerMap[playerId] and not isPatched[playerId] then local header = getHeader(playerId) sendChat(playerId, function() _mpPatch.net.skipNextChat(2) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_NOT_INSTALLED").." ".. joinWarning1Ending) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end) playerMap[playerId] = 30 end end function _mpPatch.hooks.protocol_kickunpached_onDisconnect(playerId) if Matchmaking.IsHost() then playerMap[playerId] = nil isPatched[playerId] = nil chatActive[playerId] = nil chatQueue[playerId] = nil end end end
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com> -- -- 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. if _mpPatch and _mpPatch.loaded then local playerMap = {} local isPatched = {} local chatActive = {} local chatQueue = {} local function sendChat(playerId, fn) if chatActive[playerId] then fn() else if not chatQueue[playerId] then chatQueue[playerId] = {} end table.insert(chatQueue[playerId], fn) end end local function setChatActive(playerId) chatQueue[playerId] = true if chatQueue[playerId] then for _, fn in ipairs(chatQueue[playerId]) do fn() end chatQueue[playerId] = nil end end local getPlayerName, joinWarning1Ending function _mpPatch.hooks.protocol_kickunpached_init(pGetPlayerName, pIsInGame) getPlayerName = pGetPlayerName joinWarning1Ending = Locale.Lookup(isInGame and "TXT_KEY_MPPATCH_JOIN_WARNING_1_INGAME" or "TXT_KEY_MPPATCH_JOIN_WARNING_1_STAGING") end local website = _mpPatch.version.info["mppatch.website"] or "<unknown>" local function getHeader(playerId) local header = "" if getPlayerName then local name = getPlayerName(playerId) if name then header = "@"..tostring(name)..": " end end return header end function _mpPatch.hooks.protocol_kickunpached_installHooks() _mpPatch.addResetHook(function() playerMap = {} isPatched = {} chatActive = {} chatQueue = {} end) _mpPatch.net.clientIsPatched.registerHandler(function(protocolVersion, playerId) if Matchmaking.IsHost() then if protocolVersion == _mpPatch.protocolVersion then playerMap[playerId] = nil isPatched[playerId] = true else local header = getHeader(playerId) sendChat(playerId, function() _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_OUTDATED").." ".. joinWarning1Ending) _mpPatch.skipNextChatIfVersion(_mpPatch.protocolVersion) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end) end end end) local function checkPlayerId(player, reason) if playerMap[player] then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch. ("..reason..")") Matchmaking.KickPlayer(player) playerMap[player] = nil end end _mpPatch.event.kickIfUnpatched.registerHandler(function(player, reason) if Matchmaking.IsHost() then checkPlayerId(player, reason) end end) _mpPatch.event.kickAllUnpatched.registerHandler(function(reason) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do checkPlayerId(player, reason) end end end) end function _mpPatch.hooks.protocol_kickunpached_onUpdate(timeDiff) if Matchmaking.IsHost() then for player, _ in pairs(playerMap) do playerMap[player] = playerMap[player] - timeDiff if playerMap[player] <= 0 then _mpPatch.debugPrint("Kicking player "..player.." for (presumably) not having MPPatch.") Matchmaking.KickPlayer(player) playerMap[player] = nil end end end end function _mpPatch.hooks.protocol_kickunpached_chatActive(playerId) setChatActive(playerId) end function _mpPatch.hooks.protocol_kickunpached_onJoin(playerId) if Matchmaking.IsHost() and not playerMap[playerId] and not isPatched[playerId] then local header = getHeader(playerId) sendChat(playerId, function() _mpPatch.net.skipNextChat(2) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_1_NOT_INSTALLED").." ".. joinWarning1Ending) Network.SendChat(header..Locale.Lookup("TXT_KEY_MPPATCH_JOIN_WARNING_2")..website) end) playerMap[playerId] = 30 end end function _mpPatch.hooks.protocol_kickunpached_onDisconnect(playerId) if Matchmaking.IsHost() then playerMap[playerId] = nil isPatched[playerId] = nil chatActive[playerId] = nil chatQueue[playerId] = nil end end end
Fix chat queue.
Fix chat queue.
Lua
mit
Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MPPatch
76887679781d2ae3ea432d860e507116986c4f48
installer.lua
installer.lua
function file2table(file,atable) local fp = io.open(file, "r") for line in fp:lines() do table.insert (atable, line) end fp:close() end local commands = {} file2table("./resources/commands.txt", commands) local whoami = assert(io.popen("whoami", "r")) local homedir = whoami:read('*all') whoami:close() local uid = homedir:sub(1,homedir:len()-1) homedir = "/home/" .. homedir:sub(1,homedir:len()-1) local torrentdir = homedir .. "/rtorrent" print("Welcome to the Raspberry PI RuTorrent Installer") print("created by Pyro_Killer") print("It is currently in early pre-dev and will not work at all") print("Checking for a working internet connection") os.execute("wget http://detectportal.firefox.com/success.txt 2> /dev/null") local internetcheck = io.open("success.txt","r") if internetcheck == nil then print("There appears to be no internet connection") os.exit() else print("Internet connection confirmed") internetcheck:close() os.execute("rm success.txt") end print("Please enter location of the rtorrent downloads") print("If you use the same media as your system is on") print("the entire operating system will start getting stuttery") print("So I suggest you use something like a USB stick or ") print("external hard drive. Press enter to leave as default") io.write("[" .. torrentdir .. "]") io.flush() local inputdir = io.read() if inputdir ~= "" then torrentdir = inputdir end local dircheck = assert(io.popen("cd " .. torrentdir .. " 2>&1", "r")) local dircheck_data = dircheck:read('*all') dircheck:close() if dircheck_data ~= "" then local super_dir = torrentdir:reverse() local new_dir = super_dir:sub(1,super_dir:find("/" )-1) super_dir = super_dir:sub(super_dir:find("/" )+1) new_dir = new_dir:reverse() super_dir = super_dir:reverse() dircheck = assert(io.popen("cd " .. super_dir .. " 2>&1", "r")) local dircheck_data = dircheck:read('*all') dircheck:close() if dircheck_data == "" then os.execute("cd " .. super_dir .. " && mkdir " .. new_dir ) else print("The location you entered is invalid") os.exit() end end print(torrentdir .. " will be used as rtorrent directory") if torrentdir:sub(torrentdir:len()) == "/" then torrentdir = torrentdir:sub(1,torrentdir:len()-1) end os.execute("sudo mkdir -p " .. torrentdir .. "/{.session,~watch}") os.execute("sudo chown -R " .. uid .. " " .. torrentdir) for i = 1, #commands do local x, y = commands[i]:find(";") print(commands[i]:sub(x+1)) os.execute(commands[i]:sub(1,x-1)) end os.execute("sudo lua ./resources/rewriter.lua ".. torrentdir .. " " .. homedir) print("Please enter the username for the RuTorrent login") io.write("Login: ") io.flush() local login = io.read() os.execute("sudo htdigest -c /etc/apache2/.htpasswd rutorrent " .. login) print("Restarting apache") os.execute("sudo service apache2 restart >> /dev/null") print("Starting rTorrent") os.execute("screen -S rtorrent -fa -d -m rtorrent")
function file2table(file,atable) local fp = io.open(file, "r") for line in fp:lines() do table.insert (atable, line) end fp:close() end local commands = {} file2table("./resources/commands.txt", commands) local whoami = assert(io.popen("whoami", "r")) local homedir = whoami:read('*all') whoami:close() local uid = homedir:sub(1,homedir:len()-1) homedir = "/home/" .. homedir:sub(1,homedir:len()-1) local torrentdir = homedir .. "/rtorrent" print("Welcome to the Raspberry PI RuTorrent Installer") print("created by Pyro_Killer") print("It is currently in early pre-dev and will not work at all") print("Checking for a working internet connection") os.execute("wget http://detectportal.firefox.com/success.txt 2> /dev/null") local internetcheck = io.open("success.txt","r") if internetcheck == nil then print("There appears to be no internet connection") os.exit() else print("Internet connection confirmed") internetcheck:close() os.execute("rm success.txt") end print("Please enter location of the rtorrent downloads") print("If you use the same media as your system is on") print("the entire operating system will start getting stuttery") print("So I suggest you use something like a USB stick or ") print("external hard drive. Press enter to leave as default") io.write("[" .. torrentdir .. "]") io.flush() local inputdir = io.read() if inputdir ~= "" then torrentdir = inputdir end local dircheck = assert(io.popen("cd " .. torrentdir .. " 2>&1", "r")) local dircheck_data = dircheck:read('*all') dircheck:close() if dircheck_data ~= "" then local super_dir = torrentdir:reverse() local new_dir = super_dir:sub(1,super_dir:find("/" )-1) super_dir = super_dir:sub(super_dir:find("/" )+1) new_dir = new_dir:reverse() super_dir = super_dir:reverse() dircheck = assert(io.popen("cd " .. super_dir .. " 2>&1", "r")) local dircheck_data = dircheck:read('*all') dircheck:close() if dircheck_data == "" then os.execute("cd " .. super_dir .. " && mkdir " .. new_dir ) else print("The location you entered is invalid") os.exit() end end print(torrentdir .. " will be used as rtorrent directory") if torrentdir:sub(torrentdir:len()) == "/" then torrentdir = torrentdir:sub(1,torrentdir:len()-1) end os.execute("sudo mkdir " .. torrentdir .. "/.session") os.execute("sudo mkdir " .. torrentdir .. "/watch") os.execute("sudo chown -R " .. uid .. " " .. torrentdir) for i = 1, #commands do local x, y = commands[i]:find(";") print(commands[i]:sub(x+1)) os.execute(commands[i]:sub(1,x-1)) end os.execute("sudo lua ./resources/rewriter.lua ".. torrentdir .. " " .. homedir) print("Please enter the username for the RuTorrent login") io.write("Login: ") io.flush() local login = io.read() os.execute("sudo htdigest -c /etc/apache2/.htpasswd rutorrent " .. login) print("Restarting apache") os.execute("sudo service apache2 restart >> /dev/null") print("Starting rTorrent") os.execute("screen -S rtorrent -fa -d -m rtorrent")
Fixed mkdir
Fixed mkdir
Lua
mit
LarsHLunde/RuTorrent-Installer
95b40caa3d89c38c057a02a9303f54d363cfe7e4
spec/02-integration/02-cmd/10-migrations_spec.lua
spec/02-integration/02-cmd/10-migrations_spec.lua
local helpers = require "spec.helpers" local pl_utils = require "pl.utils" local dao = helpers.dao -- postgreSQL DAO (faster to test this command) describe("kong migrations", function() describe("reset", function() before_each(function() assert(dao:run_migrations()) end) teardown(function() dao:drop_schema() end) it("runs interactively by default", function() local answers = { "y", "Y", "yes", "YES", } for _, answer in ipairs(answers) do local cmd = string.format(helpers.unindent [[ echo %s | %s migrations reset -c %s ]], answer, helpers.bin_path, helpers.test_conf_path) local ok, _, stdout, stderr = pl_utils.executeex(cmd) assert.is_true(ok) assert.equal("", stderr) assert.matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) assert(dao:run_migrations()) end end) it("cancels when ran interactively", function() local answers = { "n", "N", "no", "NO", } for _, answer in ipairs(answers) do local cmd = string.format(helpers.unindent [[ echo %s | %s migrations reset -c %s ]], answer, helpers.bin_path, helpers.test_conf_path) local ok, _, stdout, stderr = pl_utils.executeex(cmd) assert.is_true(ok) assert.equal("", stderr) assert.matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Canceled", stdout, nil, true) end end) it("runs non-interactively with --yes", function() local ok, stderr, stdout = helpers.kong_exec("migrations reset --yes -c " .. helpers.test_conf_path) assert.is_true(ok) assert.is_equal("", stderr) assert.not_matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) end) it("runs non-interactively with -y", function() local ok, stderr, stdout = helpers.kong_exec("migrations reset -y -c " .. helpers.test_conf_path) assert.is_true(ok) assert.is_equal("", stderr) assert.not_matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) end) end) end)
local helpers = require "spec.helpers" local pl_utils = require "pl.utils" local dao = helpers.dao -- postgreSQL DAO (faster to test this command) describe("kong migrations", function() describe("reset", function() before_each(function() assert(dao:run_migrations()) end) teardown(function() dao:drop_schema() end) it("runs interactively by default", function() local answers = { "y", "Y", "yes", "YES", } for _, answer in ipairs(answers) do local cmd = string.format(helpers.unindent [[ echo %s | %s migrations reset -c %s ]], answer, helpers.bin_path, helpers.test_conf_path) local ok, _, stdout, stderr = pl_utils.executeex(cmd) assert.is_true(ok) assert.not_matches("error", stderr, nil, true) assert.matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) assert(dao:run_migrations()) end end) it("cancels when ran interactively", function() local answers = { "n", "N", "no", "NO", } for _, answer in ipairs(answers) do local cmd = string.format(helpers.unindent [[ echo %s | %s migrations reset -c %s ]], answer, helpers.bin_path, helpers.test_conf_path) local ok, _, stdout, stderr = pl_utils.executeex(cmd) assert.is_true(ok) assert.not_matches("error", stderr, nil, true) assert.matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Canceled", stdout, nil, true) end end) it("runs non-interactively with --yes", function() local ok, stderr, stdout = helpers.kong_exec("migrations reset --yes -c " .. helpers.test_conf_path) assert.is_true(ok) assert.not_matches("error", stderr, nil, true) assert.not_matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) end) it("runs non-interactively with -y", function() local ok, stderr, stdout = helpers.kong_exec("migrations reset -y -c " .. helpers.test_conf_path) assert.is_true(ok) assert.not_matches("error", stderr, nil, true) assert.not_matches("Are you sure? This operation is irreversible. [Y/n]", stdout, nil, true) assert.matches("Schema successfully reset", stdout, nil, true) end) end) end)
tests(*) fix some failing test cases due to lua-cassandra bump
tests(*) fix some failing test cases due to lua-cassandra bump Starting with lua-cassandra 1.3.3, we log a warning message when the `rpc_address` of nodes is "bind all" (as with other Datastax drivers). Updating the Travis-CI ccm scripts so that it binds on the local interface has been considered, but since nothing guarantees that other existing tests setups out there don't make the same mistake, this approach is safer.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
6b35ac37b35eb5b950272455cfef8ff33664cdab
src/lib/configure/lang/cxx/libraries/boost.lua
src/lib/configure/lang/cxx/libraries/boost.lua
--- C++ Boost libraries -- @module configure.lang.cxx.libraries local M = {} local function default_component_defines(component, kind, threading) if component == 'unit_test_framework' and kind == 'shared' then return {'BOOST_TEST_DYN_LINK'} end return {} end --- Find Boost libraries -- -- @param args -- @param args.compiler A compiler instance -- @param args.components A list of components -- @param[opt] args.version The required version (defaults to the latest found) -- @param[opt] args.env_prefix A prefix for all environment variables (default to BOOST) -- @param[opt] args.kind 'shared' or 'static' (default to 'static') -- @param[opt] args.defines A list of preprocessor definitions -- @param[opt] args.threading Search for threading enable libraries (default to the compiler default) -- @param[opt] args.<COMPONENT>_kind Select the 'static' or 'shared' version of a component. -- @param[opt] args.<COMPONENT>_defines A list of preprocessor definitions function M.find(args) local env_prefix = args.env_prefix or 'BOOST' local build = args.compiler.build local fs = build:fs() local boost_root = build:path_option( env_prefix .. '-root', "Boost root directory" ) local boost_include_dir = build:lazy_path_option( env_prefix .. '-include-dir', "Boost include directory", function () local dirs = {} if boost_root ~= nil then table.append(dirs, boost_root) table.append(dirs, boost_root / 'include') end table.extend(dirs, args.compiler:system_include_directories()) return fs:find_file( dirs, 'boost/version.hpp' ):path():parent_path():parent_path() end ) local boost_version_header = build:file_node(boost_include_dir / 'boost/version.hpp') if not boost_version_header:path():exists() then build:error("Couldn't find 'boost/version.hpp' in", boost_include_dir) end build:debug("Found boost version header at", boost_version_header) local boost_library_dir = build:lazy_path_option( env_prefix .. '-library-dir', "Boost library dir", function () local dirs = {} if boost_root then table.append(dirs, boost_root / 'lib') table.append(dirs, boost_root / 'stage/lib') end table.extend(dirs, args.compiler:system_library_directories()) for _, dir in ipairs(dirs) do build:debug("Examining library directory", dir) for _, lib in ipairs(fs:glob(dir, "libboost_*")) do -- return when some file is found return dir end end build:error("Couldn't find Boost library directory (checked " .. table.tostring(dirs) .. ")") end ) local components = args.components if components == nil then build:error("You must provide a list of Boost libraries to search for") end local component_files = {} for _, lib in ipairs(fs:glob(boost_library_dir, "libboost_*")) do for _, component in ipairs(components) do local filename = tostring(lib:path():filename()) if filename:starts_with("libboost_" .. component) or (build:target():os() == Platform.OS.windows and filename:starts_with("boost_")) then if component_files[component] == nil then component_files[component] = {} end table.append(component_files[component], lib) build:debug("Found Boost library", lib, "for component", component) end end end local Library = require('configure.lang.cxx.Library') local res = {} for _, component in ipairs(components) do if component_files[component] == nil then build:error("Couldn't find library files for boost component '" .. component .. "'") end local files = component_files[component] local filtered = {} local kind = args[component .. '_kind'] or args.kind or 'static' -- Filter files based on the kind selected ('static' or 'shared') local ext = args.compiler:_library_extension(kind) for i, f in ipairs(files) do if tostring(f:path()):ends_with(ext) then build:debug("Select", f, "(ends with '" .. ext .."')") table.append(filtered, f) else build:debug("Ignore", f, "(do not end with '" .. ext .."')") end end local function arg(name, default) local res = args[component .. '_' .. name] if res == nil then return default end return res end local abi_flags = { threading = arg('threading', args.compiler.threading), static_runtime = arg('static_runtime', args.compiler.runtime == 'static'), debug_runtime = arg('debug_runtime', args.compiler.debug_runtime), debug = arg('debug', args.compiler.debug), } local files, selected, unknown = filtered, {}, {} for _, f in ipairs(files) do -- Boost library files are as follow: -- (lib)?boost_<COMPONENT>(-<FLAGS>)?.(lib|a|so)(.<VERSION>)? local flags = tostring(f:path():filename()):match("-[^.]*") local parts = {} if flags ~= nil then parts = flags:split('-') end local check = nil for i, part in ipairs(parts) do if check == false then break end if part == "mt" then check = abi_flags[threading] elseif part:starts_with('vc') then -- TODO: Check against toolset elseif part:match("%d+_%d+_%d+") then -- TODO: Check the version elseif part:match("^s?g?d?p?n?$") then local file_abi_flags = { static_runtime = part:find('s') ~= nil, debug_runtime = part:find('g') ~= nil, debug = part:find('d') ~= nil, stlport = part:find('p') ~= nil, native_iostreams = part:find('n') ~= nil, } for k, v in pairs(abi_flags) do if v ~= file_abi_flags[k] then build:debug("Ignore", f, "(The", k, "abi flag", (v and "is not" or "is"), " present)") check = false break else check = true end end else build:error("Unknown boost library name part '" .. part .. "'") end end if check == true then table.append(selected, f) elseif check == nil then table.append(unknown, f) end end if #selected > 0 then files = selected elseif #unknown > 0 then files = unknown else build:error("Couldn't find any library file for Boost component '" .. component .. "' in:", table.tostring(files)) end if #files > 1 then build:error("Too many file selected for Boost component '" .. component .. "':", table.tostring(files)) end local defines = default_component_defines(component, kind, threading) table.extend(defines, args[component .. '_defines'] or args.defines or {}) build:debug("Boost component '" .. component .. "' defines:", table.tostring(defines)) table.append(res, Library:new{ name = "Boost." .. component, include_directories = { boost_include_dir }, files = files, defines = defines, }) end return res end return M
--- C++ Boost libraries -- @module configure.lang.cxx.libraries local M = {} local function default_component_defines(component, kind, threading) if component == 'unit_test_framework' and kind == 'shared' then return {'BOOST_TEST_DYN_LINK'} end return {} end --- Find Boost libraries -- -- @param args -- @param args.compiler A compiler instance -- @param args.components A list of components -- @param[opt] args.version The required version (defaults to the latest found) -- @param[opt] args.env_prefix A prefix for all environment variables (default to BOOST) -- @param[opt] args.kind 'shared' or 'static' (default to 'static') -- @param[opt] args.defines A list of preprocessor definitions -- @param[opt] args.threading Search for threading enable libraries (default to the compiler default) -- @param[opt] args.<COMPONENT>_kind Select the 'static' or 'shared' version of a component. -- @param[opt] args.<COMPONENT>_defines A list of preprocessor definitions function M.find(args) local env_prefix = args.env_prefix or 'BOOST' local build = args.compiler.build local fs = build:fs() local boost_root = build:path_option( env_prefix .. '-root', "Boost root directory" ) local boost_include_dir = build:lazy_path_option( env_prefix .. '-include-dir', "Boost include directory", function () local dirs = {} if boost_root ~= nil then table.append(dirs, boost_root) table.append(dirs, boost_root / 'include') end table.extend(dirs, args.compiler:system_include_directories()) return fs:find_file( dirs, 'boost/version.hpp' ):path():parent_path():parent_path() end ) local boost_version_header = build:file_node(boost_include_dir / 'boost/version.hpp') if not boost_version_header:path():exists() then build:error("Couldn't find 'boost/version.hpp' in", boost_include_dir) end build:debug("Found boost version header at", boost_version_header) local boost_library_dir = build:lazy_path_option( env_prefix .. '-library-dir', "Boost library dir", function () local dirs = {} if boost_root then table.append(dirs, boost_root / 'lib') table.append(dirs, boost_root / 'stage/lib') end table.extend(dirs, args.compiler:system_library_directories()) for _, dir in ipairs(dirs) do build:debug("Examining library directory", dir) for _, lib in ipairs(fs:glob(dir, "libboost_*")) do -- return when some file is found return dir end end build:error("Couldn't find Boost library directory (checked " .. table.tostring(dirs) .. ")") end ) local components = args.components if components == nil then build:error("You must provide a list of Boost libraries to search for") end local component_files = {} for _, lib in ipairs(fs:glob(boost_library_dir, "libboost_*")) do for _, component in ipairs(components) do local filename = tostring(lib:path():filename()) if filename:starts_with("libboost_" .. component) or (build:target():os() == Platform.OS.windows and filename:starts_with("boost_")) then if component_files[component] == nil then component_files[component] = {} end table.append(component_files[component], lib) build:debug("Found Boost library", lib, "for component", component) end end end local Library = require('configure.lang.cxx.Library') local res = {} for _, component in ipairs(components) do if component_files[component] == nil then build:error("Couldn't find library files for boost component '" .. component .. "'") end local files = component_files[component] local filtered = {} local kind = args[component .. '_kind'] or args.kind or 'static' -- Filter files based on the kind selected ('static' or 'shared') local ext = args.compiler:_library_extension(kind) for i, f in ipairs(files) do if tostring(f:path()):ends_with(ext) then build:debug("Select", f, "(ends with '" .. ext .."')") table.append(filtered, f) else build:debug("Ignore", f, "(do not end with '" .. ext .."')") end end local function arg(name, default) local res = args[component .. '_' .. name] if res == nil then return default end return res end local abi_flags = { threading = arg('threading', args.compiler.threading), static_runtime = arg('static_runtime', args.compiler.runtime == 'static'), debug_runtime = arg('debug_runtime', args.compiler.debug_runtime), debug = arg('debug', args.compiler.debug), } local files, selected, unknown = filtered, {}, {} for _, f in ipairs(files) do -- Boost library files are as follow: -- (lib)?boost_<COMPONENT>(-<FLAGS>)?.(lib|a|so)(.<VERSION>)? local flags = tostring(f:path():filename()):match("-[^.]*") local parts = {} if flags ~= nil then parts = flags:split('-') end local check = nil for i, part in ipairs(parts) do if check == false then break end if part == "mt" then check = abi_flags[threading] elseif part:starts_with('vc') then -- TODO: Check against toolset elseif part:match("%d+_%d+_%d+") then -- TODO: Check the version elseif part:match("^s?g?d?p?n?$") then local file_abi_flags = { static_runtime = part:find('s') ~= nil, debug_runtime = part:find('g') ~= nil, debug = part:find('d') ~= nil, stlport = part:find('p') ~= nil, native_iostreams = part:find('n') ~= nil, } build:debug("Found abi flags of", f, (function() local res = "" for k, v in pairs(file_abi_flags) do res = res .. ' ' .. k .. '=' .. tostring(v); end end)()) for k, v in pairs(abi_flags) do if k ~= 'threading' and v ~= file_abi_flags[k] then build:debug("Ignore", f, "(The", k, "abi flag", (v and "is not" or "is"), " present)") check = false break else check = true end end else build:error("Unknown boost library name part '" .. part .. "'") end end if check == true then table.append(selected, f) elseif check == nil then table.append(unknown, f) end end if #selected > 0 then files = selected elseif #unknown > 0 then files = unknown else build:error("Couldn't find any library file for Boost component '" .. component .. "' in:", table.tostring(files)) end if #files > 1 then build:error("Too many file selected for Boost component '" .. component .. "':", table.tostring(files)) end local defines = default_component_defines(component, kind, threading) table.extend(defines, args[component .. '_defines'] or args.defines or {}) build:debug("Boost component '" .. component .. "' defines:", table.tostring(defines)) table.append(res, Library:new{ name = "Boost." .. component, include_directories = { boost_include_dir }, files = files, defines = defines, }) end return res end return M
lang.cxx.libraries.boost: Fix ABI flag checking.
lang.cxx.libraries.boost: Fix ABI flag checking.
Lua
bsd-3-clause
hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure
5d7a6efa13021da59a370bb011f4caf494b35da3
xmake/actions/create/main.lua
xmake/actions/create/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.project") import("core.project.template") -- get the builtin variables function _get_builtinvars(tempinst, targetname) return {TARGETNAME = targetname, FAQ = function() return io.readfile(path.join(os.programdir(), "scripts", "faq.lua")) end} end -- create project from template function _create_project(language, templateid, targetname) -- check the language assert(language, "no language!") -- check the template id assert(templateid, "no template id!") -- load all templates for the given language local templates = template.templates(language) -- TODO: deprecated -- in order to be compatible with the old version template local templates_new = { quickapp_qt = "qt.quickapp", widgetapp_qt = "qt.widgetapp", console_qt = "qt.console", static_qt = "qt.static", shared_qt = "qt.shared", console_tbox = "tbox.console", static_tbox = "tbox.static", shared_tbox = "tbox.shared"} if templates_new[templateid] then cprint("${yellow}deprecated: please uses template(%s) instead of template(%s)!", templates_new[templateid], templateid) templateid = templates_new[templateid] end -- get the given template instance local tempinst = nil if templates then for _, t in ipairs(templates) do if t:name() == templateid then tempinst = t break end end end assert(tempinst and tempinst:scriptdir(), "invalid template id: %s!", templateid) -- get project directory local projectdir = path.absolute(option.get("project") or path.join(os.curdir(), targetname)) -- ensure the project directory if not os.isdir(projectdir) then os.mkdir(projectdir) end -- enter the project directory os.cd(projectdir) -- ensure the project directory is empty if #os.filedirs('./*') ~= 0 then raise("project directory (${underline}%s${reset}) is not empty!", path.relative(projectdir, os.workingdir())) end -- create project local filedirs = {} local sourcedir = path.join(tempinst:scriptdir(), "project") if os.isdir(sourcedir) then for _, filedir in ipairs(os.filedirs(path.join(sourcedir, "*"))) do os.cp(filedir, projectdir) table.insert(filedirs, path.relative(filedir, sourcedir)) end os.cp(path.join(os.programdir(), "scripts", "gitignore"), path.join(projectdir, ".gitignore")) table.insert(filedirs, ".gitignore") else raise("template(%s): project not found!", templateid) end -- get the builtin variables local builtinvars = _get_builtinvars(tempinst, targetname) -- replace all variables for _, configfile in ipairs(tempinst:get("configfiles")) do local pattern = "%${(.-)}" io.gsub(configfile, "(" .. pattern .. ")", function(_, variable) variable = variable:trim() local value = builtinvars[variable] return type(value) == "function" and value() or value end) end -- do after_create local after_create = tempinst:get("create_after") if after_create then after_create(tempinst, {targetname = targetname}) end -- trace for _, filedir in ipairs(filedirs) do if os.isdir(filedir) then for _, file in ipairs(os.files(path.join(filedir, "**"))) do cprint(" ${green}[+]: ${clear}%s", file) end else cprint(" ${green}[+]: ${clear}%s", filedir) end end end -- main function main() -- enter the original working directory, because the default directory is in the project directory os.cd(os.workingdir()) -- the target name local targetname = option.get("target") or path.basename(project.directory()) or "demo" -- trace cprint("${bright}create %s ...", targetname) -- create project from template _create_project(option.get("language"), option.get("template"), targetname) -- trace cprint("${bright}create ok!") end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.project") import("core.project.template") -- get the builtin variables function _get_builtinvars(tempinst, targetname) return {TARGETNAME = targetname, FAQ = function() return io.readfile(path.join(os.programdir(), "scripts", "faq.lua")) end} end -- create project from template function _create_project(language, templateid, targetname) -- check the language assert(language, "no language!") -- check the template id assert(templateid, "no template id!") -- load all templates for the given language local templates = template.templates(language) -- TODO: deprecated -- in order to be compatible with the old version template local templates_new = { quickapp_qt = "qt.quickapp", widgetapp_qt = "qt.widgetapp", console_qt = "qt.console", static_qt = "qt.static", shared_qt = "qt.shared", console_tbox = "tbox.console", static_tbox = "tbox.static", shared_tbox = "tbox.shared"} if templates_new[templateid] then cprint("${yellow}deprecated: please uses template(%s) instead of template(%s)!", templates_new[templateid], templateid) templateid = templates_new[templateid] end -- get the given template instance local tempinst = nil if templates then for _, t in ipairs(templates) do if t:name() == templateid then tempinst = t break end end end assert(tempinst and tempinst:scriptdir(), "invalid template id: %s!", templateid) -- get project directory local projectdir = path.absolute(option.get("project") or path.join(os.curdir(), targetname)) if not os.isdir(projectdir) then -- make the project directory if not exists os.mkdir(projectdir) elseif not os.emptydir(projectdir) then -- otherwise, check whether it is empty raise("project directory (${underline}%s${reset}) is not empty!", path.relative(projectdir, os.workingdir())) end -- enter the project directory os.cd(projectdir) -- create project local filedirs = {} local sourcedir = path.join(tempinst:scriptdir(), "project") if os.isdir(sourcedir) then for _, filedir in ipairs(os.filedirs(path.join(sourcedir, "*"))) do os.cp(filedir, projectdir) table.insert(filedirs, path.relative(filedir, sourcedir)) end os.cp(path.join(os.programdir(), "scripts", "gitignore"), path.join(projectdir, ".gitignore")) table.insert(filedirs, ".gitignore") else raise("template(%s): project not found!", templateid) end -- get the builtin variables local builtinvars = _get_builtinvars(tempinst, targetname) -- replace all variables for _, configfile in ipairs(tempinst:get("configfiles")) do local pattern = "%${(.-)}" io.gsub(configfile, "(" .. pattern .. ")", function(_, variable) variable = variable:trim() local value = builtinvars[variable] return type(value) == "function" and value() or value end) end -- do after_create local after_create = tempinst:get("create_after") if after_create then after_create(tempinst, {targetname = targetname}) end -- trace for _, filedir in ipairs(filedirs) do if os.isdir(filedir) then for _, file in ipairs(os.files(path.join(filedir, "**"))) do cprint(" ${green}[+]: ${clear}%s", file) end else cprint(" ${green}[+]: ${clear}%s", filedir) end end end -- main function main() -- enter the original working directory, because the default directory is in the project directory os.cd(os.workingdir()) -- the target name local targetname = option.get("target") or path.basename(project.directory()) or "demo" -- trace cprint("${bright}create %s ...", targetname) -- create project from template _create_project(option.get("language"), option.get("template"), targetname) -- trace cprint("${bright}create ok!") end
fix check
fix check
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
d1f5784580a2045eef143c94e6f8d14087652e2f
trovebox.lua
trovebox.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, item_value) then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "site" then if string.match(url, "%?") then newurl = string.match(url, "(https://[^%?]+)%?") check(newurl) end if string.match(url, item_value.."%.trovebox%.com") and not string.match(url, %.jpg) then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "\/") then newnewurl = string.gsub(newurl, "\/", "/") check(newnewurl) elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then check(newurl) end end for newurl2 in string.gmatch(html, '"(%?[^"]+)"') then newurl1 = string.match(url, "(https?://[^%?]+)%?") newurl = newurl1..newurl2 check(newurl) end for newurl2 in string.gmatch(html, "(/[^"]+)") do if not string.match(newurl2, "%%") then newurl1 = string.match(url, "(https?://[^/]+)/") newurl = newurl1..newurl2 check(newurl) end end if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])") for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do newurl = string.gsub(url, "/p/"..photoid, "/p/"..newphotoid) check(newurl) end end if string.match(url, "%.trovebox%.com/albums/") then for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do newurl = string.gsub(url, "/albums/", newalbum) check(newurl) end end if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])") for photoid in string.gmatch(html, '"id":"[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]"') newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc check(newurl) check(newurl0) check(newurl1) check(newurl2) check(newurl3) check(newurl4) end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, item_value) then return verdict elseif html == 0 then return verdict else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) then table.insert(urls, { url=url }) addedtolist[url] = true end end if item_type == "site" then if string.match(url, "%?") then newurl = string.match(url, "(https://[^%?]+)%?") check(newurl) end if string.match(url, item_value.."%.trovebox%.com") and not string.match(url, "%.jpg") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if string.match(newurl, "\/") then newnewurl = string.gsub(newurl, "\/", "/") check(newnewurl) elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then check(newurl) end end for newurl2 in string.gmatch(html, '"(%?[^"]+)"') then newurl1 = string.match(url, "(https?://[^%?]+)%?") newurl = newurl1..newurl2 check(newurl) end for newurl2 in string.gmatch(html, '"(/[^"]+)"') do if not string.match(newurl2, "%%") then newurl1 = string.match(url, "(https?://[^/]+)/") newurl = newurl1..newurl2 check(newurl) end end if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])") for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do newurl = string.gsub(url, "/p/"..photoid, "/p/"..newphotoid) check(newurl) end end if string.match(url, "%.trovebox%.com/albums/") then for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do https://opensourceecology.trovebox.com/photos/album-23/list newurl = string.gsub(url, "/albums/", "/photos/album%-"..newalbum.."/list") check(newurl) end end if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])") for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc" newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc" newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc" newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc" check(newurl) check(newurl0) check(newurl1) check(newurl2) check(newurl3) check(newurl4) end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url["url"], "https://") then local newurl = string.gsub(url["url"], "https://", "http://") downloaded[newurl] = true else downloaded[url["url"]] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
trovebox.lua: fixes
trovebox.lua: fixes
Lua
unlicense
ArchiveTeam/trovebox-grab,ArchiveTeam/trovebox-grab
e03294e46384a22e5f3e0ba5e815e2c45cdf2a6f
src/application.lua
src/application.lua
local sensors = require("sensors") local dht_sensors = require("dht_sensors") local ds18b20_sensors = require("ds18b20_sensors") local actuators = require("actuators") local settings = require("settings") local sensorPut = {} local actuatorGet = {} local dni = wifi.sta.getmac():gsub("%:", "") local timeout = tmr.create() local sensorTimer = tmr.create() local sendTimer = tmr.create() timeout:register(10000, tmr.ALARM_SEMI, node.restart) -- initialize binary sensors for i, sensor in pairs(sensors) do print("Heap:", node.heap(), "Initializing sensor pin:", sensor.pin) gpio.mode(sensor.pin, gpio.INPUT, gpio.PULLUP) end -- initialize actuators for i, actuator in pairs(actuators) do table.insert(actuatorGet, actuator) end -- initialize DHT sensors if #dht_sensors > 0 then require("dht") local function readDht(pin) local status, temp, humi, temp_dec, humi_dec = dht.read(pin) if status == dht.OK then local temperature_string = temp .. "." .. math.abs(temp_dec) local humidity_string = humi .. "." .. humi_dec print("Heap:", node.heap(), "Temperature:", temperature_string, "Humidity:", humidity_string) table.insert(sensorPut, { pin = pin, temp = temperature_string, humi = humidity_string }) else print("Heap:", node.heap(), "DHT Status:", status) end end for i, sensor in pairs(dht_sensors) do local pollInterval = (sensor.poll_interval > 0 and sensor.poll_interval or 3) * 60 * 1000 print("Heap:", node.heap(), "Polling DHT on pin " .. sensor.pin .. " every " .. pollInterval .. "ms") tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() readDht(sensor.pin) end) readDht(sensor.pin) end end -- initialize ds18b20 temp sensors if #ds18b20_sensors > 0 then local function ds18b20Callback(pin) local callbackFn = function(i, rom, res, temp, temp_dec, par) local temperature_string = temp .. "." .. math.abs(temp_dec) print("Heap:", node.heap(), "Temperature:", temperature_string, "Resolution:", res) if (res >= 12) then table.insert(sensorPut, { pin = pin, temp = temperature_string, addr = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X", string.match(rom, "(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")) }) end end return callbackFn end for i, sensor in pairs(ds18b20_sensors) do local pollInterval = (sensor.poll_interval > 0 and sensor.poll_interval or 3) * 60 * 1000 print("Heap:", node.heap(), "Polling DS18b20 on pin " .. sensor.pin .. " every " .. pollInterval .. "ms") local callbackFn = ds18b20Callback(sensor.pin) ds18b20.setup(sensor.pin) ds18b20.setting({}, 12) tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() ds18b20.read(callbackFn, {}) end) ds18b20.read(callbackFn, {}) end end -- Poll every configured binary sensor and insert into the request queue when changed sensorTimer:alarm(200, tmr.ALARM_AUTO, function(t) for i, sensor in pairs(sensors) do if sensor.state ~= gpio.read(sensor.pin) then sensor.state = gpio.read(sensor.pin) table.insert(sensorPut, { pin = sensor.pin, state = sensor.state }) end end end) -- print HTTP status line local printHttpResponse = function(code, data) local a = { "Heap:", node.heap(), "HTTP Call:", code } for k, v in pairs(data) do table.insert(a, k) table.insert(a, v) end print(unpack(a)) end -- This loop makes the HTTP requests to the home automation service to get or update device state sendTimer:alarm(200, tmr.ALARM_AUTO, function(t) -- gets state of actuators if actuatorGet[1] then t:stop() local actuator = actuatorGet[1] timeout:start() http.get(table.concat({ settings.apiUrl, "/device/", dni, '?pin=', actuator.pin }), table.concat({ "Authorization: Bearer ", settings.token, "\r\nAccept: application/json\r\n" }), function(code, response) timeout:stop() local pin = tonumber(response:match('"pin":(%d)')) local state = tonumber(response:match('"state":(%d)')) printHttpResponse(code, {pin = pin, state = state}) gpio.mode(actuator.pin, gpio.OUTPUT) if pin == actuator.pin and code >= 200 and code < 300 and state then gpio.write(actuator.pin, state) else state = actuator.trigger == gpio.LOW and gpio.HIGH or gpio.LOW gpio.write(actuator.pin, state) end print("Heap:", node.heap(), "Initialized actuator Pin:", actuator.pin, "Trigger:", actuator.trigger, "Initial state:", state) table.remove(actuatorGet, 1) blinktimer:start() t:start() end) -- update state of sensors when needed elseif sensorPut[1] then t:stop() local sensor = sensorPut[1] timeout:start() http.put(table.concat({ settings.apiUrl, "/device/", dni }), table.concat({ "Authorization: Bearer ", settings.token, "\r\nAccept: application/json\r\nContent-Type: application/json\r\n" }), sjson.encode(sensor), function(code) timeout:stop() printHttpResponse(code, sensor) -- check for success and retry if necessary if code >= 200 and code < 300 then table.remove(sensorPut, 1) else -- retry up to 10 times then reboot as a failsafe local retry = sensor.retry or 0 if retry == 10 then node.restart() end sensor.retry = retry + 1 sensorPut[1] = sensor end blinktimer:start() t:start() end) end collectgarbage() end) print("Heap:", node.heap(), "Endpoint:", settings.apiUrl)
local sensors = require("sensors") local dht_sensors = require("dht_sensors") local ds18b20_sensors = require("ds18b20_sensors") local actuators = require("actuators") local settings = require("settings") local sensorPut = {} local actuatorGet = {} local dni = wifi.sta.getmac():gsub("%:", "") local timeout = tmr.create() local sensorTimer = tmr.create() local sendTimer = tmr.create() timeout:register(10000, tmr.ALARM_SEMI, node.restart) -- initialize binary sensors for i, sensor in pairs(sensors) do print("Heap:", node.heap(), "Initializing sensor pin:", sensor.pin) gpio.mode(sensor.pin, gpio.INPUT, gpio.PULLUP) end -- initialize actuators for i, actuator in pairs(actuators) do table.insert(actuatorGet, actuator) end -- initialize DHT sensors if #dht_sensors > 0 then require("dht") local function readDht(pin) local status, temp, humi, temp_dec, humi_dec = dht.read(pin) if status == dht.OK then local temperature_string = temp .. "." .. math.abs(temp_dec) local humidity_string = humi .. "." .. humi_dec print("Heap:", node.heap(), "Temperature:", temperature_string, "Humidity:", humidity_string) table.insert(sensorPut, { pin = pin, temp = temperature_string, humi = humidity_string }) else print("Heap:", node.heap(), "DHT Status:", status) end end for i, sensor in pairs(dht_sensors) do local pollInterval = (sensor.poll_interval > 0 and sensor.poll_interval or 3) * 60 * 1000 print("Heap:", node.heap(), "Polling DHT on pin " .. sensor.pin .. " every " .. pollInterval .. "ms") tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() readDht(sensor.pin) end) readDht(sensor.pin) end end -- initialize ds18b20 temp sensors if #ds18b20_sensors > 0 then local function ds18b20Callback(pin) local callbackFn = function(i, rom, res, temp, temp_dec, par) local temperature_string = temp .. "." .. math.abs(temp_dec) print("Heap:", node.heap(), "Temperature:", temperature_string, "Resolution:", res) if (res >= 12) then table.insert(sensorPut, { pin = pin, temp = temperature_string, addr = string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X", string.match(rom, "(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)")) }) end end return callbackFn end for i, sensor in pairs(ds18b20_sensors) do local pollInterval = (sensor.poll_interval > 0 and sensor.poll_interval or 3) * 60 * 1000 print("Heap:", node.heap(), "Polling DS18b20 on pin " .. sensor.pin .. " every " .. pollInterval .. "ms") local callbackFn = ds18b20Callback(sensor.pin) ds18b20.setup(sensor.pin) ds18b20.setting({}, 12) tmr.create():alarm(pollInterval, tmr.ALARM_AUTO, function() ds18b20.read(callbackFn, {}) end) ds18b20.read(callbackFn, {}) end end -- Poll every configured binary sensor and insert into the request queue when changed sensorTimer:alarm(200, tmr.ALARM_AUTO, function(t) for i, sensor in pairs(sensors) do if sensor.state ~= gpio.read(sensor.pin) then sensor.state = gpio.read(sensor.pin) table.insert(sensorPut, { pin = sensor.pin, state = sensor.state }) end end end) -- print HTTP status line local printHttpResponse = function(code, data) print("printHttpResponse") local a = { "Heap:", node.heap(), "HTTP Call:", code } for k, v in pairs(data) do table.insert(a, k) table.insert(a, v) end print(unpack(a)) end -- This loop makes the HTTP requests to the home automation service to get or update device state sendTimer:alarm(200, tmr.ALARM_AUTO, function(t) -- gets state of actuators if actuatorGet[1] then t:stop() local actuator = actuatorGet[1] timeout:start() http.get(table.concat({ settings.apiUrl, "/device/", dni, '?pin=', actuator.pin }), table.concat({ "Authorization: Bearer ", settings.token, "\r\nAccept: application/json\r\n" }), function(code, response) timeout:stop() local pin, state if response then pin = tonumber(response:match('"pin":(%d)')) state = tonumber(response:match('"state":(%d)')) end printHttpResponse(code, {pin = pin, state = state}) gpio.mode(actuator.pin, gpio.OUTPUT) if pin == actuator.pin and code >= 200 and code < 300 and state then gpio.write(actuator.pin, state) else state = actuator.trigger == gpio.LOW and gpio.HIGH or gpio.LOW gpio.write(actuator.pin, state) end print("Heap:", node.heap(), "Initialized actuator Pin:", actuator.pin, "Trigger:", actuator.trigger, "Initial state:", state) table.remove(actuatorGet, 1) blinktimer:start() t:start() end) -- update state of sensors when needed elseif sensorPut[1] then t:stop() local sensor = sensorPut[1] timeout:start() http.put(table.concat({ settings.apiUrl, "/device/", dni }), table.concat({ "Authorization: Bearer ", settings.token, "\r\nAccept: application/json\r\nContent-Type: application/json\r\n" }), sjson.encode(sensor), function(code) timeout:stop() printHttpResponse(code, sensor) -- check for success and retry if necessary if code >= 200 and code < 300 then table.remove(sensorPut, 1) else -- retry up to 10 times then reboot as a failsafe local retry = sensor.retry or 0 if retry == 10 then node.restart() end sensor.retry = retry + 1 sensorPut[1] = sensor end blinktimer:start() t:start() end) end collectgarbage() end) print("Heap:", node.heap(), "Endpoint:", settings.apiUrl)
fix nil crash when remote server times out
fix nil crash when remote server times out
Lua
apache-2.0
konnected-io/konnected-security,konnected-io/konnected-security
6d941a6de170508f9e45189e2763936338c2b99b
lualib/skynet/db/redis.lua
lualib/skynet/db/redis.lua
local skynet = require "skynet" local socket = require "skynet.socket" local socketchannel = require "skynet.socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local function compose_message(cmd, msg) local t = type(msg) local lines = {} if t == "table" then lines[1] = count_cache[#msg+1] lines[2] = command_cache[cmd] local idx = 3 for _,v in ipairs(msg) do v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end if db then so:request(compose_message("SELECT", db), read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, overload = db_conf.overload, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, {v, ...}), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
local skynet = require "skynet" local socket = require "skynet.socket" local socketchannel = require "skynet.socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local function compose_message(cmd, msg) local t = type(msg) local lines = {} if t == "table" then local n = msg.n or #msg lines[1] = count_cache[n+1] lines[2] = command_cache[cmd] local idx = 3 for i = 1, n do v = msg[i] if v == nil then lines[idx] = "\r\n$-1" idx = idx + 1 else v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end if db then so:request(compose_message("SELECT", db), read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, overload = db_conf.overload, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", table.pack(key, value)), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
support nil in array, fix #1340
support nil in array, fix #1340
Lua
mit
pigparadise/skynet,icetoggle/skynet,hongling0/skynet,sanikoyes/skynet,xjdrew/skynet,sanikoyes/skynet,wangyi0226/skynet,wangyi0226/skynet,sanikoyes/skynet,pigparadise/skynet,korialuo/skynet,hongling0/skynet,cloudwu/skynet,xjdrew/skynet,korialuo/skynet,wangyi0226/skynet,cloudwu/skynet,cloudwu/skynet,pigparadise/skynet,icetoggle/skynet,hongling0/skynet,icetoggle/skynet,xjdrew/skynet,korialuo/skynet
28cc864c0ceadc303339ec323b5c61a6efc71c91
lib/iproc.lua
lib/iproc.lua
local gm = require 'graphicsmagick' local image = require 'image' local iproc = {} local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5) function iproc.crop_mod4(src) local w = src:size(3) % 4 local h = src:size(2) % 4 return iproc.crop(src, 0, 0, src:size(3) - w, src:size(2) - h) end function iproc.crop(src, w1, h1, w2, h2) local dest if src:dim() == 3 then dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]:clone() else -- dim == 2 dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]:clone() end return dest end function iproc.crop_nocopy(src, w1, h1, w2, h2) local dest if src:dim() == 3 then dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}] else -- dim == 2 dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}] end return dest end function iproc.byte2float(src) local conversion = false local dest = src if src:type() == "torch.ByteTensor" then conversion = true dest = src:float():div(255.0) end return dest, conversion end function iproc.float2byte(src) local conversion = false local dest = src if src:type() == "torch.FloatTensor" then conversion = true dest = (src + clip_eps8):mul(255.0) dest[torch.lt(dest, 0.0)] = 0 dest[torch.gt(dest, 255.0)] = 255.0 dest = dest:byte() end return dest, conversion end function iproc.scale(src, width, height, filter) local conversion src, conversion = iproc.byte2float(src) filter = filter or "Box" local im = gm.Image(src, "RGB", "DHW") im:size(math.ceil(width), math.ceil(height), filter) local dest = im:toTensor("float", "RGB", "DHW") if conversion then dest = iproc.float2byte(dest) end return dest end function iproc.scale_with_gamma22(src, width, height, filter) local conversion src, conversion = iproc.byte2float(src) filter = filter or "Box" local im = gm.Image(src, "RGB", "DHW") im:gammaCorrection(1.0 / 2.2): size(math.ceil(width), math.ceil(height), filter): gammaCorrection(2.2) local dest = im:toTensor("float", "RGB", "DHW") if conversion then dest = iproc.float2byte(dest) end return dest end function iproc.padding(img, w1, w2, h1, h2) local dst_height = img:size(2) + h1 + h2 local dst_width = img:size(3) + w1 + w2 local flow = torch.Tensor(2, dst_height, dst_width) flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width)) flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width)) flow[1]:add(-h1) flow[2]:add(-w1) return image.warp(img, flow, "simple", false, "clamp") end function iproc.white_noise(src, std, rgb_weights, gamma) gamma = gamma or 0.454545 local conversion src, conversion = iproc.byte2float(src) std = std or 0.01 local noise = torch.Tensor():resizeAs(src):normal(0, std) if rgb_weights then noise[1]:mul(rgb_weights[1]) noise[2]:mul(rgb_weights[2]) noise[3]:mul(rgb_weights[3]) end local dest if gamma ~= 0 then dest = src:clone():pow(gamma):add(noise):pow(1.0 / gamma) else dest = src + noise end if conversion then dest = iproc.float2byte(dest) end return dest end local function test_conversion() local a = torch.linspace(0, 255, 256):float():div(255.0) local b = iproc.float2byte(a) local c = iproc.byte2float(a) local d = torch.linspace(0, 255, 256) assert((a - c):abs():sum() == 0) assert((d:float() - b:float()):abs():sum() == 0) a = torch.FloatTensor({256.0, 255.0, 254.999}):div(255.0) b = iproc.float2byte(a) assert(b:float():sum() == 255.0 * 3) a = torch.FloatTensor({254.0, 254.499, 253.50001}):div(255.0) b = iproc.float2byte(a) print(b) assert(b:float():sum() == 254.0 * 3) end --test_conversion() return iproc
local gm = require 'graphicsmagick' local image = require 'image' local iproc = {} local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5) function iproc.crop_mod4(src) local w = src:size(3) % 4 local h = src:size(2) % 4 return iproc.crop(src, 0, 0, src:size(3) - w, src:size(2) - h) end function iproc.crop(src, w1, h1, w2, h2) local dest if src:dim() == 3 then dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]:clone() else -- dim == 2 dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]:clone() end return dest end function iproc.crop_nocopy(src, w1, h1, w2, h2) local dest if src:dim() == 3 then dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}] else -- dim == 2 dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}] end return dest end function iproc.byte2float(src) local conversion = false local dest = src if src:type() == "torch.ByteTensor" then conversion = true dest = src:float():div(255.0) end return dest, conversion end function iproc.float2byte(src) local conversion = false local dest = src if src:type() == "torch.FloatTensor" then conversion = true dest = (src + clip_eps8):mul(255.0) dest[torch.lt(dest, 0.0)] = 0 dest[torch.gt(dest, 255.0)] = 255.0 dest = dest:byte() end return dest, conversion end function iproc.scale(src, width, height, filter) local conversion src, conversion = iproc.byte2float(src) filter = filter or "Box" local im = gm.Image(src, "RGB", "DHW") im:size(math.ceil(width), math.ceil(height), filter) local dest = im:toTensor("float", "RGB", "DHW") if conversion then dest = iproc.float2byte(dest) end return dest end function iproc.scale_with_gamma22(src, width, height, filter) local conversion src, conversion = iproc.byte2float(src) filter = filter or "Box" local im = gm.Image(src, "RGB", "DHW") im:gammaCorrection(1.0 / 2.2): size(math.ceil(width), math.ceil(height), filter): gammaCorrection(2.2) local dest = im:toTensor("float", "RGB", "DHW") if conversion then dest = iproc.float2byte(dest) end return dest end function iproc.padding(img, w1, w2, h1, h2) local dst_height = img:size(2) + h1 + h2 local dst_width = img:size(3) + w1 + w2 local flow = torch.Tensor(2, dst_height, dst_width) flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width)) flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width)) flow[1]:add(-h1) flow[2]:add(-w1) return image.warp(img, flow, "simple", false, "clamp") end function iproc.white_noise(src, std, rgb_weights, gamma) gamma = gamma or 0.454545 local conversion src, conversion = iproc.byte2float(src) std = std or 0.01 local noise = torch.Tensor():resizeAs(src):normal(0, std) if rgb_weights then noise[1]:mul(rgb_weights[1]) noise[2]:mul(rgb_weights[2]) noise[3]:mul(rgb_weights[3]) end local dest if gamma ~= 0 then dest = src:clone():pow(gamma):add(noise) dest[torch.lt(dest, 0.0)] = 0.0 dest[torch.gt(dest, 1.0)] = 1.0 dest:pow(1.0 / gamma) else dest = src + noise end if conversion then dest = iproc.float2byte(dest) end return dest end local function test_conversion() local a = torch.linspace(0, 255, 256):float():div(255.0) local b = iproc.float2byte(a) local c = iproc.byte2float(a) local d = torch.linspace(0, 255, 256) assert((a - c):abs():sum() == 0) assert((d:float() - b:float()):abs():sum() == 0) a = torch.FloatTensor({256.0, 255.0, 254.999}):div(255.0) b = iproc.float2byte(a) assert(b:float():sum() == 255.0 * 3) a = torch.FloatTensor({254.0, 254.499, 253.50001}):div(255.0) b = iproc.float2byte(a) print(b) assert(b:float():sum() == 254.0 * 3) end --test_conversion() return iproc
Fix NaN bug in iproc.white_noise
Fix NaN bug in iproc.white_noise
Lua
mit
higankanshi/waifu2x,Spitfire1900/upscaler,higankanshi/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,vitaliylag/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x
8234319570a091f2089a2278df320f6a39840c37
lua/rima/operators/sum.lua
lua/rima/operators/sum.lua
-- Copyright (c) 2009 Incremental IP Limited -- see license.txt for license information local ipairs, pairs = ipairs, pairs local object = require("rima.object") local expression = require("rima.expression") local add = require("rima.operators.add") local rima = rima module(...) -- Subscripts ------------------------------------------------------------------ local sum = object:new(_M, "sum") sum.precedence = 1 function rima.sum(sets, e) return expression:new(sum, sets, e) end function sum.construct(args) local sets = args[1] if not object.isa(sets, rima.iteration.set_list) then sets = rima.iteration.set_list:new(sets) end return { sets, args[2] } end -- String Representation ------------------------------------------------------- function sum.__repr(args, format) local sets, e = args[1], args[2] return "sum({"..expression.concat(sets, format).."}, "..rima.repr(e, format)..")" end -- Evaluation ------------------------------------------------------------------ function sum.__eval(args, S, eval) local sets, e = args[1], args[2] local defined_terms, undefined_terms = {}, {} -- Iterate through all the elements of the sets, collecting defined and -- undefined terms for S2, undefined in sets:iterate(S) do local z = eval(e, S2) if undefined[1] then -- Undefined terms are stored in groups based on the undefined sum -- indices (so we can group them back into sums over the same indices) local name = rima.concat(undefined, ",", rima.repr) local terms local udn = undefined_terms[name] if not udn then terms = {} undefined_terms[name] = { iterators=undefined, terms=terms } else terms = udn.terms end terms[#terms+1] = { 1, z } else -- Defined terms are just stored in a list defined_terms[#defined_terms+1] = { 1, z } end end local total_terms = {} -- Run through all the undefined terms, rebuilding the sums for n, t in pairs(undefined_terms) do local z if #t.terms > 1 then z = expression:new_table(add, t.terms) else z = t.terms[1][2] end total_terms[#total_terms+1] = {1, expression:new(sum, t.iterators, z) } end -- Add the defined terms onto the end for _, t in ipairs(defined_terms) do total_terms[#total_terms+1] = t end if #total_terms == 1 then return total_terms[1][2] else return eval(expression:new_table(add, total_terms), S) end end -- EOF -------------------------------------------------------------------------
-- Copyright (c) 2009 Incremental IP Limited -- see license.txt for license information local ipairs, pairs = ipairs, pairs local object = require("rima.object") local expression = require("rima.expression") local add = require("rima.operators.add") local rima = rima module(...) -- Subscripts ------------------------------------------------------------------ local sum = object:new(_M, "sum") sum.precedence = 1 function rima.sum(sets, e) if e then return expression:new(sum, sets, e) else return function(e2) return expression:new(sum, sets, e2) end end end function sum.construct(args) local sets = args[1] if not object.isa(sets, rima.iteration.set_list) then sets = rima.iteration.set_list:new(sets) end return { sets, args[2] } end -- String Representation ------------------------------------------------------- function sum.__repr(args, format) local sets, e = args[1], args[2] if format and format.dump then return "sum({"..expression.concat(sets, format).."}, "..rima.repr(e, format)..")" else return "sum{"..expression.concat(sets, format).."}("..rima.repr(e, format)..")" end end -- Evaluation ------------------------------------------------------------------ function sum.__eval(args, S, eval) local sets, e = args[1], args[2] local defined_terms, undefined_terms = {}, {} -- Iterate through all the elements of the sets, collecting defined and -- undefined terms for S2, undefined in sets:iterate(S) do local z = eval(e, S2) if undefined[1] then -- Undefined terms are stored in groups based on the undefined sum -- indices (so we can group them back into sums over the same indices) local name = rima.concat(undefined, ",", rima.repr) local terms local udn = undefined_terms[name] if not udn then terms = {} undefined_terms[name] = { iterators=undefined, terms=terms } else terms = udn.terms end terms[#terms+1] = { 1, z } else -- Defined terms are just stored in a list defined_terms[#defined_terms+1] = { 1, z } end end local total_terms = {} -- Run through all the undefined terms, rebuilding the sums for n, t in pairs(undefined_terms) do local z if #t.terms > 1 then z = expression:new_table(add, t.terms) else z = t.terms[1][2] end total_terms[#total_terms+1] = {1, expression:new(sum, t.iterators, z) } end -- Add the defined terms onto the end for _, t in ipairs(defined_terms) do total_terms[#total_terms+1] = t end if #total_terms == 1 then return total_terms[1][2] else return eval(expression:new_table(add, total_terms), S) end end -- EOF -------------------------------------------------------------------------
rima: sum has a new format: sum{X}(X + 2). Hamish likes it better. Some tests fail, but they'll get fixed when all the notation changes are done.
rima: sum has a new format: sum{X}(X + 2). Hamish likes it better. Some tests fail, but they'll get fixed when all the notation changes are done.
Lua
mit
geoffleyland/rima,geoffleyland/rima,geoffleyland/rima
49ef1b249781d84a70f87b09b65f39914feb2c04
src_trunk/resources/realism-system/s_enginebreak.lua
src_trunk/resources/realism-system/s_enginebreak.lua
function engineBreak() local health = getElementHealth(source) local driver = getVehicleController(source) if (driver) and (health<=400) then local rand = math.random(1, 10) if (rand==1) then -- 10% chance setVehicleEngineState(source, false) setElementData(source, "engine", 0) exports.global:sendLocalDoAction(driver, "The engine breaks down.") end end end addEventHandler("onVehicleDamage", getRootElement(), engineBreak)
function engineBreak() local health = getElementHealth(source) local driver = getVehicleController(source) if (driver) then if (health<=400) local rand = math.random(1, 5) if (rand==1) then -- 20% chance setVehicleEngineState(source, false) setElementData(source, "engine", 0) exports.global:sendLocalDoAction(driver, "The engine stalls due to damage.") end elseif (health<=300) then local rand = math.random(1, 2) if (rand==1) then -- 50% chance setVehicleEngineState(source, false) setElementData(source, "engine", 0) exports.global:sendLocalDoAction(driver, "The engine breaks down.") end end end end addEventHandler("onVehicleDamage", getRootElement(), engineBreak)
Fix for 327
Fix for 327 git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@119 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
026441ccc107d8754abb3971fc89e1784ccb1b11
src/program/top/top.lua
src/program/top/top.lua
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local shm = require("core.shm") local counter = require("core.counter") local S = require("syscall") local usage = require("program.top.README_inc") local long_opts = { help = "h" } function clearterm () io.write('\027[2J') end function run (args) local opt = {} function opt.h (arg) print(usage) main.exit(1) end args = lib.dogetopt(args, opt, "h", long_opts) if #args > 1 then print(usage) main.exit(1) end local target_pid = args[1] local instance_tree = "//"..(select_snabb_instance(target_pid)) local counters = open_counters(instance_tree) local configs = 0 local last_stats = nil while (true) do if configs < counter.read(counters.configs) then -- If a (new) config is loaded we (re)open the link counters. open_link_counters(counters, instance_tree) end local new_stats = get_stats(counters) if last_stats then clearterm() print_global_metrics(new_stats, last_stats) io.write("\n") print_link_metrics(new_stats, last_stats) io.flush() end last_stats = new_stats C.sleep(1) end end function select_snabb_instance (pid) local instances = shm.children("//") if pid then -- Try to use given pid for _, instance in ipairs(instances) do if instance == pid then return pid end end print("No such Snabb Switch instance: "..pid) elseif #instances == 2 then -- Two means one is us, so we pick the other. local own_pid = tostring(S.getpid()) if instances[1] == own_pid then return instances[2] else return instances[1] end elseif #instances == 1 then print("No Snabb Switch instance found.") else print("Multple Snabb Switch instances found. Select one.") end os.exit(1) end function open_counters (tree) local counters = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do counters[name] = counter.open(tree.."/engine/"..name, 'readonly') end counters.links = {} -- These will be populated on demand. return counters end function open_link_counters (counters, tree) -- Unmap and clear existing link counters. for _, link in ipairs(counters.links) do for _, counter in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"}) do shm.unmap(counters.links[counter]) end end counters.links = {} -- Open current link counters. for _, linkspec in ipairs(shm.children(tree.."/links")) do counters.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"}) do counters.links[linkspec][name] = counter.open(tree.."/counters/"..linkspec.."/"..name, 'readonly') end end end function get_stats (counters) local new_stats = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do new_stats[name] = counter.read(counters[name]) end new_stats.links = {} for linkspec, link in pairs(counters.links) do new_stats.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop" }) do new_stats.links[linkspec][name] = counter.read(link[name]) end end return new_stats end local global_metrics_row = {15, 15, 15} function print_global_metrics (new_stats, last_stats) local frees = tonumber(new_stats.frees - last_stats.frees) local bytes = tonumber(new_stats.freebytes - last_stats.freebytes) local breaths = tonumber(new_stats.breaths - last_stats.breaths) print_row(global_metrics_row, {"Kfrees/s", "freeGbytes/s", "breaths/s"}) print_row(global_metrics_row, {float_s(frees / 1000), float_s(bytes / (1000^3)), tostring(breaths)}) end local link_metrics_row = {31, 7, 7, 7, 7, 7} function print_link_metrics (new_stats, last_stats) print_row(link_metrics_row, {"Links (rx/tx/txdrop in Mpps)", "rx", "tx", "rxGb", "txGb", "txdrop"}) for linkspec, link in pairs(new_stats.links) do if last_stats.links[linkspec] then local rx = tonumber(new_stats.links[linkspec].rxpackets - last_stats.links[linkspec].rxpackets) local tx = tonumber(new_stats.links[linkspec].txpackets - last_stats.links[linkspec].txpackets) local rxbytes = tonumber(new_stats.links[linkspec].rxbytes - last_stats.links[linkspec].rxbytes) local txbytes = tonumber(new_stats.links[linkspec].txbytes - last_stats.links[linkspec].txbytes) local drop = tonumber(new_stats.links[linkspec].txdrop - last_stats.links[linkspec].txdrop) print_row(link_metrics_row, {linkspec, float_s(rx / 1e6), float_s(tx / 1e6), float_s(rxbytes / (1000^3)), float_s(txbytes / (1000^3)), float_s(drop / 1e6)}) end end end function pad_str (s, n) local padding = math.max(n - s:len(), 0) return ("%s%s"):format(s:sub(1, n), (" "):rep(padding)) end function print_row (spec, args) for i, s in ipairs(args) do io.write((" %s"):format(pad_str(s, spec[i]))) end io.write("\n") end function float_s (n) return ("%.2f"):format(n) end
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local shm = require("core.shm") local counter = require("core.counter") local S = require("syscall") local usage = require("program.top.README_inc") local long_opts = { help = "h" } function clearterm () io.write('\027[2J') end function run (args) local opt = {} function opt.h (arg) print(usage) main.exit(1) end args = lib.dogetopt(args, opt, "h", long_opts) if #args > 1 then print(usage) main.exit(1) end local target_pid = args[1] local instance_tree = "//"..(select_snabb_instance(target_pid)) local counters = open_counters(instance_tree) local configs = 0 local last_stats = nil while (true) do if configs < counter.read(counters.configs) then -- If a (new) config is loaded we (re)open the link counters. open_link_counters(counters, instance_tree) end local new_stats = get_stats(counters) if last_stats then clearterm() print_global_metrics(new_stats, last_stats) io.write("\n") print_link_metrics(new_stats, last_stats) io.flush() end last_stats = new_stats C.sleep(1) end end function select_snabb_instance (pid) local instances = shm.children("//") if pid then -- Try to use given pid for _, instance in ipairs(instances) do if instance == pid then return pid end end print("No such Snabb Switch instance: "..pid) elseif #instances == 2 then -- Two means one is us, so we pick the other. local own_pid = tostring(S.getpid()) if instances[1] == own_pid then return instances[2] else return instances[1] end elseif #instances == 1 then print("No Snabb Switch instance found.") else print("Multple Snabb Switch instances found. Select one.") end os.exit(1) end function open_counters (tree) local counters = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do counters[name] = counter.open(tree.."/engine/"..name, 'readonly') end counters.links = {} -- These will be populated on demand. return counters end function open_link_counters (counters, tree) -- Unmap and clear existing link counters. for linkspec, _ in pairs(counters.links) do for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"}) do counter.delete(tree.."/counters/"..linkspec.."/"..name) end end counters.links = {} -- Open current link counters. for _, linkspec in ipairs(shm.children(tree.."/links")) do counters.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"}) do counters.links[linkspec][name] = counter.open(tree.."/counters/"..linkspec.."/"..name, 'readonly') end end end function get_stats (counters) local new_stats = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do new_stats[name] = counter.read(counters[name]) end new_stats.links = {} for linkspec, link in pairs(counters.links) do new_stats.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop" }) do new_stats.links[linkspec][name] = counter.read(link[name]) end end return new_stats end local global_metrics_row = {15, 15, 15} function print_global_metrics (new_stats, last_stats) local frees = tonumber(new_stats.frees - last_stats.frees) local bytes = tonumber(new_stats.freebytes - last_stats.freebytes) local breaths = tonumber(new_stats.breaths - last_stats.breaths) print_row(global_metrics_row, {"Kfrees/s", "freeGbytes/s", "breaths/s"}) print_row(global_metrics_row, {float_s(frees / 1000), float_s(bytes / (1000^3)), tostring(breaths)}) end local link_metrics_row = {31, 7, 7, 7, 7, 7} function print_link_metrics (new_stats, last_stats) print_row(link_metrics_row, {"Links (rx/tx/txdrop in Mpps)", "rx", "tx", "rxGb", "txGb", "txdrop"}) for linkspec, link in pairs(new_stats.links) do if last_stats.links[linkspec] then local rx = tonumber(new_stats.links[linkspec].rxpackets - last_stats.links[linkspec].rxpackets) local tx = tonumber(new_stats.links[linkspec].txpackets - last_stats.links[linkspec].txpackets) local rxbytes = tonumber(new_stats.links[linkspec].rxbytes - last_stats.links[linkspec].rxbytes) local txbytes = tonumber(new_stats.links[linkspec].txbytes - last_stats.links[linkspec].txbytes) local drop = tonumber(new_stats.links[linkspec].txdrop - last_stats.links[linkspec].txdrop) print_row(link_metrics_row, {linkspec, float_s(rx / 1e6), float_s(tx / 1e6), float_s(rxbytes / (1000^3)), float_s(txbytes / (1000^3)), float_s(drop / 1e6)}) end end end function pad_str (s, n) local padding = math.max(n - s:len(), 0) return ("%s%s"):format(s:sub(1, n), (" "):rep(padding)) end function print_row (spec, args) for i, s in ipairs(args) do io.write((" %s"):format(pad_str(s, spec[i]))) end io.write("\n") end function float_s (n) return ("%.2f"):format(n) end
[top] Fix bug in link counter deallocation.
[top] Fix bug in link counter deallocation.
Lua
apache-2.0
plajjan/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,dpino/snabb,Igalia/snabb,hb9cwp/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,SnabbCo/snabbswitch,mixflowtech/logsensor,Igalia/snabbswitch,SnabbCo/snabbswitch,dwdm/snabbswitch,snabbnfv-goodies/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,wingo/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,wingo/snabb,aperezdc/snabbswitch,kbara/snabb,kellabyte/snabbswitch,kbara/snabb,dpino/snabb,alexandergall/snabbswitch,snabbco/snabb,pavel-odintsov/snabbswitch,kellabyte/snabbswitch,wingo/snabb,justincormack/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,andywingo/snabbswitch,hb9cwp/snabbswitch,fhanik/snabbswitch,eugeneia/snabb,heryii/snabb,kbara/snabb,hb9cwp/snabbswitch,wingo/snabb,Igalia/snabbswitch,aperezdc/snabbswitch,dpino/snabbswitch,justincormack/snabbswitch,snabbco/snabb,lukego/snabbswitch,plajjan/snabbswitch,dwdm/snabbswitch,kbara/snabb,SnabbCo/snabbswitch,wingo/snabb,heryii/snabb,wingo/snabb,mixflowtech/logsensor,snabbco/snabb,alexandergall/snabbswitch,wingo/snabbswitch,justincormack/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,pirate/snabbswitch,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,pirate/snabbswitch,pirate/snabbswitch,wingo/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,dpino/snabbswitch,xdel/snabbswitch,kbara/snabb,snabbnfv-goodies/snabbswitch,justincormack/snabbswitch,snabbco/snabb,lukego/snabb,Igalia/snabb,heryii/snabb,lukego/snabbswitch,Igalia/snabb,kellabyte/snabbswitch,fhanik/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,Igalia/snabb,lukego/snabb,heryii/snabb,kbara/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,lukego/snabb,dwdm/snabbswitch,snabbco/snabb,dpino/snabb,heryii/snabb,aperezdc/snabbswitch,dpino/snabb,lukego/snabb,eugeneia/snabbswitch,dpino/snabb,eugeneia/snabb,wingo/snabbswitch,andywingo/snabbswitch,Igalia/snabbswitch,wingo/snabb,dpino/snabb,lukego/snabbswitch,hb9cwp/snabbswitch,dpino/snabb,dpino/snabbswitch,plajjan/snabbswitch,mixflowtech/logsensor,dpino/snabbswitch,andywingo/snabbswitch,snabbco/snabb,plajjan/snabbswitch,andywingo/snabbswitch,xdel/snabbswitch,Igalia/snabb,lukego/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,fhanik/snabbswitch,xdel/snabbswitch,eugeneia/snabb,Igalia/snabb
f008ec70f982113b71ee00fbda2ee24868e1c360
applications/luci-samba/luasrc/model/cbi/samba.lua
applications/luci-samba/luasrc/model/cbi/samba.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("samba") s = m:section(TypedSection, "samba", "Samba") s.anonymous = true s:option(Value, "name") s:option(Value, "description") s:option(Value, "workgroup") s:option(Flag, "homes") s = m:section(TypedSection, "sambashare") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "name", translate("name")) s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab") s:option(Value, "users").rmempty = true ro = s:option(Flag, "read_only") ro.enabled = "yes" ro.disabled = "no" go = s:option(Flag, "guest_ok") go.enabled = "yes" go.disabled = "no" cm = s:option(Value, "create_mask") cm.rmempty = true cm.size = 4 dm = s:option(Value, "dir_mask") dm.rmempty = true dm.size = 4 return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("samba") s = m:section(TypedSection, "samba", "Samba") s.anonymous = true s:option(Value, "name") s:option(Value, "description") s:option(Value, "workgroup") s:option(Flag, "homes") s = m:section(TypedSection, "sambashare") s.anonymous = true s.addremove = true s.template = "cbi/tblsection" s:option(Value, "name", translate("name")) s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab") s:option(Value, "users").rmempty = true ro = s:option(Flag, "read_only") ro.rmempty = false ro.enabled = "yes" ro.disabled = "no" go = s:option(Flag, "guest_ok") go.rmempty = false go.enabled = "yes" go.disabled = "no" cm = s:option(Value, "create_mask") cm.rmempty = true cm.size = 4 dm = s:option(Value, "dir_mask") dm.rmempty = true dm.size = 4 return m
Fix samba "read only" and "guest ok" settings not applied correctly.
Fix samba "read only" and "guest ok" settings not applied correctly.
Lua
apache-2.0
lbthomsen/openwrt-luci,florian-shellfire/luci,forward619/luci,Wedmer/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,RuiChen1113/luci,palmettos/cnLuCI,ff94315/luci-1,Noltari/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,MinFu/luci,palmettos/cnLuCI,thess/OpenWrt-luci,joaofvieira/luci,cshore-firmware/openwrt-luci,tcatm/luci,ollie27/openwrt_luci,bright-things/ionic-luci,joaofvieira/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,981213/luci-1,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,lcf258/openwrtcn,urueedi/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,openwrt-es/openwrt-luci,maxrio/luci981213,bittorf/luci,bright-things/ionic-luci,wongsyrone/luci-1,MinFu/luci,david-xiao/luci,opentechinstitute/luci,artynet/luci,aa65535/luci,dismantl/luci-0.12,cshore/luci,jorgifumi/luci,nmav/luci,aa65535/luci,kuoruan/lede-luci,florian-shellfire/luci,lcf258/openwrtcn,kuoruan/luci,florian-shellfire/luci,nmav/luci,openwrt/luci,joaofvieira/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,forward619/luci,Sakura-Winkey/LuCI,deepak78/new-luci,artynet/luci,Kyklas/luci-proto-hso,kuoruan/luci,aa65535/luci,teslamint/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,ollie27/openwrt_luci,mumuqz/luci,kuoruan/lede-luci,schidler/ionic-luci,urueedi/luci,maxrio/luci981213,urueedi/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,nmav/luci,981213/luci-1,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,jlopenwrtluci/luci,Wedmer/luci,florian-shellfire/luci,dismantl/luci-0.12,tcatm/luci,jorgifumi/luci,nwf/openwrt-luci,palmettos/cnLuCI,bittorf/luci,dwmw2/luci,keyidadi/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,nmav/luci,lcf258/openwrtcn,obsy/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,Noltari/luci,maxrio/luci981213,cshore/luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,bittorf/luci,palmettos/test,cappiewu/luci,schidler/ionic-luci,harveyhu2012/luci,fkooman/luci,cshore/luci,dwmw2/luci,bright-things/ionic-luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,teslamint/luci,opentechinstitute/luci,tcatm/luci,kuoruan/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,joaofvieira/luci,cshore-firmware/openwrt-luci,dwmw2/luci,981213/luci-1,remakeelectric/luci,kuoruan/luci,oneru/luci,artynet/luci,Sakura-Winkey/LuCI,palmettos/test,jchuang1977/luci-1,sujeet14108/luci,bittorf/luci,slayerrensky/luci,thess/OpenWrt-luci,MinFu/luci,Wedmer/luci,marcel-sch/luci,slayerrensky/luci,aa65535/luci,male-puppies/luci,sujeet14108/luci,daofeng2015/luci,chris5560/openwrt-luci,RuiChen1113/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,slayerrensky/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,oyido/luci,hnyman/luci,zhaoxx063/luci,tcatm/luci,cshore-firmware/openwrt-luci,thesabbir/luci,teslamint/luci,MinFu/luci,981213/luci-1,daofeng2015/luci,tcatm/luci,fkooman/luci,jlopenwrtluci/luci,oneru/luci,maxrio/luci981213,mumuqz/luci,jchuang1977/luci-1,artynet/luci,NeoRaider/luci,981213/luci-1,thesabbir/luci,kuoruan/lede-luci,fkooman/luci,male-puppies/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,LuttyYang/luci,lcf258/openwrtcn,NeoRaider/luci,artynet/luci,remakeelectric/luci,Hostle/luci,artynet/luci,fkooman/luci,teslamint/luci,mumuqz/luci,ff94315/luci-1,teslamint/luci,harveyhu2012/luci,thess/OpenWrt-luci,keyidadi/luci,nmav/luci,taiha/luci,nmav/luci,tcatm/luci,ff94315/luci-1,deepak78/new-luci,hnyman/luci,remakeelectric/luci,cappiewu/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,sujeet14108/luci,fkooman/luci,oneru/luci,Hostle/luci,marcel-sch/luci,harveyhu2012/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,obsy/luci,chris5560/openwrt-luci,david-xiao/luci,aa65535/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,artynet/luci,tobiaswaldvogel/luci,cappiewu/luci,bittorf/luci,slayerrensky/luci,palmettos/cnLuCI,zhaoxx063/luci,chris5560/openwrt-luci,LuttyYang/luci,cshore/luci,remakeelectric/luci,dismantl/luci-0.12,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,david-xiao/luci,schidler/ionic-luci,cshore/luci,sujeet14108/luci,nwf/openwrt-luci,thesabbir/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,maxrio/luci981213,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,thesabbir/luci,david-xiao/luci,harveyhu2012/luci,bright-things/ionic-luci,deepak78/new-luci,maxrio/luci981213,Noltari/luci,opentechinstitute/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,RuiChen1113/luci,bittorf/luci,bright-things/ionic-luci,Hostle/luci,tobiaswaldvogel/luci,oneru/luci,oneru/luci,ff94315/luci-1,palmettos/test,hnyman/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,lcf258/openwrtcn,oyido/luci,Noltari/luci,artynet/luci,slayerrensky/luci,schidler/ionic-luci,cshore/luci,daofeng2015/luci,palmettos/test,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,mumuqz/luci,urueedi/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,palmettos/test,bright-things/ionic-luci,rogerpueyo/luci,nmav/luci,marcel-sch/luci,taiha/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,marcel-sch/luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,shangjiyu/luci-with-extra,mumuqz/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,marcel-sch/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,NeoRaider/luci,taiha/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,jorgifumi/luci,florian-shellfire/luci,NeoRaider/luci,oneru/luci,jlopenwrtluci/luci,palmettos/cnLuCI,LuttyYang/luci,palmettos/cnLuCI,cappiewu/luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,oyido/luci,oyido/luci,forward619/luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,deepak78/new-luci,bittorf/luci,hnyman/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,jchuang1977/luci-1,jchuang1977/luci-1,maxrio/luci981213,dwmw2/luci,male-puppies/luci,shangjiyu/luci-with-extra,NeoRaider/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,slayerrensky/luci,teslamint/luci,kuoruan/luci,zhaoxx063/luci,rogerpueyo/luci,Wedmer/luci,aa65535/luci,thesabbir/luci,schidler/ionic-luci,NeoRaider/luci,zhaoxx063/luci,LuttyYang/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,nwf/openwrt-luci,hnyman/luci,palmettos/test,slayerrensky/luci,openwrt/luci,lcf258/openwrtcn,Noltari/luci,remakeelectric/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,teslamint/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,kuoruan/lede-luci,thesabbir/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,cappiewu/luci,mumuqz/luci,rogerpueyo/luci,981213/luci-1,ollie27/openwrt_luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,kuoruan/lede-luci,Hostle/luci,kuoruan/luci,ollie27/openwrt_luci,981213/luci-1,taiha/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,hnyman/luci,joaofvieira/luci,Wedmer/luci,rogerpueyo/luci,taiha/luci,harveyhu2012/luci,keyidadi/luci,marcel-sch/luci,LuttyYang/luci,fkooman/luci,kuoruan/luci,opentechinstitute/luci,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,forward619/luci,thess/OpenWrt-luci,cshore/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,chris5560/openwrt-luci,forward619/luci,Kyklas/luci-proto-hso,tcatm/luci,tobiaswaldvogel/luci,taiha/luci,jorgifumi/luci,LuttyYang/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,nwf/openwrt-luci,openwrt/luci,jlopenwrtluci/luci,palmettos/cnLuCI,jchuang1977/luci-1,wongsyrone/luci-1,oyido/luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,florian-shellfire/luci,MinFu/luci,MinFu/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,jchuang1977/luci-1,david-xiao/luci,palmettos/cnLuCI,obsy/luci,oneru/luci,urueedi/luci,hnyman/luci,openwrt/luci,MinFu/luci,Wedmer/luci,LuttyYang/luci,david-xiao/luci,jorgifumi/luci,male-puppies/luci,lcf258/openwrtcn,forward619/luci,tobiaswaldvogel/luci,ff94315/luci-1,slayerrensky/luci,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,wongsyrone/luci-1,joaofvieira/luci,wongsyrone/luci-1,openwrt/luci,teslamint/luci,deepak78/new-luci,wongsyrone/luci-1,male-puppies/luci,jorgifumi/luci,kuoruan/lede-luci,RuiChen1113/luci,zhaoxx063/luci,kuoruan/luci,obsy/luci,openwrt/luci,openwrt-es/openwrt-luci,obsy/luci,obsy/luci,oneru/luci,keyidadi/luci,Wedmer/luci,zhaoxx063/luci,dismantl/luci-0.12,oyido/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,Noltari/luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,Hostle/luci,deepak78/new-luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,jchuang1977/luci-1,remakeelectric/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,opentechinstitute/luci,urueedi/luci,dwmw2/luci,remakeelectric/luci,rogerpueyo/luci,nwf/openwrt-luci,fkooman/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,taiha/luci,joaofvieira/luci,tcatm/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,sujeet14108/luci,thesabbir/luci,jlopenwrtluci/luci,marcel-sch/luci,marcel-sch/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,nmav/luci,artynet/luci,palmettos/test,male-puppies/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,palmettos/test,tobiaswaldvogel/luci,deepak78/new-luci,harveyhu2012/luci,schidler/ionic-luci,Noltari/luci,keyidadi/luci,ollie27/openwrt_luci,urueedi/luci,obsy/luci,schidler/ionic-luci,forward619/luci,MinFu/luci,ff94315/luci-1,remakeelectric/luci,nwf/openwrt-luci,david-xiao/luci,NeoRaider/luci,dwmw2/luci,openwrt/luci,keyidadi/luci,shangjiyu/luci-with-extra,forward619/luci,RuiChen1113/luci,Wedmer/luci,mumuqz/luci,deepak78/new-luci,lbthomsen/openwrt-luci,obsy/luci,chris5560/openwrt-luci,rogerpueyo/luci,daofeng2015/luci,florian-shellfire/luci,cappiewu/luci,ff94315/luci-1,keyidadi/luci,thess/OpenWrt-luci,RuiChen1113/luci,cappiewu/luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,shangjiyu/luci-with-extra,dwmw2/luci,cshore/luci,openwrt/luci,kuoruan/lede-luci
ec13f98b196c4c91c82197677b303a278ef2bad4
src/clienttranslator/src/Client/JSONTranslator.lua
src/clienttranslator/src/Client/JSONTranslator.lua
--- -- @classmod JSONTranslator -- @author Quenty local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local LocalizationService = game:GetService("LocalizationService") local Players = game:GetService("Players") local RunService = game:GetService("RunService") local JsonToLocalizationTable = require("JsonToLocalizationTable") local PseudoLocalize = require("PseudoLocalize") local LocalizationServiceUtils = require("LocalizationServiceUtils") local Promise = require("Promise") local JSONTranslator = {} JSONTranslator.ClassName = "JSONTranslator" JSONTranslator.__index = JSONTranslator function JSONTranslator.new(parent) local self = setmetatable({}, JSONTranslator) self._parent = assert(parent, "No parent") -- Cache localizaiton table, because it can take 10-20ms to load. self._localizationTable = JsonToLocalizationTable.loadFolder(self._parent) self._localizationTable.Name = ("JSONTable_%s"):format(parent.Name) if RunService:IsRunning() then self._localizationTable.Parent = LocalizationService self._englishTranslator = self._localizationTable:GetTranslator("en") self._promiseTranslator = Promise.resolved(self._englishTranslator) else self._promiseTranslator = LocalizationServiceUtils.promiseTranslator(Players.LocalPlayer) end if RunService:IsStudio() then PseudoLocalize.addToLocalizationTable(self._localizationTable, nil, "en") end return self end function JSONTranslator:PromiseLoaded() return self._promiseTranslator end function JSONTranslator:PromiseFormatByKey(key, args) assert(self ~= JSONTranslator, "Construct a new version of this class to use it") assert(type(key) == "string", "Key must be a string") return self._promiseTranslator:Then(function() return self:FormatByKey(key, args) end) end --- Blocking format until the cloud translations are loaded. function JSONTranslator:FormatByKey(key, args) assert(self ~= JSONTranslator, "Construct a new version of this class to use it") assert(type(key) == "string", "Key must be a string") if not RunService:IsRunning() then return self:_formatByKeyTestMode(key, args) end local clientTranslator = self:_getClientTranslatorOrError() local result local ok, err = pcall(function() result = clientTranslator:FormatByKey(key, args) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end -- Fallback to English if clientTranslator.LocaleId ~= self._englishTranslator.LocaleId then -- Ignore results as we know this may error ok, err = pcall(function() result = self._englishTranslator:FormatByKey(key, args) end) if ok and not err then return result end end return key end function JSONTranslator:_getClientTranslatorOrError() assert(self._promiseTranslator, "ClientTranslator is not initialized") if self._promiseTranslator:IsFulfilled() then return self._promiseTranslator:Wait() else error("Translator is not yet acquired yet") return nil end end function JSONTranslator:_formatByKeyTestMode(key, args) local i18n = self._parent:FindFirstChild("i18n") if not i18n then return key end -- Can't read LocalizationService.ForcePlayModeRobloxLocaleId :( local translator = self._localizationTable:GetTranslator("en") local result local ok, err = pcall(function() result = translator:FormatByKey(key, args) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end return key end function JSONTranslator:Destroy() self._localizationTable:Destroy() self._localizationTable = nil self._englishTranslator = nil self._promiseTranslator = nil setmetatable(self, nil) end return JSONTranslator
--- -- @classmod JSONTranslator -- @author Quenty local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local LocalizationService = game:GetService("LocalizationService") local Players = game:GetService("Players") local RunService = game:GetService("RunService") local JsonToLocalizationTable = require("JsonToLocalizationTable") local PseudoLocalize = require("PseudoLocalize") local LocalizationServiceUtils = require("LocalizationServiceUtils") local Promise = require("Promise") local JSONTranslator = {} JSONTranslator.ClassName = "JSONTranslator" JSONTranslator.__index = JSONTranslator function JSONTranslator.new(parent) local self = setmetatable({}, JSONTranslator) self._parent = assert(parent, "No parent") -- Cache localizaiton table, because it can take 10-20ms to load. self._localizationTable = JsonToLocalizationTable.loadFolder(self._parent) self._localizationTable.Name = ("JSONTable_%s"):format(parent.Name) self._localizationTable.Parent = LocalizationService self._englishTranslator = self._localizationTable:GetTranslator("en") if RunService:IsRunning() then self._promiseTranslator = LocalizationServiceUtils.promiseTranslator(Players.LocalPlayer) else self._promiseTranslator = Promise.resolved(self._englishTranslator) end if RunService:IsStudio() then PseudoLocalize.addToLocalizationTable(self._localizationTable, nil, "en") end return self end function JSONTranslator:PromiseLoaded() return self._promiseTranslator end function JSONTranslator:PromiseFormatByKey(key, args) assert(self ~= JSONTranslator, "Construct a new version of this class to use it") assert(type(key) == "string", "Key must be a string") return self._promiseTranslator:Then(function() return self:FormatByKey(key, args) end) end --- Blocking format until the cloud translations are loaded. function JSONTranslator:FormatByKey(key, args) assert(self ~= JSONTranslator, "Construct a new version of this class to use it") assert(type(key) == "string", "Key must be a string") if not RunService:IsRunning() then return self:_formatByKeyTestMode(key, args) end local clientTranslator = self:_getClientTranslatorOrError() local result local ok, err = pcall(function() result = clientTranslator:FormatByKey(key, args) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end -- Fallback to English if clientTranslator.LocaleId ~= self._englishTranslator.LocaleId then -- Ignore results as we know this may error ok, err = pcall(function() result = self._englishTranslator:FormatByKey(key, args) end) if ok and not err then return result end end return key end function JSONTranslator:_getClientTranslatorOrError() assert(self._promiseTranslator, "ClientTranslator is not initialized") if self._promiseTranslator:IsFulfilled() then return assert(self._promiseTranslator:Wait(), "Failed to get translator") else error("Translator is not yet acquired yet") return nil end end function JSONTranslator:_formatByKeyTestMode(key, args) local i18n = self._parent:FindFirstChild("i18n") if not i18n then return key end -- Can't read LocalizationService.ForcePlayModeRobloxLocaleId :( local translator = self._localizationTable:GetTranslator("en") local result local ok, err = pcall(function() result = translator:FormatByKey(key, args) end) if ok and not err then return result end if err then warn(err) else warn("Failed to localize '" .. key .. "'") end return key end function JSONTranslator:Destroy() self._localizationTable:Destroy() self._localizationTable = nil self._englishTranslator = nil self._promiseTranslator = nil setmetatable(self, nil) end return JSONTranslator
fix: JSONTranslator fails to resolve to anything but english in run mode
fix: JSONTranslator fails to resolve to anything but english in run mode
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
968e96378d32d5be53ce169a3b1bf386fee538fd
src/luarocks/fs.lua
src/luarocks/fs.lua
--- Proxy module for filesystem and platform abstractions. -- All code using "fs" code should require "luarocks.fs", -- and not the various platform-specific implementations. -- However, see the documentation of the implementation -- for the API reference. local pairs = pairs --module("luarocks.fs", package.seeall) local fs = {} package.loaded["luarocks.fs"] = fs local cfg = require("luarocks.cfg") local pack = table.pack or function(...) return { n = select("#", ...), ... } end local unpack = table.unpack or unpack local old_popen, old_exec fs.verbose = function() -- patch io.popen and os.execute to display commands in verbose mode if old_popen or old_exec then return end old_popen = io.popen io.popen = function(one, two) if two == nil then print("\nio.popen: ", one) else print("\nio.popen: ", one, "Mode:", two) end return old_popen(one, two) end old_exec = os.execute os.execute = function(cmd) print("\nos.execute: ", cmd) local code = pack(old_exec(cmd)) print("Results: "..tostring(code.n)) for i = 1,code.n do print(" "..tostring(i).." ("..type(code[i]).."): "..tostring(code[i])) end return unpack(code, 1, code.n) end end if cfg.verbose then fs.verbose() end local function load_fns(fs_table) for name, fn in pairs(fs_table) do if not fs[name] then fs[name] = fn end end end -- Load platform-specific functions local loaded_platform = nil for _, platform in ipairs(cfg.platforms) do local ok, fs_plat = pcall(require, "luarocks.fs."..platform) if ok and fs_plat then loaded_platform = platform load_fns(fs_plat) break end end -- Load platform-independent pure-Lua functionality local fs_lua = require("luarocks.fs.lua") load_fns(fs_lua) -- Load platform-specific fallbacks for missing Lua modules local ok, fs_plat_tools = pcall(require, "luarocks.fs."..loaded_platform..".tools") if ok and fs_plat_tools then load_fns(fs_plat_tools) end return fs
--- Proxy module for filesystem and platform abstractions. -- All code using "fs" code should require "luarocks.fs", -- and not the various platform-specific implementations. -- However, see the documentation of the implementation -- for the API reference. local pairs = pairs --module("luarocks.fs", package.seeall) local fs = {} package.loaded["luarocks.fs"] = fs local cfg = require("luarocks.cfg") local pack = table.pack or function(...) return { n = select("#", ...), ... } end local unpack = table.unpack or unpack local old_popen, old_exec fs.verbose = function() -- patch io.popen and os.execute to display commands in verbose mode if old_popen or old_exec then return end old_popen = io.popen io.popen = function(one, two) if two == nil then print("\nio.popen: ", one) else print("\nio.popen: ", one, "Mode:", two) end return old_popen(one, two) end old_exec = os.execute os.execute = function(cmd) -- redact api keys if present print("\nos.execute: ", cmd:gsub("(/api/[^/]+/)([^/]+)/", function(cap, key) return cap.."<redacted>/" end)) local code = pack(old_exec(cmd)) print("Results: "..tostring(code.n)) for i = 1,code.n do print(" "..tostring(i).." ("..type(code[i]).."): "..tostring(code[i])) end return unpack(code, 1, code.n) end end if cfg.verbose then fs.verbose() end local function load_fns(fs_table) for name, fn in pairs(fs_table) do if not fs[name] then fs[name] = fn end end end -- Load platform-specific functions local loaded_platform = nil for _, platform in ipairs(cfg.platforms) do local ok, fs_plat = pcall(require, "luarocks.fs."..platform) if ok and fs_plat then loaded_platform = platform load_fns(fs_plat) break end end -- Load platform-independent pure-Lua functionality local fs_lua = require("luarocks.fs.lua") load_fns(fs_lua) -- Load platform-specific fallbacks for missing Lua modules local ok, fs_plat_tools = pcall(require, "luarocks.fs."..loaded_platform..".tools") if ok and fs_plat_tools then load_fns(fs_plat_tools) end return fs
Redact api tokens when using --verbose flag
Redact api tokens when using --verbose flag fixes #358
Lua
mit
coderstudy/luarocks,luarocks/luarocks,usstwxy/luarocks,tarantool/luarocks,xpol/luarocks,xiaq/luarocks,tst2005/luarocks,tarantool/luarocks,xiaq/luarocks,keplerproject/luarocks,luarocks/luarocks,coderstudy/luarocks,xiaq/luarocks,ignacio/luarocks,tarantool/luarocks,xpol/luarocks,xpol/luavm,lxbgit/luarocks,xpol/luainstaller,xpol/luavm,keplerproject/luarocks,lxbgit/luarocks,ignacio/luarocks,lxbgit/luarocks,aryajur/luarocks,rrthomas/luarocks,tst2005/luarocks,aryajur/luarocks,lxbgit/luarocks,aryajur/luarocks,robooo/luarocks,aryajur/luarocks,usstwxy/luarocks,xpol/luavm,rrthomas/luarocks,luarocks/luarocks,xpol/luarocks,robooo/luarocks,usstwxy/luarocks,xpol/luarocks,xpol/luavm,coderstudy/luarocks,xpol/luainstaller,usstwxy/luarocks,ignacio/luarocks,coderstudy/luarocks,xpol/luainstaller,xpol/luavm,xpol/luainstaller,starius/luarocks,keplerproject/luarocks,robooo/luarocks,starius/luarocks,starius/luarocks,tst2005/luarocks,rrthomas/luarocks,xiaq/luarocks,tst2005/luarocks,keplerproject/luarocks,ignacio/luarocks,robooo/luarocks,starius/luarocks,rrthomas/luarocks
4125b0a37943c16732afef13b44cc8207c2be565
src/viewport/src/Client/Viewport.lua
src/viewport/src/Client/Viewport.lua
--[=[ @class Viewport ]=] local require = require(script.Parent.loader).load(script) local AdorneeUtils = require("AdorneeUtils") local BasicPane = require("BasicPane") local Blend = require("Blend") local CameraUtils = require("CameraUtils") local CircleUtils = require("CircleUtils") local Maid = require("Maid") local Math = require("Math") local Observable = require("Observable") local SpringObject = require("SpringObject") local ValueObject = require("ValueObject") local ViewportControls = require("ViewportControls") local Signal = require("Signal") local Rx = require("Rx") local MAX_PITCH = math.pi/3 local MIN_PITCH = -math.pi/3 local TAU = math.pi*2 local Viewport = setmetatable({}, BasicPane) Viewport.ClassName = "Viewport" Viewport.__index = Viewport function Viewport.new() local self = setmetatable(BasicPane.new(), Viewport) self._current = ValueObject.new(nil) self._maid:GiveTask(self._current) self._transparency = ValueObject.new(0) self._maid:GiveTask(self._transparency) self._absoluteSize = ValueObject.new(Vector2.new()) self._maid:GiveTask(self._absoluteSize) self._fieldOfView = ValueObject.new(20) self._maid:GiveTask(self._fieldOfView) self._rotationYawSpring = SpringObject.new(math.pi/4) self._rotationYawSpring.Speed = 30 self._maid:GiveTask(self._rotationYawSpring) self._rotationPitchSpring = SpringObject.new(-math.pi/6) self._rotationPitchSpring.Speed = 30 self._maid:GiveTask(self._rotationPitchSpring) self._notifyInstanceSizeChanged = Signal.new() self._maid:GiveTask(self._notifyInstanceSizeChanged) return self end function Viewport.blend(props) assert(type(props) == "table", "Bad props") return Observable.new(function(sub) local maid = Maid.new() local viewport = Viewport.new() local function bindObservable(propName, callback) if props[propName] then local observe = Blend.toPropertyObservable(props[propName]) if observe then maid:GiveTask(observe:Subscribe(function(value) callback(value) end)) else callback(props[propName]) end end end bindObservable("FieldOfView", function(value) viewport:SetFieldOfView(value) end) bindObservable("Instance", function(value) viewport:SetInstance(value) end) bindObservable("Transparency", function(value) viewport:SetTransparency(value) end) maid:GiveTask(viewport:Render(props):Subscribe(function(result) sub:Fire(result) end)) return maid end) end function Viewport:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") self._transparency.Value = transparency end function Viewport:SetFieldOfView(fieldOfView) assert(type(fieldOfView) == "number", "Bad fieldOfView") self._fieldOfView.Value = fieldOfView end function Viewport:SetInstance(instance) assert(typeof(instance) == "Instance" or instance == nil, "Bad instance") self._current.Value = instance end function Viewport:NotifyInstanceSizeChanged() self._notifyInstanceSizeChanged:Fire() end function Viewport:RotateBy(deltaV2, doNotAnimate) local target = (self._rotationYawSpring.Value + deltaV2.x) % TAU self._rotationYawSpring.Position = CircleUtils.updatePositionToSmallestDistOnCircle(self._rotationYawSpring.Position, target, TAU) self._rotationYawSpring.Target = target if doNotAnimate then self._rotationYawSpring.Position = self._rotationYawSpring.Target end self._rotationPitchSpring.Target = math.clamp(self._rotationPitchSpring.Value + deltaV2.y, MIN_PITCH, MAX_PITCH) if doNotAnimate then self._rotationPitchSpring.Position = self._rotationPitchSpring.Target end end function Viewport:Render(props) local currentCamera = ValueObject.new() self._maid:GiveTask(currentCamera) return Blend.New "ViewportFrame" { Parent = props.Parent; Size = props.Size or UDim2.new(1, 0, 1, 0); AnchorPoint = props.AnchorPoint; Position = props.Position; LayoutOrder = props.LayoutOrder; BackgroundTransparency = 1; CurrentCamera = currentCamera; LightColor = props.LightColor or Color3.fromRGB(200, 200, 200); Ambient = props.Ambient or Color3.fromRGB(140, 140, 140); ImageTransparency = Blend.Computed(props.Transparency or 0, self._transparency, function(propTransparency, selfTransparency) return Math.map(propTransparency, 0, 1, selfTransparency, 1) end); [Blend.OnChange "AbsoluteSize"] = self._absoluteSize; [Blend.Attached(function(viewport) return ViewportControls.new(viewport, self) end)] = true; [Blend.Attached(function(viewport) -- custom parenting scheme to ensure we don't call destroy on children local maid = Maid.new() local function update() local value = self._current.Value if value then value.Parent = viewport end end maid:GiveTask(self._current.Changed:Connect(update)) update() maid:GiveTask(function() local value = self._current.Value -- Ensure we don't call :Destroy() on our preview instance. if value then value.Parent = nil end end) return maid end)] = true; [Blend.Children] = { self._current; Blend.New "Camera" { [Blend.Instance] = currentCamera; Name = "CurrentCamera"; FieldOfView = self._fieldOfView; CFrame = Blend.Computed( self._current, self._absoluteSize, self._fieldOfView, self._rotationYawSpring:ObserveRenderStepped(), self._rotationPitchSpring:ObserveRenderStepped(), Rx.fromSignal(self._notifyInstanceSizeChanged), function(inst, absSize, fov, rotationYaw, rotationPitch) if typeof(inst) ~= "Instance" then return CFrame.new() end local aspectRatio = absSize.x/absSize.y local bbCFrame, bbSize = AdorneeUtils.getBoundingBox(inst) if not bbCFrame then return CFrame.new() end local fit = CameraUtils.fitBoundingBoxToCamera(bbSize, fov, aspectRatio) return CFrame.new(bbCFrame.Position) * CFrame.Angles(0, rotationYaw, 0) * CFrame.Angles(rotationPitch, 0, 0) * CFrame.new(0, 0, fit) end); } } }; end return Viewport
--[=[ @class Viewport ]=] local require = require(script.Parent.loader).load(script) local AdorneeUtils = require("AdorneeUtils") local BasicPane = require("BasicPane") local Blend = require("Blend") local CameraUtils = require("CameraUtils") local CircleUtils = require("CircleUtils") local Maid = require("Maid") local Math = require("Math") local Observable = require("Observable") local SpringObject = require("SpringObject") local ValueObject = require("ValueObject") local ViewportControls = require("ViewportControls") local Signal = require("Signal") local Rx = require("Rx") local MAX_PITCH = math.pi/3 local MIN_PITCH = -math.pi/3 local TAU = math.pi*2 local Viewport = setmetatable({}, BasicPane) Viewport.ClassName = "Viewport" Viewport.__index = Viewport function Viewport.new() local self = setmetatable(BasicPane.new(), Viewport) self._current = ValueObject.new(nil) self._maid:GiveTask(self._current) self._transparency = ValueObject.new(0) self._maid:GiveTask(self._transparency) self._absoluteSize = ValueObject.new(Vector2.new()) self._maid:GiveTask(self._absoluteSize) self._fieldOfView = ValueObject.new(20) self._maid:GiveTask(self._fieldOfView) self._rotationYawSpring = SpringObject.new(math.pi/4) self._rotationYawSpring.Speed = 30 self._maid:GiveTask(self._rotationYawSpring) self._rotationPitchSpring = SpringObject.new(-math.pi/6) self._rotationPitchSpring.Speed = 30 self._maid:GiveTask(self._rotationPitchSpring) self._notifyInstanceSizeChanged = Signal.new() self._maid:GiveTask(self._notifyInstanceSizeChanged) return self end function Viewport.blend(props) assert(type(props) == "table", "Bad props") return Observable.new(function(sub) local maid = Maid.new() local viewport = Viewport.new() local function bindObservable(propName, callback) if props[propName] then local observe = Blend.toPropertyObservable(props[propName]) if observe then maid:GiveTask(observe:Subscribe(function(value) callback(value) end)) else callback(props[propName]) end end end bindObservable("FieldOfView", function(value) viewport:SetFieldOfView(value) end) bindObservable("Instance", function(value) viewport:SetInstance(value) end) bindObservable("Transparency", function(value) viewport:SetTransparency(value) end) maid:GiveTask(viewport:Render(props):Subscribe(function(result) sub:Fire(result) end)) return maid end) end function Viewport:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") self._transparency.Value = transparency end function Viewport:SetFieldOfView(fieldOfView) assert(type(fieldOfView) == "number", "Bad fieldOfView") self._fieldOfView.Value = fieldOfView end function Viewport:SetInstance(instance) assert(typeof(instance) == "Instance" or instance == nil, "Bad instance") self._current.Value = instance end function Viewport:NotifyInstanceSizeChanged() self._notifyInstanceSizeChanged:Fire() end function Viewport:RotateBy(deltaV2, doNotAnimate) local target = (self._rotationYawSpring.Value + deltaV2.x) % TAU self._rotationYawSpring.Position = CircleUtils.updatePositionToSmallestDistOnCircle(self._rotationYawSpring.Position, target, TAU) self._rotationYawSpring.Target = target if doNotAnimate then self._rotationYawSpring.Position = self._rotationYawSpring.Target end self._rotationPitchSpring.Target = math.clamp(self._rotationPitchSpring.Value + deltaV2.y, MIN_PITCH, MAX_PITCH) if doNotAnimate then self._rotationPitchSpring.Position = self._rotationPitchSpring.Target end end function Viewport:Render(props) local currentCamera = ValueObject.new() self._maid:GiveTask(currentCamera) return Blend.New "ViewportFrame" { Parent = props.Parent; Size = props.Size or UDim2.new(1, 0, 1, 0); AnchorPoint = props.AnchorPoint; Position = props.Position; LayoutOrder = props.LayoutOrder; BackgroundTransparency = 1; CurrentCamera = currentCamera; LightColor = props.LightColor or Color3.fromRGB(200, 200, 200); Ambient = props.Ambient or Color3.fromRGB(140, 140, 140); ImageTransparency = Blend.Computed(props.Transparency or 0, self._transparency, function(propTransparency, selfTransparency) return Math.map(propTransparency, 0, 1, selfTransparency, 1) end); [Blend.OnChange "AbsoluteSize"] = self._absoluteSize; [Blend.Attached(function(viewport) return ViewportControls.new(viewport, self) end)] = true; [Blend.Attached(function(viewport) -- custom parenting scheme to ensure we don't call destroy on children local maid = Maid.new() local function update() local value = self._current.Value if value then value.Parent = viewport end end maid:GiveTask(self._current.Changed:Connect(update)) update() maid:GiveTask(function() local value = self._current.Value -- Ensure we don't call :Destroy() on our preview instance. if value then value.Parent = nil end end) return maid end)] = true; [Blend.Children] = { self._current; Blend.New "Camera" { [Blend.Instance] = currentCamera; Name = "CurrentCamera"; FieldOfView = self._fieldOfView; CFrame = Blend.Computed( self._current, self._absoluteSize, self._fieldOfView, self._rotationYawSpring:ObserveRenderStepped(), self._rotationPitchSpring:ObserveRenderStepped(), Rx.fromSignal(self._notifyInstanceSizeChanged):Pipe({ Rx.defaultsToNil; }), function(inst, absSize, fov, rotationYaw, rotationPitch) if typeof(inst) ~= "Instance" then return CFrame.new() end local aspectRatio = absSize.x/absSize.y local bbCFrame, bbSize = AdorneeUtils.getBoundingBox(inst) if not bbCFrame then return CFrame.new() end local fit = CameraUtils.fitBoundingBoxToCamera(bbSize, fov, aspectRatio) return CFrame.new(bbCFrame.Position) * CFrame.Angles(0, rotationYaw, 0) * CFrame.Angles(rotationPitch, 0, 0) * CFrame.new(0, 0, fit) end); } } }; end return Viewport
fix: Viewport would not render on first pass
fix: Viewport would not render on first pass
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
e78001ce96cf4d709c1141029c58a1a518d6c516
constants.lua
constants.lua
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local ConstantsCtx = require('virgo/util/constants_ctx').ConstantsCtx local path = require('path') local constants = ConstantsCtx:new() local SNET_REGIONS = { 'dfw', 'ord', 'lon', 'syd', 'hkg', 'iad' } local LIBRARY_DIR = "/var/lib/rackspace-monitoring-agent" constants:setGlobal('DEFAULT_CUSTOM_PLUGINS_PATH', path.join(LIBRARY_DIR, 'plugins')) constants:setGlobal('DEFAULT_PLUGIN_TIMEOUT', 60 * 1000) constants:setGlobal('PLUGIN_TYPE_MAP', {string = 'string', int = 'int64', float = 'double', gauge = 'gauge'}) constants:setGlobal('CRASH_REPORT_URL', 'https://monitoring.api.rackspacecloud.com/agent-crash-report') constants:setGlobal('DEFAULT_PID_FILE_PATH', '/var/run/rackspace-monitoring-agent.pid') constants:setGlobal('VALID_SNET_REGION_NAMES', SNET_REGIONS) constants:setGlobal('DEFAULT_MONITORING_SRV_QUERIES_STAGING', { '_monitoringagent._tcp.dfw1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.ord1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.lon3.stage.monitoring.api.rackspacecloud.com' }) constants:setGlobal('SNET_MONITORING_TEMPLATE_SRV_QUERIES_STAGING', { '_monitoringagent._tcp.snet-${region}-region0.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region2.stage.monitoring.api.rackspacecloud.com' }) constants:setGlobal('DEFAULT_MONITORING_SRV_QUERIES', { '_monitoringagent._tcp.dfw1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.ord1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.lon3.prod.monitoring.api.rackspacecloud.com' }) constants:setGlobal('SNET_MONITORING_TEMPLATE_SRV_QUERIES', { '_monitoringagent._tcp.snet-${region}-region0.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region2.prod.monitoring.api.rackspacecloud.com' }) constants:setGlobal('METRIC_STATUS_MAX_LENGTH', 256) return constants
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local const = require('virgo/util/constants_ctx') local path = require('path') local SNET_REGIONS = { 'dfw', 'ord', 'lon', 'syd', 'hkg', 'iad' } local constants = const.ConstantsCtx:new() constants:setGlobal('DEFAULT_CUSTOM_PLUGINS_PATH', path.join(const.LIBRARY_DIR, 'plugins')) constants:setGlobal('DEFAULT_PLUGIN_TIMEOUT', 60 * 1000) constants:setGlobal('PLUGIN_TYPE_MAP', {string = 'string', int = 'int64', float = 'double', gauge = 'gauge'}) constants:setGlobal('CRASH_REPORT_URL', 'https://monitoring.api.rackspacecloud.com/agent-crash-report') constants:setGlobal('DEFAULT_PID_FILE_PATH', '/var/run/rackspace-monitoring-agent.pid') constants:setGlobal('VALID_SNET_REGION_NAMES', SNET_REGIONS) constants:setGlobal('DEFAULT_MONITORING_SRV_QUERIES_STAGING', { '_monitoringagent._tcp.dfw1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.ord1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.lon3.stage.monitoring.api.rackspacecloud.com' }) constants:setGlobal('SNET_MONITORING_TEMPLATE_SRV_QUERIES_STAGING', { '_monitoringagent._tcp.snet-${region}-region0.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region1.stage.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region2.stage.monitoring.api.rackspacecloud.com' }) constants:setGlobal('DEFAULT_MONITORING_SRV_QUERIES', { '_monitoringagent._tcp.dfw1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.ord1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.lon3.prod.monitoring.api.rackspacecloud.com' }) constants:setGlobal('SNET_MONITORING_TEMPLATE_SRV_QUERIES', { '_monitoringagent._tcp.snet-${region}-region0.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region1.prod.monitoring.api.rackspacecloud.com', '_monitoringagent._tcp.snet-${region}-region2.prod.monitoring.api.rackspacecloud.com' }) constants:setGlobal('METRIC_STATUS_MAX_LENGTH', 256) return constants
fix plugin path
fix plugin path
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent
c8f6accc86ee82951160bf0f712e7cc1588ea1aa
game/scripts/vscripts/heroes/hero_saitama/jogging.lua
game/scripts/vscripts/heroes/hero_saitama/jogging.lua
LinkLuaModifier("modifier_saitama_jogging", "heroes/hero_saitama/jogging.lua", LUA_MODIFIER_MOTION_NONE) saitama_jogging = class({ GetIntrinsicModifierName = function() return "modifier_saitama_jogging" end, }) modifier_saitama_jogging = class({}) function modifier_saitama_jogging:DeclareFunctions() return {MODIFIER_EVENT_ON_UNIT_MOVED} end if IsServer() then function modifier_saitama_jogging:OnCreated() self.range = 0 end function modifier_saitama_jogging:OnUpgrade() self:UpdatePercentage() end function modifier_saitama_jogging:OnUnitMoved() local ability = self:GetAbility() local parent = self:GetParent() local position = parent:GetAbsOrigin() if self.position then local range = (self.position - position):Length2D() if range > 0 and range <= ability:GetSpecialValueFor("range_limit") then self.range = self.range + range self:UpdatePercentage() end end self.position = position end function modifier_saitama_jogging:UpdatePercentage() local ability = self:GetAbility() local completePart = self.range / ability:GetSpecialValueFor("range") if completePart < 1 then self:SetStackCount(math.floor(completePart * 100)) else local parent = self:GetParent() self.range = 0 self:SetStackCount(0) parent:ModifyStrength(ability:GetSpecialValueFor("bonus_strength")) ModifyStacksLua(ability, parent, parent, "modifier_saitama_limiter", ability:GetSpecialValueFor("stacks_amount")) end end end
LinkLuaModifier("modifier_saitama_jogging", "heroes/hero_saitama/jogging.lua", LUA_MODIFIER_MOTION_NONE) saitama_jogging = class({ GetIntrinsicModifierName = function() return "modifier_saitama_jogging" end, }) if IsServer() then function saitama_jogging:OnUpgrade() local modifier = self:GetCaster():FindModifierByName(self:GetIntrinsicModifierName()) if modifier then modifier:UpdatePercentage() end end end modifier_saitama_jogging = class({}) function modifier_saitama_jogging:DeclareFunctions() return {MODIFIER_EVENT_ON_UNIT_MOVED} end if IsServer() then function modifier_saitama_jogging:OnCreated() self.range = 0 end function modifier_saitama_jogging:OnUnitMoved() local ability = self:GetAbility() local parent = self:GetParent() local position = parent:GetAbsOrigin() if self.position then local range = (self.position - position):Length2D() if range > 0 and range <= ability:GetSpecialValueFor("range_limit") then self.range = self.range + range self:UpdatePercentage() end end self.position = position end function modifier_saitama_jogging:UpdatePercentage() local ability = self:GetAbility() local completePart = self.range / ability:GetSpecialValueFor("range") if completePart < 1 then self:SetStackCount(math.floor(completePart * 100)) else local parent = self:GetParent() self.range = 0 self:SetStackCount(0) parent:ModifyStrength(ability:GetSpecialValueFor("bonus_strength")) ModifyStacksLua(ability, parent, parent, "modifier_saitama_limiter", ability:GetSpecialValueFor("stacks_amount")) end end end
Fixed Jogging OnUpgrade event
Fixed Jogging OnUpgrade event
Lua
mit
ark120202/aabs
fec0017e733d54038e5188c5527d4dec98f4b6b1
spec/patient_example_spec.lua
spec/patient_example_spec.lua
--[[ FHIR Formats Copyright (C) 2016 Vadim Peretokin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local in_fhir_json = require("fhir-formats").to_json local in_fhir_xml = require("fhir-formats").to_xml local cjson = require("cjson") local xml = require("xml") describe("xml to json", function() local positive_example, negative_example, patient_example, positive_example_data, patient_example_data setup(function() io.input("spec/patient-example-good.json") positive_example_data = io.read("*a") patient_example_data = in_fhir_json("spec/patient-example.xml", {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) before_each(function() positive_example = cjson.decode(positive_example_data) patient_example = cjson.decode(patient_example_data) end) it("should have the same non-div data", function() -- cut out the div's, since the whitespace doesn't matter as much in xml positive_example.text.div = nil patient_example.text.div = nil assert.same(positive_example, patient_example) end) it("should have xml-comparable div data", function() local positive_example_div = xml.load(positive_example.text.div) local patient_example_div = xml.load(patient_example.text.div) assert.same(positive_example_div, patient_example_div) end) end) describe("json to xml", function() local positive_example, negative_example, patient_example, positive_example_data, patient_example_data setup(function() io.input("spec/patient-example.xml") positive_example_data = io.read("*a") patient_example_data = in_fhir_xml("spec/patient-example-good.json", {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) before_each(function() positive_example = xml.load(positive_example_data) patient_example = xml.load(patient_example_data) end) it("should have the same non-div data", function() -- cut out the div's, since the whitespace doesn't matter as much in xml -- positive_example.text.div = nil -- patient_example.text.div = nil assert.same(positive_example, patient_example) end) it("should have xml-comparable div data", function() assert.same(positive_example.text.div, patient_example.text.div) end) end)
--[[ FHIR Formats Copyright (C) 2016 Vadim Peretokin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local in_fhir_json = require("fhir-formats").to_json local in_fhir_xml = require("fhir-formats").to_xml local cjson = require("cjson") local xml = require("xml") local inspect = require("inspect") describe("xml to json", function() local positive_example, negative_example, patient_example, positive_example_data, patient_example_data setup(function() io.input("spec/patient-example-good.json") positive_example_data = io.read("*a") patient_example_data = in_fhir_json("spec/patient-example.xml", {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) before_each(function() positive_example = cjson.decode(positive_example_data) patient_example = cjson.decode(patient_example_data) end) it("should have the same non-div data", function() -- cut out the div's, since the whitespace doesn't matter as much in xml positive_example.text.div = nil patient_example.text.div = nil assert.same(positive_example, patient_example) end) it("should have xml-comparable div data", function() local positive_example_div = xml.load(positive_example.text.div) local patient_example_div = xml.load(patient_example.text.div) --print(inspect(positive_example_div)) --print(inspect(patient_example_div)) assert.same(positive_example_div, patient_example_div) end) end) describe("json to xml", function() local positive_example, negative_example, patient_example, positive_example_data, patient_example_data setup(function() io.input("spec/patient-example.xml") positive_example_data = io.read("*a") patient_example_data = in_fhir_xml("spec/patient-example-good.json", {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) it("should have the same data", function() -- convert it down to JSON since order of elements doesn't matter in JSON, while it does in XML assert.same(cjson.decode(in_fhir_json(positive_example_data)), cjson.decode(in_fhir_json(patient_example_data))) end) end)
Added a JSON -> XML test
Added a JSON -> XML test Also fixed testcases by updating the newlines
Lua
apache-2.0
vadi2/fhir-formats
d43c055c6056dd086f46324f73b7c0493d7ed698
UCDphone/apps/im/im_s.lua
UCDphone/apps/im/im_s.lua
IM = {} IM.friends = {} db = exports.UCDsql:getConnection() addEvent("UCDphone.requestFriendList", true) addEventHandler("UCDphone.requestFriendList", root, function () IM.sendFriends(client) end ) addEventHandler("onPlayerLogin", root, function () IM.sendFriends(source) end ) function IM.loadFriends(qh) local result = qh:poll(-1) if (result and #result >= 1) then for _, t in ipairs(result) do IM.friends[t.account] = fromJSON(t.friends) -- If a player is online if (Account(t.account) and Account(t.account).player) then local plr = Account(t.account).player IM.sendFriends(plr) end end end end db:query(IM.loadFriends, {}, "SELECT * FROM `sms_friends`") -- Placing it here removes debug issues when editing the client apps function IM.sendFriends(plr) local temp = {} if (IM.friends[plr.account.name]) then for i, accountName in ipairs(IM.friends[plr.account.name]) do local displayName, online, LUN if (Account(accountName).player) then displayName = Account(accountName).player.name online = true else --displayName = exports.UCDaccounts:GAD(accountName, "lastUsedName") displayName = accountName end temp[i] = {[1] = displayName, [2] = online, [3] = accountName} end else return end triggerClientEvent(plr, "UCDphone.sendFriends", plr, temp or {}) end function IM.addFriend(plrName) if (client and plrName) then if (not Player(plrName) or not exports.UCDaccounts:isPlayerLoggedIn(Player(plrName))) then return end if (not IM.friends[client.account.name]) then IM.friends[client.account.name] = {} end if (#IM.friends[client.account.name] >= 20) then exports.UCDdx:new(client, "You cannot have more than 20 IM friends", 255, 0, 0) return end for k, v in ipairs(IM.friends[client.account.name]) do if (v == Player(plrName).account.name) then exports.UCDdx:new(client, "This player is already your friend", 255, 0, 0) return end end table.insert(IM.friends[client.account.name], Player(plrName).account.name) db:exec("UPDATE `sms_friends` SET `friends`=? WHERE `account`=?", toJSON(IM.friends[client.account.name]), client.account.name) exports.UCDdx:new(client, "You have added "..tostring(Player(plrName).account.name).." to your friends list", 0, 255, 0) IM.sendFriends(client) end end addEvent("UCDphone.addFriend", true) addEventHandler("UCDphone.addFriend", root, IM.addFriend) function IM.removeFriend(accName) if (client and accName) then if (not Account(accName) or not Account(accName).name) then return end if (not IM.friends[client.account.name]) then return end local x for k, v in ipairs(IM.friends[client.account.name]) do if (v == accName) then table.remove(IM.friends[client.account.name], k) break end end if (Account(accName).player) then exports.UCDdx:new(client, Account(accName).player.name.." has been removed from your friends list", 0, 255, 0) else exports.UCDdx:new(client, accName.." has been removed from your friends list", 0, 255, 0) end db:exec("UPDATE `sms_friends` SET `friends`=? WHERE `account`=?", toJSON(IM.friends[client.account.name]), client.account.name) IM.sendFriends(client) end end addEvent("UCDphone.removeFriend", true) addEventHandler("UCDphone.removeFriend", root, IM.removeFriend)
IM = {} IM.friends = {} db = exports.UCDsql:getConnection() addEvent("UCDphone.requestFriendList", true) addEventHandler("UCDphone.requestFriendList", root, function () IM.sendFriends(client) end ) addEventHandler("onPlayerLogin", root, function () IM.sendFriends(source) end ) function IM.loadFriends(qh) local result = qh:poll(-1) if (result and #result >= 1) then for _, t in ipairs(result) do IM.friends[t.account] = fromJSON(t.friends) -- If a player is online if (Account(t.account) and Account(t.account).player) then local plr = Account(t.account).player IM.sendFriends(plr) end end end end db:query(IM.loadFriends, {}, "SELECT * FROM `sms_friends`") -- Placing it here removes debug issues when editing the client apps function IM.sendFriends(plr) local temp = {} if (IM.friends[plr.account.name]) then for i, accountName in ipairs(IM.friends[plr.account.name]) do local displayName, online, LUN if (Account(accountName).player) then displayName = Account(accountName).player.name online = true else --displayName = exports.UCDaccounts:GAD(accountName, "lastUsedName") displayName = accountName end temp[i] = {[1] = displayName, [2] = online, [3] = accountName} end else return end triggerClientEvent(plr, "UCDphone.sendFriends", plr, temp or {}) end function IM.addFriend(plrName) if (client and plrName) then local plr = Player(plrName) if (not plr or not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return end if (not IM.friends[client.account.name]) then IM.friends[client.account.name] = {} end if (#IM.friends[client.account.name] >= 20) then exports.UCDdx:new(client, "You cannot have more than 20 IM friends", 255, 0, 0) return end for k, v in ipairs(IM.friends[client.account.name]) do if (v == plr.account.name) then exports.UCDdx:new(client, "This player is already your friend", 255, 0, 0) return end end table.insert(IM.friends[client.account.name], plr.account.name) outputDebugString("IM.addFriend -> "..tostring(toJSON(IM.friends[client.account.name])).." ["..client.account.name.."]") db:exec("UPDATE `sms_friends` SET `friends`=? WHERE `account`=?", toJSON(IM.friends[client.account.name]), client.account.name) exports.UCDdx:new(client, "You have added "..tostring(plr.name).." to your friends list", 0, 255, 0) IM.sendFriends(client) end end addEvent("UCDphone.addFriend", true) addEventHandler("UCDphone.addFriend", root, IM.addFriend) function IM.removeFriend(accName) if (client and accName) then if (not Account(accName) or not Account(accName).name) then return end if (not IM.friends[client.account.name]) then return end local x for k, v in ipairs(IM.friends[client.account.name]) do if (v == accName) then table.remove(IM.friends[client.account.name], k) break end end if (Account(accName).player) then exports.UCDdx:new(client, Account(accName).player.name.." has been removed from your friends list", 0, 255, 0) else exports.UCDdx:new(client, tostring(exports.UCDaccounts:GAD(accName, "lastUsedName")).." has been removed from your friends list", 0, 255, 0) end outputDebugString("IM.removeFriend -> "..tostring(toJSON(IM.friends[client.account.name])).." ["..client.account.name.."]") db:exec("UPDATE `sms_friends` SET `friends`=? WHERE `account`=?", toJSON(IM.friends[client.account.name]), client.account.name) IM.sendFriends(client) end end addEvent("UCDphone.removeFriend", true) addEventHandler("UCDphone.removeFriend", root, IM.removeFriend)
UCDphone
UCDphone - Fixed some errors that would occur in the IM friend system.
Lua
mit
nokizorque/ucd,nokizorque/ucd
6febf4cae263bb99af19a22ae643265e2b441105
UCDchecking/checking.lua
UCDchecking/checking.lua
local actions = { ["RobHouse"] = { {"a", "RobHouse", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["EnterHouse"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Jetpack"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoDead"}, }, ["JobVehicle"] = { {"a", "RobHouse", "AFK"}, {"ld", 3}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, } function canPlayerDoAction(plr, action) if (not plr or not action or not actions[action] or not isElement(plr) or plr.type ~= "player" or plr.account.guest) then return false end local currentActivity = exports.UCDactions:getAction(plr) -- plr:getData("a") for _, dat in pairs(actions[action]) do for i, dat2 in pairs(dat) do if (dat[1] == "a" and dat2 == currentActivity) then exports.UCDdx:new(plr, "An activity you're doing blocks this action", 255, 0, 0) return false end if (dat[1] == "w") then if (plr.wantedLevel >= dat2) then exports.UCDdx:new(plr, "Your wanted level blocks this action", 255, 0, 0) return false end end if (dat[1] == "i" and plr.interior ~= dat2) then exports.UCDdx:new(plr, "Your interior blocks this action", 255, 0, 0) return false end if (dat[1] == "d" and plr.dimension ~= dat2) then exports.UCDdx:new(plr, "Your dimension blocks this action", 255, 0, 0) return false end if (dat[1] == "s") then if (dat2 == "NoVehicle" and plr.vehicle) then exports.UCDdx:new(plr, "Being in a vehicle blocks this action", 255, 0, 0) return false end if (dat2 == "NoDead" and plr.dead) then exports.UCDdx:new(plr, "Being dead blocks this action", 255, 0, 0) return false end if (dat2 == "NoJetpack" and plr:doesHaveJetpack()) then exports.UCDdx:new(plr, "Having a jetpack blocks this action", 255, 0, 0) return false end end end end return true end
local actions = { ["RobHouse"] = { {"a", "RobHouse", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["EnterHouse"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Jetpack"] = { {"a", "AFK"}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoDead"}, }, ["JobVehicle"] = { {"a", "RobHouse", "AFK"}, {"ld", 3}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoArrest", "NoJailed", "NoJetpack", "NoDead"}, }, ["Builder"] = { {"a", "RobHouse", "AFK"}, {"i", 0}, {"d", 0}, {"s", "NoVehicle", "NoDead", "NoArrest", "NoJailed", "NoJetpack", "NoDead"} }, } function canPlayerDoAction(plr, action) if (not plr or not action or not actions[action] or not isElement(plr) or plr.type ~= "player" or plr.account.guest) then return false end local currentActivity = exports.UCDactions:getAction(plr) -- plr:getData("a") for _, dat in pairs(actions[action]) do for i, dat2 in pairs(dat) do if (dat[1] == "a" and dat2 == currentActivity) then exports.UCDdx:new(plr, "An activity you're doing blocks this action", 255, 0, 0) return false end if (dat[1] == "w") then if (plr.wantedLevel >= dat2) then exports.UCDdx:new(plr, "Your wanted level blocks this action", 255, 0, 0) return false end end if (dat[1] == "i" and plr.interior ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your interior blocks this action", 255, 0, 0) return false end if (dat[1] == "d" and plr.dimension ~= dat2 and i ~= 1) then exports.UCDdx:new(plr, "Your dimension blocks this action", 255, 0, 0) return false end if (dat[1] == "s") then if (dat2 == "NoVehicle" and plr.vehicle) then exports.UCDdx:new(plr, "Being in a vehicle blocks this action", 255, 0, 0) return false end if (dat2 == "NoDead" and plr.dead) then exports.UCDdx:new(plr, "Being dead blocks this action", 255, 0, 0) return false end if (dat2 == "NoJetpack" and plr:doesHaveJetpack()) then exports.UCDdx:new(plr, "Having a jetpack blocks this action", 255, 0, 0) return false end end end end return true end
UCDchecking
UCDchecking - Fixed bug relating to looping. - Added Builder action.
Lua
mit
nokizorque/ucd,nokizorque/ucd
e4de0e74e8885454d0bca43bd5f8d4150425ecf9
UCDplaytime/server.lua
UCDplaytime/server.lua
-- Global variables local playerTickCount = {} -- Events function onLogin(_, theCurrentAccount) if (not isGuestAccount(theCurrentAccount)) then source:setData("playtime", exports.UCDaccounts:GAD(source, "playtime"), true) playerTickCount[source] = getTickCount() end end addEventHandler("onPlayerLogin", root, onLogin) function onQuit() if (not exports.UCDaccounts:isPlayerLoggedIn(source)) then return end local pAccTime = exports.UCDaccounts:GAD(source, "playtime") local pPlayTime = math.floor((getTickCount() - playerTickCount[source]) / 1000) exports.UCDaccounts:SAD(source, "playtime", tonumber(pAccTime + pPlayTime)) playerTickCount[source] = nil end addEventHandler("onPlayerQuit", root, onQuit) function updateScoreboard() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return end if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end local currentTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) local totalTime = plr:getData("playtime") + currentTime plr:setData("dxscoreboard_playtime", exports.UCDutil:secondsToHoursMinutes(totalTime)) end end function onStart() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return end if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end plr:setData("playtime", exports.UCDaccounts:GAD(plr, "playtime"), true) end updateScoreboard() setTimer(updateScoreboard, 900, 0) -- There is no need to define a variable for the timer but we might need this variable in the future. end addEventHandler("onResourceStart", resourceRoot, onStart) function onStop() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return false end local accPlayTime = exports.UCDaccounts:GAD(plr, "playtime") local currPlayTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) exports.UCDaccounts:SAD(plr, "playtime", tonumber(accPlayTime + currPlayTime)) playerTickCount[plr] = nil end end addEventHandler("onResourceStop", resourceRoot, onStop)
-- Global variables local playerTickCount = {} -- Events function onLogin(_, theCurrentAccount) if (not isGuestAccount(theCurrentAccount)) then source:setData("playtime", exports.UCDaccounts:GAD(source, "playtime"), true) playerTickCount[source] = getTickCount() end end addEventHandler("onPlayerLogin", root, onLogin) function onQuit() if (not exports.UCDaccounts:isPlayerLoggedIn(source)) then return end local pAccTime = exports.UCDaccounts:GAD(source, "playtime") local pPlayTime = math.floor((getTickCount() - playerTickCount[source]) / 1000) exports.UCDaccounts:SAD(source, "playtime", tonumber(pAccTime + pPlayTime)) playerTickCount[source] = nil end addEventHandler("onPlayerQuit", root, onQuit) function updateScoreboard() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return end if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end local currentTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) local totalTime = plr:getData("playtime") + currentTime plr:setData("dxscoreboard_playtime", exports.UCDutil:secondsToHoursMinutes(totalTime)) end end function onStart() for _, plr in pairs(Element.getAllByType("player")) do if (exports.UCDaccounts:isPlayerLoggedIn(plr)) then if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end plr:setData("playtime", exports.UCDaccounts:GAD(plr, "playtime"), true) end end updateScoreboard() setTimer(updateScoreboard, 900, 0) -- There is no need to define a variable for the timer but we might need this variable in the future. end addEventHandler("onResourceStart", resourceRoot, onStart) function onStop() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then local accPlayTime = exports.UCDaccounts:GAD(plr, "playtime") local currPlayTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) exports.UCDaccounts:SAD(plr, "playtime", tonumber(accPlayTime + currPlayTime)) playerTickCount[plr] = nil end end end addEventHandler("onResourceStop", resourceRoot, onStop)
UCDplaytime
UCDplaytime - Fixed for-all-player(s) loops breaking when a player isn't logged in.
Lua
mit
nokizorque/ucd,nokizorque/ucd
f52cb5b5b5340330d96287e5923462b7fd5139c2
agents/monitoring/lua/lib/client/connection_stream.lua
agents/monitoring/lua/lib/client/connection_stream.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local Emitter = require('core').Emitter local math = require('math') local timer = require('timer') local fmt = require('string').format local async = require('async') local AgentClient = require('./client').AgentClient local ConnectionMessages = require('./connection_messages').ConnectionMessages local logging = require('logging') local misc = require('../util/misc') local fmt = require('string').format local CONNECT_TIMEOUT = 6000 local ConnectionStream = Emitter:extend() function ConnectionStream:initialize(id, token) self._id = id self._token = token self._clients = {} self._unauthedClients = {} self._delays = {} self._messages = ConnectionMessages:new(self) end --[[ Create and establish a connection to the multiple endpoints. addresses - An Array of ip:port pairs callback - Callback called with (err) when all the connections have been established. --]] function ConnectionStream:createConnections(addresses, callback) async.series({ -- connect function(callback) async.forEach(addresses, function(address, callback) local split, client, options split = misc.splitAddress(address) options = {} options.host = split[1] options.port = split[2] options.datacenter = address self:createConnection(options, callback) end) end }, callback) end function ConnectionStream:_setDelay(datacenter) local maxDelay = 5 * 60 * 1000 -- max connection delay in ms local jitter = 7000 -- jitter in ms local previousDelay = self._delays[datacenter] local delay if previousDelay == nil then self._delays[datacenter] = 0 previousDelay = 0 end delay = math.min(previousDelay, maxDelay) + (jitter * math.random()) self._delays[datacenter] = delay return delay end --[[ Retry a connection to the endpoint. options - datacenter, host, port datacenter - Datacenter name / host alias. host - Hostname. port - Port. callback - Callback called with (err) ]]-- function ConnectionStream:reconnect(options, callback) local datacenter = options.datacenter local delay = self:_setDelay(datacenter) logging.log(logging.INFO, fmt('%s:%d -> Retrying connection in %dms', options.host, options.port, delay)) timer.setTimeout(delay, function() self:createConnection(options, callback) end) end function ConnectionStream:getClient() local client, min_latency = 2147483647, latency for k, v in pairs(self._clients) do latency = self._clients[k]:getLatency() if latency == nil or min_latency > latency then client = self._clients[k] end min_latency = latency end return client end --[[ Move an unauthenticated client to the list of clients that have been authenticated. client - the client. ]]-- function ConnectionStream:_promoteClient(client) local datacenter = client:getDatacenter() client:log(logging.INFO, fmt('Connection has been authenticated to %s', datacenter)) self._clients[datacenter] = client self._unauthedClients[datacenter] = nil end --[[ Create and establish a connection to the endpoint. datacenter - Datacenter name / host alias. host - Hostname. port - Port. callback - Callback called with (err) ]]-- function ConnectionStream:createConnection(options, callback) local opts = misc.merge({ id = self._id, token = self._token, timeout = CONNECT_TIMEOUT }, options) local client = AgentClient:new(opts) client:on('error', function(err) err.host = opts.host err.port = opts.port err.datacenter = opts.datacenter client:destroy() self:reconnect(opts, callback) if err then self:emit('error', err) end end) client:on('timeout', function() logging.log(logging.DEBUG, fmt('%s:%d -> Client Timeout', opts.host, opts.port)) client:destroy() self:reconnect(opts, callback) end) client:on('end', function() self:emit('client_end', client) logging.log(logging.DEBUG, fmt('%s:%d -> Remote endpoint closed the connection', opts.host, opts.port)) client:destroy() self:reconnect(opts, callback) end) client:on('handshake_success', function() self:_promoteClient(client) self._delays[options.datacenter] = 0 client:startPingInterval() self._messages:emit('handshake_success', client) end) client:on('message', function(msg) self._messages:emit('message', client, msg) end) client:connect(function(err) if err then client:destroy() self:reconnect(opts, callback) callback(err) return end client.datacenter = datacenter self._unauthedClients[datacenter] = client callback(); end) return client end local exports = {} exports.ConnectionStream = ConnectionStream return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local Emitter = require('core').Emitter local math = require('math') local timer = require('timer') local fmt = require('string').format local async = require('async') local AgentClient = require('./client').AgentClient local ConnectionMessages = require('./connection_messages').ConnectionMessages local logging = require('logging') local misc = require('../util/misc') local fmt = require('string').format local CONNECT_TIMEOUT = 6000 local ConnectionStream = Emitter:extend() function ConnectionStream:initialize(id, token) self._id = id self._token = token self._clients = {} self._unauthedClients = {} self._delays = {} self._messages = ConnectionMessages:new(self) end --[[ Create and establish a connection to the multiple endpoints. addresses - An Array of ip:port pairs callback - Callback called with (err) when all the connections have been established. --]] function ConnectionStream:createConnections(addresses, callback) async.series({ -- connect function(callback) async.forEach(addresses, function(address, callback) local split, client, options split = misc.splitAddress(address) options = {} options.host = split[1] options.port = split[2] options.datacenter = address self:createConnection(options, callback) end) end }, callback) end function ConnectionStream:_setDelay(datacenter) local maxDelay = 5 * 60 * 1000 -- max connection delay in ms local jitter = 7000 -- jitter in ms local previousDelay = self._delays[datacenter] local delay if previousDelay == nil then self._delays[datacenter] = 0 previousDelay = 0 end delay = math.min(previousDelay, maxDelay) + (jitter * math.random()) self._delays[datacenter] = delay return delay end --[[ Retry a connection to the endpoint. options - datacenter, host, port datacenter - Datacenter name / host alias. host - Hostname. port - Port. callback - Callback called with (err) ]]-- function ConnectionStream:reconnect(options, callback) local datacenter = options.datacenter local delay = self:_setDelay(datacenter) logging.log(logging.INFO, fmt('%s:%d -> Retrying connection in %dms', options.host, options.port, delay)) timer.setTimeout(delay, function() self:createConnection(options, callback) end) end function ConnectionStream:getClient() local client, min_latency = 2147483647, latency for k, v in pairs(self._clients) do latency = self._clients[k]:getLatency() if latency == nil then client = self._clients[k] elseif min_latency > latency then client = self._clients[k] min_latency = latency end end return client end --[[ Move an unauthenticated client to the list of clients that have been authenticated. client - the client. ]]-- function ConnectionStream:_promoteClient(client) local datacenter = client:getDatacenter() client:log(logging.INFO, fmt('Connection has been authenticated to %s', datacenter)) self._clients[datacenter] = client self._unauthedClients[datacenter] = nil end --[[ Create and establish a connection to the endpoint. datacenter - Datacenter name / host alias. host - Hostname. port - Port. callback - Callback called with (err) ]]-- function ConnectionStream:createConnection(options, callback) local opts = misc.merge({ id = self._id, token = self._token, timeout = CONNECT_TIMEOUT }, options) local client = AgentClient:new(opts) client:on('error', function(err) err.host = opts.host err.port = opts.port err.datacenter = opts.datacenter client:destroy() self:reconnect(opts, callback) if err then self:emit('error', err) end end) client:on('timeout', function() logging.log(logging.DEBUG, fmt('%s:%d -> Client Timeout', opts.host, opts.port)) client:destroy() self:reconnect(opts, callback) end) client:on('end', function() self:emit('client_end', client) logging.log(logging.DEBUG, fmt('%s:%d -> Remote endpoint closed the connection', opts.host, opts.port)) client:destroy() self:reconnect(opts, callback) end) client:on('handshake_success', function() self:_promoteClient(client) self._delays[options.datacenter] = 0 client:startPingInterval() self._messages:emit('handshake_success', client) end) client:on('message', function(msg) self._messages:emit('message', client, msg) end) client:connect(function(err) if err then client:destroy() self:reconnect(opts, callback) callback(err) return end client.datacenter = datacenter self._unauthedClients[datacenter] = client callback(); end) return client end local exports = {} exports.ConnectionStream = ConnectionStream return exports
fix getLatency
fix getLatency
Lua
apache-2.0
virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base
e9760b1688a237329ab0b992c7d8b506facf44a6
src/migrations/agreement-tx-counter/migrate.lua
src/migrations/agreement-tx-counter/migrate.lua
local AGREEMENT_DATA = KEYS[1] local PER_AGREEMENT_TX_IDX = KEYS[2] local AGREEMENT_TRANSACTIONS_INDEX = KEYS[3] local AGREEMENT_TRANSACTIONS_DATA = KEYS[4] local AGR_TX_FIELD = ARGV[1] local ARG_AGR_ID_FIELD = ARGV[2] -- step 1. get all transaction ids local txIds = redis.call("SMEMBERS", AGREEMENT_TRANSACTIONS_INDEX) local function isempty(s) return s == nil or s == '' or s == false; end -- step 2. iterate over every tx for i,txId in pairs(txIds) do -- retrieve associated agreement id local txDataKey = AGREEMENT_TRANSACTIONS_DATA .. ":" .. txId local encodedAgreementId = redis.call("HGET", txDataKey, ARG_AGR_ID_FIELD) -- no data for some reason - skip this if isempty(encodedAgreementId) then goto skip_to_next end local agreementId = cjson.decode(encodedAgreementId) local agreementKey = AGREEMENT_DATA .. ":" .. agreementId local perAgreementTxIdxKey = PER_AGREEMENT_TX_IDX .. ":" .. agreementId -- if we are storing this for the first time - increment tx count by 1 if redis.call("SADD", perAgreementTxIdxKey, txId) == 1 then redis.call("HINCRBY", agreementKey, AGR_TX_FIELD, 1) end ::skip_to_next:: end
local AGREEMENT_DATA = KEYS[2] local PER_AGREEMENT_TX_IDX = KEYS[3] local AGREEMENT_TRANSACTIONS_INDEX = KEYS[4] local AGREEMENT_TRANSACTIONS_DATA = KEYS[5] local AGR_TX_FIELD = ARGV[1] local ARG_AGR_ID_FIELD = ARGV[2] -- step 1. get all transaction ids local txIds = redis.call("SMEMBERS", AGREEMENT_TRANSACTIONS_INDEX) local function isempty(s) return s == nil or s == '' or s == false; end -- step 2. iterate over every tx for i,txId in pairs(txIds) do -- retrieve associated agreement id local txDataKey = AGREEMENT_TRANSACTIONS_DATA .. ":" .. txId local encodedAgreementId = redis.call("HGET", txDataKey, ARG_AGR_ID_FIELD) -- no data for some reason - skip this if isempty(encodedAgreementId) == false then local agreementId = cjson.decode(encodedAgreementId) local agreementKey = AGREEMENT_DATA .. ":" .. agreementId local perAgreementTxIdxKey = PER_AGREEMENT_TX_IDX .. ":" .. agreementId -- if we are storing this for the first time - increment tx count by 1 if redis.call("SADD", perAgreementTxIdxKey, txId) == 1 then redis.call("HINCRBY", agreementKey, AGR_TX_FIELD, 1) end end end
fix: migration key & goto statement
fix: migration key & goto statement
Lua
mit
makeomatic/ms-payments
75e0b413f65ab6941fad4b5a1326d6b22da0df56
src/cosy/configuration.lua
src/cosy/configuration.lua
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Scheduler = require "cosy.scheduler" local Layer = require "layeredata" local i18n = I18n.load "cosy.configuration" local layers = { default = Layer.new { name = "default", data = { locale = "en" } }, etc = Layer.new { name = "etc" }, home = Layer.new { name = "home" }, pwd = Layer.new { name = "pwd" }, } layers.whole = Layer.new { name = "whole", data = { __depends__ = { layers.default, layers.etc, layers.home, layers.pwd, }, }, } local Configuration = {} function Configuration.load (t) if type (t) ~= "table" then t = { t } end for _, name in ipairs (t) do require (name .. "-conf") end end local Metatable = {} function Metatable.__index (_, key) return layers.whole [key] end function Metatable.__newindex (_, key, value) layers.whole [key] = value end function Metatable.__div (_, name) return layers [name] end setmetatable (Configuration, Metatable) local files = { etc = "/etc/cosy.conf", home = os.getenv "HOME" .. "/.cosy/cosy.conf", pwd = os.getenv "PWD" .. "/cosy.conf", } if not _G.js then local updater = Scheduler.addthread (function () local Nginx = require "cosy.nginx" local Redis = require "cosy.redis" if not Nginx.directory then return end while true do local redis = Redis () -- http://stackoverflow.com/questions/4006324 local script = { [[ local n = 1000 local keys = redis.call ("keys", ARGV[1]) for i=1, #keys, n do redis.call ("del", unpack (keys, i, math.min (i+n-1, #keys))) end ]] } for name, p in Layer.pairs (Configuration.dependencies) do local url = p [nil] if type (url) == "string" and url:match "^http" then script [#script+1] = ([[ redis.call ("set", "foreign:{{{name}}}", "{{{source}}}") ]]) % { name = name, source = url, } end end script [#script+1] = [[ return true ]] script = table.concat (script) redis:eval (script, 1, "foreign:*") os.execute ([[ find {{{root}}}/cache -type f -delete ]] % { root = Nginx.directory, }) Logger.debug { _ = i18n ["updated"], } Nginx.update () Scheduler.sleep (-math.huge) end end) package.searchers [#package.searchers+1] = function (name) local result, err = io.open (name, "r") if not result then return nil, err end result, err = loadfile (name) if not result then return nil, err end return result, name end for key, name in pairs (files) do local result = Loader.hotswap.try_require (name) if result then Loader.hotswap.on_change ["cosy:configuration"] = function () Scheduler.wakeup (updater) end Logger.debug { _ = i18n ["use"], path = name, locale = Configuration.locale [nil] or "en", } Layer.replacewith (layers [key], result) else Logger.warning { _ = i18n ["skip"], path = name, locale = Configuration.locale [nil] or "en", } end end end return Configuration
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = require "cosy.logger" local Scheduler = require "cosy.scheduler" local Layer = require "layeredata" local i18n = I18n.load "cosy.configuration" local layers = { default = Layer.new { name = "default", data = { locale = "en" } }, etc = Layer.new { name = "etc" }, home = Layer.new { name = "home" }, pwd = Layer.new { name = "pwd" }, } layers.whole = Layer.new { name = "whole", data = { __depends__ = { layers.default, layers.etc, layers.home, layers.pwd, }, }, } local Configuration = {} function Configuration.load (t) if type (t) ~= "table" then t = { t } end for _, name in ipairs (t) do require (name .. "-conf") end end local Metatable = {} function Metatable.__index (_, key) return layers.whole [key] end function Metatable.__newindex (_, key, value) layers.whole [key] = value end function Metatable.__div (_, name) return layers [name] end setmetatable (Configuration, Metatable) local files = { etc = "/etc/cosy.conf", home = os.getenv "HOME" .. "/.cosy/cosy.conf", pwd = os.getenv "PWD" .. "/cosy.conf", } if not _G.js then local updater = Scheduler.addthread (function () local Nginx = require "cosy.nginx" local Redis = require "cosy.redis" while true do local redis = Redis () -- http://stackoverflow.com/questions/4006324 local script = { [[ local n = 1000 local keys = redis.call ("keys", ARGV[1]) for i=1, #keys, n do redis.call ("del", unpack (keys, i, math.min (i+n-1, #keys))) end ]] } for name, p in Layer.pairs (Configuration.dependencies) do local url = p [nil] if type (url) == "string" and url:match "^http" then script [#script+1] = ([[ redis.call ("set", "foreign:{{{name}}}", "{{{source}}}") ]]) % { name = name, source = url, } end end script [#script+1] = [[ return true ]] script = table.concat (script) redis:eval (script, 1, "foreign:*") os.execute ([[ if [ -d {{{root}}}/cache ] then find {{{root}}}/cache -type f -delete fi ]] % { root = Configuration.http.directory [nil], }) Logger.debug { _ = i18n ["updated"], } Nginx.update () Scheduler.sleep (-math.huge) end end) package.searchers [#package.searchers+1] = function (name) local result, err = io.open (name, "r") if not result then return nil, err end result, err = loadfile (name) if not result then return nil, err end return result, name end for key, name in pairs (files) do local result = Loader.hotswap.try_require (name) if result then Loader.hotswap.on_change ["cosy:configuration"] = function () Scheduler.wakeup (updater) end Logger.debug { _ = i18n ["use"], path = name, locale = Configuration.locale [nil] or "en", } Layer.replacewith (layers [key], result) else Logger.warning { _ = i18n ["skip"], path = name, locale = Configuration.locale [nil] or "en", } end end end return Configuration
Fix nginx forwards.
Fix nginx forwards.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
8cad664aade89612f67dd99987fa036606c453e7
src/luarocks/tools/tar.lua
src/luarocks/tools/tar.lua
--- A pure-Lua implementation of untar (unpacking .tar archives) --module("luarocks.tools.tar", package.seeall) local tar = {} local fs = require("luarocks.fs") local dir = require("luarocks.dir") local util = require("luarocks.util") local blocksize = 512 local function get_typeflag(flag) if flag == "0" or flag == "\0" then return "file" elseif flag == "1" then return "link" elseif flag == "2" then return "symlink" -- "reserved" in POSIX, "symlink" in GNU elseif flag == "3" then return "character" elseif flag == "4" then return "block" elseif flag == "5" then return "directory" elseif flag == "6" then return "fifo" elseif flag == "7" then return "contiguous" -- "reserved" in POSIX, "contiguous" in GNU elseif flag == "x" then return "next file" elseif flag == "g" then return "global extended header" elseif flag == "L" then return "long name" elseif flag == "K" then return "long link name" end return "unknown" end local function octal_to_number(octal) local exp = 0 local number = 0 for i = #octal,1,-1 do local digit = tonumber(octal:sub(i,i)) if not digit then break end number = number + (digit * 8^exp) exp = exp + 1 end return number end local function checksum_header(block) local sum = 256 for i = 1,148 do sum = sum + block:byte(i) end for i = 157,500 do sum = sum + block:byte(i) end return sum end local function nullterm(s) return s:match("^[^%z]*") end local function read_header_block(block) local header = {} header.name = nullterm(block:sub(1,100)) header.mode = nullterm(block:sub(101,108)) header.uid = octal_to_number(nullterm(block:sub(109,116))) header.gid = octal_to_number(nullterm(block:sub(117,124))) header.size = octal_to_number(nullterm(block:sub(125,136))) header.mtime = octal_to_number(nullterm(block:sub(137,148))) header.chksum = octal_to_number(nullterm(block:sub(149,156))) header.typeflag = get_typeflag(block:sub(157,157)) header.linkname = nullterm(block:sub(158,257)) header.magic = block:sub(258,263) header.version = block:sub(264,265) header.uname = nullterm(block:sub(266,297)) header.gname = nullterm(block:sub(298,329)) header.devmajor = octal_to_number(nullterm(block:sub(330,337))) header.devminor = octal_to_number(nullterm(block:sub(338,345))) header.prefix = block:sub(346,500) if header.magic ~= "ustar " and header.magic ~= "ustar\0" then return false, "Invalid header magic "..header.magic end if header.version ~= "00" and header.version ~= " \0" then return false, "Unknown version "..header.version end if not checksum_header(block) == header.chksum then return false, "Failed header checksum" end return header end function tar.untar(filename, destdir) assert(type(filename) == "string") assert(type(destdir) == "string") local tar_handle = io.open(filename, "r") if not tar_handle then return nil, "Error opening file "..filename end local long_name, long_link_name while true do local block repeat block = tar_handle:read(blocksize) until (not block) or checksum_header(block) > 256 if not block then break end local header, err = read_header_block(block) if not header then util.printerr(err) end local file_data = tar_handle:read(math.ceil(header.size / blocksize) * blocksize):sub(1,header.size) if header.typeflag == "long name" then long_name = nullterm(file_data) elseif header.typeflag == "long link name" then long_link_name = nullterm(file_data) else if long_name then header.name = long_name long_name = nil end if long_link_name then header.name = long_link_name long_link_name = nil end end local pathname = dir.path(destdir, header.name) if header.typeflag == "directory" then local ok, err = fs.make_dir(pathname) if not ok then return nil, err end elseif header.typeflag == "file" then local dirname = dir.dir_name(pathname) if dirname ~= "" then local ok, err = fs.make_dir(dirname) if not ok then return nil, err end end local file_handle = io.open(pathname, "wb") file_handle:write(file_data) file_handle:close() fs.set_time(pathname, header.mtime) if fs.chmod then fs.chmod(pathname, header.mode) end end --[[ for k,v in pairs(header) do util.printout("[\""..tostring(k).."\"] = "..(type(v)=="number" and v or "\""..v:gsub("%z", "\\0").."\"")) end util.printout() --]] end return true end return tar
--- A pure-Lua implementation of untar (unpacking .tar archives) --module("luarocks.tools.tar", package.seeall) local tar = {} local fs = require("luarocks.fs") local dir = require("luarocks.dir") local util = require("luarocks.util") local blocksize = 512 local function get_typeflag(flag) if flag == "0" or flag == "\0" then return "file" elseif flag == "1" then return "link" elseif flag == "2" then return "symlink" -- "reserved" in POSIX, "symlink" in GNU elseif flag == "3" then return "character" elseif flag == "4" then return "block" elseif flag == "5" then return "directory" elseif flag == "6" then return "fifo" elseif flag == "7" then return "contiguous" -- "reserved" in POSIX, "contiguous" in GNU elseif flag == "x" then return "next file" elseif flag == "g" then return "global extended header" elseif flag == "L" then return "long name" elseif flag == "K" then return "long link name" end return "unknown" end local function octal_to_number(octal) local exp = 0 local number = 0 for i = #octal,1,-1 do local digit = tonumber(octal:sub(i,i)) if digit then number = number + (digit * 8^exp) exp = exp + 1 end end return number end local function checksum_header(block) local sum = 256 for i = 1,148 do sum = sum + block:byte(i) end for i = 157,500 do sum = sum + block:byte(i) end return sum end local function nullterm(s) return s:match("^[^%z]*") end local function read_header_block(block) local header = {} header.name = nullterm(block:sub(1,100)) header.mode = nullterm(block:sub(101,108)):gsub(" ", "") header.uid = octal_to_number(nullterm(block:sub(109,116))) header.gid = octal_to_number(nullterm(block:sub(117,124))) header.size = octal_to_number(nullterm(block:sub(125,136))) print("{"..block:sub(125,136).."}", "{"..nullterm(block:sub(125,136)).."}", "{"..octal_to_number(nullterm(block:sub(125,136))).."}", header.size) header.mtime = octal_to_number(nullterm(block:sub(137,148))) header.chksum = octal_to_number(nullterm(block:sub(149,156))) header.typeflag = get_typeflag(block:sub(157,157)) header.linkname = nullterm(block:sub(158,257)) header.magic = block:sub(258,263) header.version = block:sub(264,265) header.uname = nullterm(block:sub(266,297)) header.gname = nullterm(block:sub(298,329)) header.devmajor = octal_to_number(nullterm(block:sub(330,337))) header.devminor = octal_to_number(nullterm(block:sub(338,345))) header.prefix = block:sub(346,500) if header.magic ~= "ustar " and header.magic ~= "ustar\0" then return false, "Invalid header magic "..header.magic end if header.version ~= "00" and header.version ~= " \0" then return false, "Unknown version "..header.version end if not checksum_header(block) == header.chksum then return false, "Failed header checksum" end return header end function tar.untar(filename, destdir) assert(type(filename) == "string") assert(type(destdir) == "string") local tar_handle = io.open(filename, "r") if not tar_handle then return nil, "Error opening file "..filename end local long_name, long_link_name while true do local block repeat block = tar_handle:read(blocksize) until (not block) or checksum_header(block) > 256 if not block then break end local header, err = read_header_block(block) if not header then util.printerr(err) return nil, err end local file_data = tar_handle:read(math.ceil(header.size / blocksize) * blocksize):sub(1,header.size) if header.typeflag == "long name" then long_name = nullterm(file_data) elseif header.typeflag == "long link name" then long_link_name = nullterm(file_data) else if long_name then header.name = long_name long_name = nil end if long_link_name then header.name = long_link_name long_link_name = nil end end local pathname = dir.path(destdir, header.name) if header.typeflag == "directory" then local ok, err = fs.make_dir(pathname) if not ok then return nil, err end elseif header.typeflag == "file" then local dirname = dir.dir_name(pathname) if dirname ~= "" then local ok, err = fs.make_dir(dirname) if not ok then return nil, err end end local file_handle = io.open(pathname, "wb") file_handle:write(file_data) file_handle:close() fs.set_time(pathname, header.mtime) if fs.chmod then fs.chmod(pathname, header.mode) end end --[[ for k,v in pairs(header) do util.printout("[\""..tostring(k).."\"] = "..(type(v)=="number" and v or "\""..v:gsub("%z", "\\0").."\"")) end util.printout() --]] end tar_handle:close() return true end return tar
Fix merge conflict.
Fix merge conflict.
Lua
mit
luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,tarantool/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks
29b924284be0847fb3ad24aa50c92af2bfdcbdad
core/componentmanager.lua
core/componentmanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local core_route_stanza = core_route_stanza; local jid_split = require "util.jid".split; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; prosody.events.add_handler("server-starting", function () core_route_stanza = _G.core_route_stanza; end); module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" then core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end local components_loaded_once; function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = { type = "component", host = host, connected = false, s2sout = {}, events = events_new() }; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza)); end end function create_component(host, component) -- TODO check for host well-formedness return { type = "component", host = host, connected = true, s2sout = {}, events = events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end -- FIXME only load for a.b.c if b.c has dialback, and/or check in config modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local log = require "util.logger".init("componentmanager"); local configmanager = require "core.configmanager"; local modulemanager = require "core.modulemanager"; local core_route_stanza = core_route_stanza; local jid_split = require "util.jid".split; local events_new = require "util.events".new; local st = require "util.stanza"; local hosts = hosts; local pairs, type, tostring = pairs, type, tostring; local components = {}; local disco_items = require "util.multitable".new(); local NULL = {}; prosody.events.add_handler("server-starting", function () core_route_stanza = _G.core_route_stanza; end); module "componentmanager" local function default_component_handler(origin, stanza) log("warn", "Stanza being handled by default component, bouncing error"); if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then core_route_stanza(nil, st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable")); end end local components_loaded_once; function load_enabled_components(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then hosts[host] = { type = "component", host = host, connected = false, s2sout = {}, events = events_new() }; components[host] = default_component_handler; local ok, err = modulemanager.load(host, host_config.core.component_module); if not ok then log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err)); else log("debug", "Activated %s component: %s", host_config.core.component_module, host); end end end end prosody.events.add_handler("server-starting", load_enabled_components); function handle_stanza(origin, stanza) local node, host = jid_split(stanza.attr.to); local component = nil; if host then if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server if not component then component = components[host]; end end if component then log("debug", "%s stanza being handled by component: %s", stanza.name, host); component(origin, stanza, hosts[host]); else log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza)); end end function create_component(host, component) -- TODO check for host well-formedness return { type = "component", host = host, connected = true, s2sout = {}, events = events_new() }; end function register_component(host, component, session) if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then local old_events = hosts[host] and hosts[host].events; components[host] = component; hosts[host] = session or create_component(host, component); -- Add events object if not already one if not hosts[host].events then hosts[host].events = old_events or events_new(); end -- add to disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:set(host:sub(host:find(".", 1, true)+1), host, true); end -- FIXME only load for a.b.c if b.c has dialback, and/or check in config modulemanager.load(host, "dialback"); log("debug", "component added: "..host); return session or hosts[host]; else log("error", "Attempt to set component for existing host: "..host); end end function deregister_component(host) if components[host] then modulemanager.unload(host, "dialback"); hosts[host].connected = nil; local host_config = configmanager.getconfig()[host]; if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then -- Set default handler components[host] = default_component_handler; else -- Component not in config, or disabled, remove hosts[host] = nil; components[host] = nil; end -- remove from disco_items if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then disco_items:remove(host:sub(host:find(".", 1, true)+1), host); end log("debug", "component removed: "..host); return true; else log("error", "Attempt to remove component for non-existing host: "..host); end end function set_component_handler(host, handler) components[host] = handler; end function get_children(host) return disco_items:get(host) or NULL; end return _M;
ComponentManager: Fixed: Default handler sent error replies on result stanzas.
ComponentManager: Fixed: Default handler sent error replies on result stanzas.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
20eab8df3ea23ea79bfcd8e3d250f7d5b2985d95
spec/unit/statics_spec.lua
spec/unit/statics_spec.lua
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true nginx_plus_status: false # Cassandra cache configuration cache: expiration: 5 # in seconds nginx: | worker_processes auto; error_log logs/error.log info; daemon on; # Set "worker_rlimit_nofile" to a high value # worker_rlimit_nofile 65536; env KONG_CONF; events { # Set "worker_connections" to a high value worker_connections 1024; } http { resolver 8.8.8.8; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; lua_socket_log_errors off; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should parse a correct configuration", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # Sends anonymous error reports send_anonymous_reports: true nginx_plus_status: false # Cassandra cache configuration cache: expiration: 5 # in seconds # Nginx configuration nginx: | worker_processes auto; error_log logs/error.log info; daemon on; worker_rlimit_nofile {{auto_worker_rlimit_nofile}}; env KONG_CONF; events { worker_connections {{auto_worker_connections}}; multi_accept on; } http { resolver 8.8.8.8; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; lua_socket_log_errors off; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
fixing test
fixing test
Lua
apache-2.0
isdom/kong,Kong/kong,kyroskoh/kong,li-wl/kong,xvaara/kong,smanolache/kong,salazar/kong,ejoncas/kong,streamdataio/kong,Kong/kong,ind9/kong,jebenexer/kong,Kong/kong,shiprabehera/kong,Vermeille/kong,beauli/kong,vzaramel/kong,ccyphers/kong,Mashape/kong,ajayk/kong,rafael/kong,jerizm/kong,icyxp/kong,isdom/kong,streamdataio/kong,vzaramel/kong,akh00/kong,ind9/kong,kyroskoh/kong,rafael/kong,ejoncas/kong
db64a359eca14db6372d6273ab091db16c5749f4
core/configmanager.lua
core/configmanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type = setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type; local eventmanager = require "core.eventmanager"; module "configmanager" local parsers = {}; local config = { ["*"] = { core = {} } }; local global_config = config["*"]; -- When host not found, use global setmetatable(config, { __index = function () return global_config; end}); local host_mt = { __index = global_config }; -- When key not found in section, check key in global's section function section_mt(section_name) return { __index = function (t, k) local section = rawget(global_config, section_name); if not section then return nil; end return section[k]; end }; end function getconfig() return config; end function get(host, section, key) local sec = config[host][section]; if sec then return sec[key]; end return nil; end function set(host, section, key, value) if host and section and key then local hostconfig = rawget(config, host); if not hostconfig then hostconfig = rawset(config, host, setmetatable({}, host_mt))[host]; end if not rawget(hostconfig, section) then hostconfig[section] = setmetatable({}, section_mt(section)); end hostconfig[section][key] = value; return true; end return false; end function load(filename, format) format = format or filename:match("%w+$"); if parsers[format] and parsers[format].load then local f, err = io.open(filename); if f then local ok, err = parsers[format].load(f:read("*a")); f:close(); if ok then eventmanager.fire_event("config-reloaded", { filename = filename, format = format }); end return ok, "parser", err; end return f, "file", err; end if not format then return nil, "file", "no parser specified"; else return nil, "file", "no parser for "..(format); end end function save(filename, format) end function addparser(format, parser) if format and parser then parsers[format] = parser; end end -- Built-in Lua parser do local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable; local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring; parsers.lua = {}; function parsers.lua.load(data) local env; -- The ' = true' are needed so as not to set off __newindex when we assign the functions below env = setmetatable({ Host = true; host = true; Component = true, component = true, Include = true, include = true, RunScript = dofile }, { __index = function (t, k) return rawget(_G, k) or function (settings_table) config[__currenthost or "*"][k] = settings_table; end; end, __newindex = function (t, k, v) set(env.__currenthost or "*", "core", k, v); end}); rawset(env, "__currenthost", "*") -- Default is global function env.Host(name) rawset(env, "__currenthost", name); -- Needs at least one setting to logically exist :) set(name or "*", "core", "defined", true); end env.host = env.Host; function env.Component(name) set(name, "core", "component_module", "component"); -- Don't load the global modules by default set(name, "core", "load_global_modules", false); rawset(env, "__currenthost", name); return function (module) if type(module) == "string" then set(name, "core", "component_module", module); end end end env.component = env.Component; function env.Include(file) local f, err = io.open(file); if f then local data = f:read("*a"); local ok, err = parsers.lua.load(data); if not ok then error(err:gsub("%[string.-%]", file), 0); end end if not f then error("Error loading included "..file..": "..err, 0); end return f, err; end env.include = env.Include; local chunk, err = loadstring(data); if not chunk then return nil, err; end setfenv(chunk, env); local ok, err = pcall(chunk); if not ok then return nil, err; end return true; end end return _M;
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type = setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type; local eventmanager = require "core.eventmanager"; module "configmanager" local parsers = {}; local config = { ["*"] = { core = {} } }; local global_config = config["*"]; -- When host not found, use global setmetatable(config, { __index = function () return global_config; end}); local host_mt = { __index = global_config }; -- When key not found in section, check key in global's section function section_mt(section_name) return { __index = function (t, k) local section = rawget(global_config, section_name); if not section then return nil; end return section[k]; end }; end function getconfig() return config; end function get(host, section, key) local sec = config[host][section]; if sec then return sec[key]; end return nil; end function set(host, section, key, value) if host and section and key then local hostconfig = rawget(config, host); if not hostconfig then hostconfig = rawset(config, host, setmetatable({}, host_mt))[host]; end if not rawget(hostconfig, section) then hostconfig[section] = setmetatable({}, section_mt(section)); end hostconfig[section][key] = value; return true; end return false; end function load(filename, format) format = format or filename:match("%w+$"); if parsers[format] and parsers[format].load then local f, err = io.open(filename); if f then local ok, err = parsers[format].load(f:read("*a"), filename); f:close(); if ok then eventmanager.fire_event("config-reloaded", { filename = filename, format = format }); end return ok, "parser", err; end return f, "file", err; end if not format then return nil, "file", "no parser specified"; else return nil, "file", "no parser for "..(format); end end function save(filename, format) end function addparser(format, parser) if format and parser then parsers[format] = parser; end end -- Built-in Lua parser do local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable; local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring; parsers.lua = {}; function parsers.lua.load(data, filename) local env; -- The ' = true' are needed so as not to set off __newindex when we assign the functions below env = setmetatable({ Host = true; host = true; Component = true, component = true, Include = true, include = true, RunScript = dofile }, { __index = function (t, k) return rawget(_G, k) or function (settings_table) config[__currenthost or "*"][k] = settings_table; end; end, __newindex = function (t, k, v) set(env.__currenthost or "*", "core", k, v); end}); rawset(env, "__currenthost", "*") -- Default is global function env.Host(name) rawset(env, "__currenthost", name); -- Needs at least one setting to logically exist :) set(name or "*", "core", "defined", true); end env.host = env.Host; function env.Component(name) set(name, "core", "component_module", "component"); -- Don't load the global modules by default set(name, "core", "load_global_modules", false); rawset(env, "__currenthost", name); return function (module) if type(module) == "string" then set(name, "core", "component_module", module); end end end env.component = env.Component; function env.Include(file) local f, err = io.open(file); if f then local data = f:read("*a"); local ok, err = parsers.lua.load(data, file); if not ok then error(err:gsub("%[string.-%]", file), 0); end end if not f then error("Error loading included "..file..": "..err, 0); end return f, err; end env.include = env.Include; local chunk, err = loadstring(data, "@"..filename); if not chunk then return nil, err; end setfenv(chunk, env); local ok, err = pcall(chunk); if not ok then return nil, err; end return true; end end return _M;
configmanager: Assign a chunk name to config files loaded using the default config loader (fixes issues with some diagnostic tools).
configmanager: Assign a chunk name to config files loaded using the default config loader (fixes issues with some diagnostic tools).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
533bbb172c43b9f75d4caf7219a003f4a3efd724
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" local netstate = luci.model.uci.cursor_state():get_all("network") m = Map("network", translate("Interfaces")) local created local netstat = sys.net.deviceinfo() s = m:section(TypedSection, "interface", "") s.addremove = true s.anonymous = false s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s" s.template = "cbi/tblsection" s.override_scheme = true function s.filter(self, section) return section ~= "loopback" and section end function s.create(self, section) if TypedSection.create(self, section) then created = section else self.invalid_cts = true end end function s.parse(self, ...) TypedSection.parse(self, ...) if created then m.uci:save("network") luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network") .. "/" .. created) end end up = s:option(Flag, "up") function up.cfgvalue(self, section) return netstate[section] and netstate[section].up or "0" end function up.write(self, section, value) local call if value == "1" then call = "ifup" elseif value == "0" then call = "ifdown" end os.execute(call .. " " .. section .. " >/dev/null 2>&1") end ifname = s:option(DummyValue, "ifname", translate("Device")) function ifname.cfgvalue(self, section) return netstate[section] and netstate[section].ifname end ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan") if luci.model.uci.cursor():load("firewall") then zone = s:option(DummyValue, "_zone", translate("Zone")) zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones") function zone.cfgvalue(self, section) return table.concat(wa.network_get_zones(section) or { "-" }, ", ") end end hwaddr = s:option(DummyValue, "_hwaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address")) function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" local mac = fs.readfile("/sys/class/net/" .. ix .. "/address") if not mac then mac = luci.util.exec("ifconfig " .. ix) mac = mac and mac:match(" ([A-F0-9:]+)%s*\n") end if mac and #mac > 0 then return mac:upper() end return "?" end ipaddr = s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" .. "-Address")) function ipaddr.cfgvalue(self, section) return table.concat(wa.network_get_addresses(section), ", ") end txrx = s:option(DummyValue, "_txrx", translate("Traffic"), translate("transmitted / received")) function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and wa.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and wa.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err", translate("Errors"), translate("TX / RX")) function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" local netstate = luci.model.uci.cursor_state():get_all("network") m = Map("network", translate("Interfaces")) local created local netstat = sys.net.deviceinfo() s = m:section(TypedSection, "interface", "") s.addremove = true s.anonymous = false s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s" s.template = "cbi/tblsection" s.override_scheme = true function s.filter(self, section) return section ~= "loopback" and section end function s.create(self, section) if TypedSection.create(self, section) then created = section else self.invalid_cts = true end end function s.parse(self, ...) TypedSection.parse(self, ...) if created then m.uci:save("network") luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network") .. "/" .. created) end end up = s:option(Flag, "up") function up.cfgvalue(self, section) return netstate[section] and netstate[section].up or "0" end function up.write(self, section, value) local call if value == "1" then call = "ifup" elseif value == "0" then call = "ifdown" end os.execute(call .. " " .. section .. " >/dev/null 2>&1") end ifname = s:option(DummyValue, "ifname", translate("Device")) function ifname.cfgvalue(self, section) return netstate[section] and netstate[section].ifname end ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan") if luci.model.uci.cursor():load("firewall") then zone = s:option(DummyValue, "_zone", translate("Zone")) zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones") function zone.cfgvalue(self, section) return table.concat(wa.network_get_zones(section) or { "-" }, ", ") end end hwaddr = s:option(DummyValue, "_hwaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address")) function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" ix = (type(ix) == "table") and ix[1] or ix local mac = fs.readfile("/sys/class/net/" .. ix .. "/address") if not mac then mac = luci.util.exec("ifconfig " .. ix) mac = mac and mac:match(" ([A-F0-9:]+)%s*\n") end if mac and #mac > 0 then return mac:upper() end return "?" end ipaddr = s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" .. "-Address")) function ipaddr.cfgvalue(self, section) return table.concat(wa.network_get_addresses(section), ", ") end txrx = s:option(DummyValue, "_txrx", translate("Traffic"), translate("transmitted / received")) function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and wa.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and wa.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err", translate("Errors"), translate("TX / RX")) function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end return m
modules/admin-full: fix crash on network interface overview page
modules/admin-full: fix crash on network interface overview page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6099 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Canaan-Creative/luci,Flexibity/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,jschmidlapp/luci,freifunk-gluon/luci,phi-psi/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,stephank/luci,freifunk-gluon/luci,vhpham80/luci,vhpham80/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,Flexibity/luci,vhpham80/luci,stephank/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,jschmidlapp/luci,vhpham80/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,Canaan-Creative/luci,8devices/carambola2-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,stephank/luci,Canaan-Creative/luci,gwlim/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,yeewang/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,ch3n2k/luci,gwlim/luci,8devices/carambola2-luci,stephank/luci,yeewang/openwrt-luci,8devices/carambola2-luci,jschmidlapp/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,stephank/luci,Flexibity/luci,vhpham80/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,8devices/carambola2-luci,vhpham80/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,phi-psi/luci,yeewang/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,Flexibity/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,Flexibity/luci,saraedum/luci-packages-old,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ch3n2k/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,stephank/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,freifunk-gluon/luci
e837c1ef04818a1acfe283e9853920b9bb8e2739
sslobby/gamemode/init.lua
sslobby/gamemode/init.lua
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_scoreboard.lua") AddCSLuaFile("modules/sh_link.lua") AddCSLuaFile("modules/cl_link.lua") AddCSLuaFile("modules/sh_chairs.lua") AddCSLuaFile("modules/cl_chairs.lua") AddCSLuaFile("modules/cl_worldpicker.lua") AddCSLuaFile("modules/sh_minigame.lua") AddCSLuaFile("modules/cl_minigame.lua") AddCSLuaFile("modules/cl_worldpanel.lua") AddCSLuaFile("modules/sh_leaderboard.lua") AddCSLuaFile("modules/cl_leaderboard.lua") AddCSLuaFile("modules/sh_sound.lua") include("shared.lua") include("player_class/player_lobby.lua") include("player_extended.lua") include("modules/sv_socket.lua") include("modules/sh_link.lua") include("modules/sv_link.lua") include("modules/sh_chairs.lua") include("modules/sv_chairs.lua") include("modules/sv_worldpicker.lua") include("modules/sh_minigame.lua") include("modules/sv_minigame.lua") include("modules/sh_leaderboard.lua") include("modules/sv_leaderboard.lua") include("modules/sv_elevator.lua") include("modules/sh_sound.lua") -------------------------------------------------- -- -------------------------------------------------- function GM:InitPostEntity() self.spawnPoints = {lounge = {}} local spawns = ents.FindByClass("info_player_spawn") for k, entity in pairs(spawns) do if (entity.lounge) then table.insert(self.spawnPoints.lounge, entity) else if (!entity.minigames) then table.insert(self.spawnPoints, entity) end end end local slotMachines = ents.FindByClass("prop_physics_multiplayer") for k, entity in pairs(slotMachines) do if (IsValid(entity)) then local model = string.lower(entity:GetModel()) if (model == "models/sam/slotmachine.mdl") then local position, angles = entity:GetPos(), entity:GetAngles() local slotMachine = ents.Create("slot_machine") slotMachine:SetPos(position) slotMachine:SetAngles(angles) slotMachine:Spawn() entity:Remove() end end end timer.Simple(5,function() socket.SetupHost("192.168.1.152", 40000) timer.Simple(2,function() socket.AddServer("192.168.1.152", 40001) end) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerInitialSpawn(player) self.BaseClass:PlayerInitialSpawn(player) player:SetTeam(TEAM_READY) timer.Simple(0.4,function() for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do SS.Lobby.LeaderBoard.Network(i, player) end SS.Lobby.Minigame:UpdateScreen(player) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSpawn(player) player_manager.SetPlayerClass(ply, "player_sslobby") self.BaseClass:PlayerSpawn(player) player:SetModel("models/player/group01/male_01.mdl") player:SetJumpPower(205) player:SetRunSpeed(350) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerLoadout(player) player:StripWeapons() player:RemoveAllAmmo() SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player) end -------------------------------------------------- -- -------------------------------------------------- function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable ) local Pos = spawnpointent:GetPos() -- Note that we're searching the default hull size here for a player in the way of our spawning. -- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job -- (HL2DM kills everything within a 128 unit radius) local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) ) if ( pl:Team() == TEAM_SPECTATOR ) then return true end local Blockers = 0 for k, v in pairs( Ents ) do if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then Blockers = Blockers + 1 if ( bMakeSuitable ) then v:Kill() end end end if ( bMakeSuitable ) then return true end if ( Blockers > 0 ) then return false end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSelectSpawn(player) local spawnPoint = self.spawnPoints.lounge if (player:Team() > TEAM_READY) then if (player:IsPlayingMinigame() && player.minigame) then spawnPoint = player.minigame:GetSpawnPoints(player) else spawnPoint = self.spawnPoints end end for i = 1, #spawnPoint do local entity = spawnPoint[i] local suitAble = self:IsSpawnpointSuitable(player, entity, false) if (suitAble) then return entity end end spawnPoint = table.Random(spawnPoint) return spawnPoint end -------------------------------------------------- -- -------------------------------------------------- function GM:KeyPress(player, key) if (key == IN_USE) then local trace = player:EyeTrace(84) if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then local canSlap = player:CanSlap(trace.Entity) if (canSlap) then player:Slap(trace.Entity) end end end SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key) end -------------------------------------------------- -- -------------------------------------------------- function GM:DoPlayerDeath(victim, inflictor, dmginfo) SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo) return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo) end -------------------------------------------------- -- -------------------------------------------------- function GM:CanPlayerSuicide(player) local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player) if (bool != nil) then return bool end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:EntityKeyValue(entity, key, value) if (IsValid(entity)) then local class = entity:GetClass() if (class == "func_door" and key == "hammerid") then entity.id = tonumber(value) end end end -------------------------------------------------- -- -------------------------------------------------- function GM:ShowTeam(player) player:SetTeam(TEAM_READY) player:Spawn() end -- dev concommand.Add("poo",function() RunConsoleCommand("bot") timer.Simple(0,function() for k, bot in pairs(player.GetBots()) do bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE)) bot:SetPos(Vector(-607.938110, -447.018799, 16.031250)) bot:Freeze(true) end end) end)
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_scoreboard.lua") AddCSLuaFile("modules/sh_link.lua") AddCSLuaFile("modules/cl_link.lua") AddCSLuaFile("modules/sh_chairs.lua") AddCSLuaFile("modules/cl_chairs.lua") AddCSLuaFile("modules/cl_worldpicker.lua") AddCSLuaFile("modules/sh_minigame.lua") AddCSLuaFile("modules/cl_minigame.lua") AddCSLuaFile("modules/cl_worldpanel.lua") AddCSLuaFile("modules/sh_leaderboard.lua") AddCSLuaFile("modules/cl_leaderboard.lua") AddCSLuaFile("modules/sh_sound.lua") include("shared.lua") include("player_class/player_lobby.lua") include("player_extended.lua") include("modules/sv_socket.lua") include("modules/sh_link.lua") include("modules/sv_link.lua") include("modules/sh_chairs.lua") include("modules/sv_chairs.lua") include("modules/sv_worldpicker.lua") include("modules/sh_minigame.lua") include("modules/sv_minigame.lua") include("modules/sh_leaderboard.lua") include("modules/sv_leaderboard.lua") include("modules/sv_elevator.lua") include("modules/sh_sound.lua") -------------------------------------------------- -- -------------------------------------------------- function GM:InitPostEntity() self.spawnPoints = {lounge = {}} local spawns = ents.FindByClass("info_player_spawn") for k, entity in pairs(spawns) do if (entity.lounge) then table.insert(self.spawnPoints.lounge, entity) else if (!entity.minigames) then table.insert(self.spawnPoints, entity) end end end local slotMachines = ents.FindByClass("prop_physics_multiplayer") for k, entity in pairs(slotMachines) do if (IsValid(entity)) then local model = string.lower(entity:GetModel()) if (model == "models/sam/slotmachine.mdl") then local position, angles = entity:GetPos(), entity:GetAngles() local slotMachine = ents.Create("slot_machine") slotMachine:SetPos(position) slotMachine:SetAngles(angles) slotMachine:Spawn() entity:Remove() end end end timer.Simple(5,function() socket.SetupHost("192.168.1.152", 40000) timer.Simple(2,function() socket.AddServer("192.168.1.152", 40001) end) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerInitialSpawn(player) self.BaseClass:PlayerInitialSpawn(player) player:SetTeam(TEAM_READY) timer.Simple(0.4,function() for i = LEADERBOARD_DAILY, LEADERBOARD_ALLTIME_10 do SS.Lobby.LeaderBoard.Network(i, player) end SS.Lobby.Minigame:UpdateScreen(player) end) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSpawn(player) player_manager.SetPlayerClass(ply, "player_sslobby") self.BaseClass:PlayerSpawn(player) player:SetJumpPower(205) player:SetRunSpeed(350) end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerLoadout(player) player:StripWeapons() player:RemoveAllAmmo() SS.Lobby.Minigame:CallWithPlayer("PlayerLoadout", player) end -------------------------------------------------- -- -------------------------------------------------- function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable ) local Pos = spawnpointent:GetPos() -- Note that we're searching the default hull size here for a player in the way of our spawning. -- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job -- (HL2DM kills everything within a 128 unit radius) local Ents = ents.FindInBox( Pos + Vector( -14, -14, 0 ), Pos + Vector( 14, 14, 64 ) ) if ( pl:Team() == TEAM_SPECTATOR ) then return true end local Blockers = 0 for k, v in pairs( Ents ) do if ( IsValid( v ) && v:GetClass() == "player" && v:Alive() ) then Blockers = Blockers + 1 if ( bMakeSuitable ) then v:Kill() end end end if ( bMakeSuitable ) then return true end if ( Blockers > 0 ) then return false end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:PlayerSelectSpawn(player) local spawnPoint = self.spawnPoints.lounge if (player:Team() > TEAM_READY) then if (player:IsPlayingMinigame() && player.minigame) then spawnPoint = player.minigame:GetSpawnPoints(player) else spawnPoint = self.spawnPoints end end for i = 1, #spawnPoint do local entity = spawnPoint[i] local suitAble = self:IsSpawnpointSuitable(player, entity, false) if (suitAble) then return entity end end spawnPoint = table.Random(spawnPoint) return spawnPoint end -------------------------------------------------- -- -------------------------------------------------- function GM:KeyPress(player, key) if (key == IN_USE) then local trace = player:EyeTrace(84) if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then local canSlap = player:CanSlap(trace.Entity) if (canSlap) then player:Slap(trace.Entity) end end end SS.Lobby.Minigame:CallWithPlayer("KeyPress", player, key) end -------------------------------------------------- -- -------------------------------------------------- function GM:DoPlayerDeath(victim, inflictor, dmginfo) SS.Lobby.Minigame:CallWithPlayer("DoPlayerDeath", victim, inflictor, dmginfo) return self.BaseClass:DoPlayerDeath(victim, inflictor, dmginfo) end -------------------------------------------------- -- -------------------------------------------------- function GM:CanPlayerSuicide(player) local bool = SS.Lobby.Minigame:CallWithPlayer("CanPlayerSuicide", player) if (bool != nil) then return bool end return true end -------------------------------------------------- -- -------------------------------------------------- function GM:EntityKeyValue(entity, key, value) if (IsValid(entity)) then local class = entity:GetClass() if (class == "func_door" and key == "hammerid") then entity.id = tonumber(value) end end end -------------------------------------------------- -- -------------------------------------------------- function GM:ShowTeam(player) player:SetTeam(TEAM_READY) player:Spawn() end -- dev concommand.Add("poo",function() RunConsoleCommand("bot") timer.Simple(0,function() for k, bot in pairs(player.GetBots()) do bot:SetTeam(math.random(TEAM_RED,TEAM_ORANGE)) bot:SetPos(Vector(-607.938110, -447.018799, 16.031250)) bot:Freeze(true) end end) end)
I think I broke this, fixed.
I think I broke this, fixed.
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
fb7b825586e215d4ae7a869d50bf03621f469d06
demos/bench.lua
demos/bench.lua
--[[ export LUA_CPATH='./env/lib/lua/5.1/?.so' export LUA_PATH='./demos/?.lua;./src/?.lua;./env/share/lua/5.1/?.lua;./env/share/lua/5.1/?/init.lua' time ../other/luajit-2.0/src/luajit demos/bench.lua --]] local Request = require('http.request') local ResponseWriter = require('http.response') local app = require(arg[1] or 'hello') local w = setmetatable({ headers = {} }, {__index = ResponseWriter}) local req = setmetatable({ method = 'POST', path = '/', form = {author='John', message='Hello World!'}, server_parts = function() return 'http', 'localhost', '8080' end }, {__index = Request}) app(w, req) --for i = 1, 1000000 do for j = 1, 1 do app(w, req) end end
package.path = package.path .. ';demos/?.lua' local Request = require('http.request') local ResponseWriter = require('http.response') local app = require(arg[1] or 'test') local w = setmetatable({ headers = {} }, {__index = ResponseWriter}) local req = setmetatable({ method = 'POST', path = '/', form = {author='John', message='Hello World!'}, server_parts = function() return 'http', 'localhost', '8080' end }, {__index = Request}) app(w, req) --for i = 1, 1000000 do for j = 1, 1 do app(w, req) end end
Fixed package.path.
Fixed package.path.
Lua
mit
akornatskyy/lucid
f115a8b479a4a7b6a28176087dac95c27620f5be
spec/fixtures/https_server.lua
spec/fixtures/https_server.lua
local https_server = {} https_server.__index = https_server local fmt = string.format local mock_srv_tpl_file = require "spec.fixtures.mock_webserver_tpl" local ngx = require "ngx" local pl_dir = require "pl.dir" local pl_file = require "pl.file" local pl_template = require "pl.template" local pl_path = require "pl.path" local pl_stringx = require "pl.stringx" local uuid = require "resty.jit-uuid" local http_client = require "resty.http" local cjson = require "cjson" -- we need this to get random UUIDs math.randomseed(os.time()) local tmp_root = os.getenv("TMPDIR") or "/tmp" local host_regex = [[([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-z0-9\-._~%!$&'()*+,;=:]+\])(:?[0-9]+)*]] local function create_temp_dir(copy_cert_and_key) local tmp_name = fmt("nginx_%s", uuid()) local tmp_path = fmt("%s/%s", tmp_root, tmp_name) local _, err = pl_path.mkdir(tmp_path) if err then return nil, err end local _, err = pl_path.mkdir(tmp_path .. "/logs") if err then return nil, err end if copy_cert_and_key then local status = pl_dir.copyfile("./spec/fixtures/kong_spec.crt", tmp_path) if not status then return nil, "could not copy cert" end status = pl_dir.copyfile("./spec/fixtures/kong_spec.key", tmp_path) if not status then return nil, "could not copy private key" end end return tmp_path end local function create_conf(params) local tpl, err = pl_template.compile(mock_srv_tpl_file) if err then return nil, err end local compiled_tpl = pl_stringx.Template(tpl:render(params, { ipairs = ipairs })) local conf_filename = params.base_path .. "/nginx.conf" local conf, err = io.open (conf_filename, "w") if err then return nil, err end conf:write(compiled_tpl:substitute(params)) conf:close() return conf_filename end local function count_results(logs_dir) local results = { ["ok"] = 0, ["fail"] = 0, ["total"] = 0, ["status_ok"] = 0, ["status_fail"] = 0, ["status_total"] = 0 } local error_log_filename = logs_dir .. "/error.log" for line in io.lines(error_log_filename) do local m = ngx.re.match(line, [[^.*\[COUNT\] (.+) (\d\d\d)\,.*\, host: \"(.+)\"$]]) if m then local location = m[1] local status = m[2] local host = m[3] if host then local host_no_port = ngx.re.match(m[3], host_regex) if host_no_port then host = host_no_port[2] end else host = "nonamehost" end if results[host] == nil then results[host] = { ["ok"] = 0, ["fail"] = 0, ["status_ok"] = 0, ["status_fail"] = 0, } end if location == "slash" then if status == "200" then results.ok = results.ok + 1 results[host].ok = results[host].ok + 1 else results.fail = results.fail + 1 results[host].fail = results[host].fail + 1 end results.total = results.ok + results.fail elseif location == "status" then if status == "200" then results.status_ok = results.status_ok + 1 results[host].status_ok = results[host].status_ok + 1 else results.status_fail = results.status_fail + 1 results[host].status_fail = results[host].status_fail + 1 end results.status_total = results.status_ok + results.status_fail end end end return results end function https_server.clear_access_log(self) local client = assert(http_client.new()) local uri = string.format("%s://%s:%d/clear_log", self.protocol, self.host, self.http_port) local res = assert(client:request_uri(uri, { method = "GET" })) assert(res.body == "cleared\n") end function https_server.get_access_log(self) local client = assert(http_client.new()) local uri = string.format("%s://%s:%d/log?do_not_log", self.protocol, self.host, self.http_port) local res = assert(client:request_uri(uri, { method = "GET" })) return assert(cjson.decode(res.body)) end function https_server.start(self) if not pl_path.exists(tmp_root) or not pl_path.isdir(tmp_root) then error("could not get a temporary path", 2) end local err self.base_path, err = create_temp_dir(self.protocol == "https") if err then error(fmt("could not create temp dir: %s", err), 2) end local conf_params = { base_path = self.base_path, delay = self.delay, cert_path = "./", check_hostname = self.check_hostname, logs_dir = self.logs_dir, host = self.host, hosts = self.hosts, http_port = self.http_port, protocol = self.protocol, worker_num = self.worker_num, } local file, err = create_conf(conf_params) if err then error(fmt("could not create conf: %s", err), 2) end local status = os.execute("nginx -c " .. file .. " -p " .. self.base_path) if not status then error("failed starting nginx") end end function https_server.shutdown(self) local pid_filename = self.base_path .. "/logs/nginx.pid" local pid_file = io.open (pid_filename, "r") if pid_file then local pid, err = pid_file:read() if err then error(fmt("could not read pid file: %s", tostring(err)), 2) end local kill_nginx_cmd = fmt("kill -s TERM %s", tostring(pid)) local status = os.execute(kill_nginx_cmd) if not status then error(fmt("could not kill nginx test server. %s was not removed", self.base_path), 2) end local pidfile_removed local watchdog = 0 repeat pidfile_removed = pl_file.access_time(pid_filename) == nil if not pidfile_removed then ngx.sleep(0.01) watchdog = watchdog + 1 if(watchdog > 100) then error("could not stop nginx", 2) end end until(pidfile_removed) end local count, err = count_results(self.base_path .. "/" .. self.logs_dir) if err then -- not a fatal error print(fmt("could not count results: %s", tostring(err))) end local _, err = pl_dir.rmtree(self.base_path) if err then print(fmt("could not remove %s: %s", self.base_path, tostring(err))) end return count end function https_server.new(port, hostname, protocol, check_hostname, workers, delay) local self = setmetatable({}, https_server) local host local hosts if type(hostname) == "table" then hosts = hostname host = "" for _, h in ipairs(hostname) do host = fmt("%s %s", host, h) end else hosts = {hostname} host = hostname end self.check_hostname = check_hostname or false self.delay = tonumber(delay) or 0 self.host = host or "localhost" self.hosts = hosts self.http_port = port self.logs_dir = "logs" self.protocol = protocol or "http" self.worker_num = workers or 2 return self end return https_server
local https_server = {} https_server.__index = https_server local fmt = string.format local mock_srv_tpl_file = require "spec.fixtures.mock_webserver_tpl" local ngx = require "ngx" local pl_dir = require "pl.dir" local pl_file = require "pl.file" local pl_template = require "pl.template" local pl_path = require "pl.path" local pl_stringx = require "pl.stringx" local uuid = require "resty.jit-uuid" local http_client = require "resty.http" local cjson = require "cjson" -- we need this to get random UUIDs math.randomseed(os.time()) local HTTPS_SERVER_START_MAX_RETRY = 10 local tmp_root = os.getenv("TMPDIR") or "/tmp" local host_regex = [[([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-z0-9\-._~%!$&'()*+,;=:]+\])(:?[0-9]+)*]] local function create_temp_dir(copy_cert_and_key) local tmp_name = fmt("nginx_%s", uuid()) local tmp_path = fmt("%s/%s", tmp_root, tmp_name) local _, err = pl_path.mkdir(tmp_path) if err then return nil, err end local _, err = pl_path.mkdir(tmp_path .. "/logs") if err then return nil, err end if copy_cert_and_key then local status = pl_dir.copyfile("./spec/fixtures/kong_spec.crt", tmp_path) if not status then return nil, "could not copy cert" end status = pl_dir.copyfile("./spec/fixtures/kong_spec.key", tmp_path) if not status then return nil, "could not copy private key" end end return tmp_path end local function create_conf(params) local tpl, err = pl_template.compile(mock_srv_tpl_file) if err then return nil, err end local compiled_tpl = pl_stringx.Template(tpl:render(params, { ipairs = ipairs })) local conf_filename = params.base_path .. "/nginx.conf" local conf, err = io.open (conf_filename, "w") if err then return nil, err end conf:write(compiled_tpl:substitute(params)) conf:close() return conf_filename end local function count_results(logs_dir) local results = { ["ok"] = 0, ["fail"] = 0, ["total"] = 0, ["status_ok"] = 0, ["status_fail"] = 0, ["status_total"] = 0 } local error_log_filename = logs_dir .. "/error.log" for line in io.lines(error_log_filename) do local m = ngx.re.match(line, [[^.*\[COUNT\] (.+) (\d\d\d)\,.*\, host: \"(.+)\"$]]) if m then local location = m[1] local status = m[2] local host = m[3] if host then local host_no_port = ngx.re.match(m[3], host_regex) if host_no_port then host = host_no_port[2] end else host = "nonamehost" end if results[host] == nil then results[host] = { ["ok"] = 0, ["fail"] = 0, ["status_ok"] = 0, ["status_fail"] = 0, } end if location == "slash" then if status == "200" then results.ok = results.ok + 1 results[host].ok = results[host].ok + 1 else results.fail = results.fail + 1 results[host].fail = results[host].fail + 1 end results.total = results.ok + results.fail elseif location == "status" then if status == "200" then results.status_ok = results.status_ok + 1 results[host].status_ok = results[host].status_ok + 1 else results.status_fail = results.status_fail + 1 results[host].status_fail = results[host].status_fail + 1 end results.status_total = results.status_ok + results.status_fail end end end return results end function https_server.clear_access_log(self) local client = assert(http_client.new()) local uri = string.format("%s://%s:%d/clear_log", self.protocol, self.host, self.http_port) local res = assert(client:request_uri(uri, { method = "GET" })) assert(res.body == "cleared\n") end function https_server.get_access_log(self) local client = assert(http_client.new()) local uri = string.format("%s://%s:%d/log?do_not_log", self.protocol, self.host, self.http_port) local res = assert(client:request_uri(uri, { method = "GET" })) return assert(cjson.decode(res.body)) end function https_server.start(self) if not pl_path.exists(tmp_root) or not pl_path.isdir(tmp_root) then error("could not get a temporary path", 2) end local err self.base_path, err = create_temp_dir(self.protocol == "https") if err then error(fmt("could not create temp dir: %s", err), 2) end local conf_params = { base_path = self.base_path, delay = self.delay, cert_path = "./", check_hostname = self.check_hostname, logs_dir = self.logs_dir, host = self.host, hosts = self.hosts, http_port = self.http_port, protocol = self.protocol, worker_num = self.worker_num, } local file, err = create_conf(conf_params) if err then error(fmt("could not create conf: %s", err), 2) end for _ = 1, HTTPS_SERVER_START_MAX_RETRY do if os.execute("nginx -c " .. file .. " -p " .. self.base_path) then return end ngx.sleep(1) end error("failed starting nginx") end function https_server.shutdown(self) local pid_filename = self.base_path .. "/logs/nginx.pid" local pid_file = io.open (pid_filename, "r") if pid_file then local pid, err = pid_file:read() if err then error(fmt("could not read pid file: %s", tostring(err)), 2) end local kill_nginx_cmd = fmt("kill -s TERM %s", tostring(pid)) local status = os.execute(kill_nginx_cmd) if not status then error(fmt("could not kill nginx test server. %s was not removed", self.base_path), 2) end local pidfile_removed local watchdog = 0 repeat pidfile_removed = pl_file.access_time(pid_filename) == nil if not pidfile_removed then ngx.sleep(0.01) watchdog = watchdog + 1 if(watchdog > 100) then error("could not stop nginx", 2) end end until(pidfile_removed) end local count, err = count_results(self.base_path .. "/" .. self.logs_dir) if err then -- not a fatal error print(fmt("could not count results: %s", tostring(err))) end local _, err = pl_dir.rmtree(self.base_path) if err then print(fmt("could not remove %s: %s", self.base_path, tostring(err))) end return count end function https_server.new(port, hostname, protocol, check_hostname, workers, delay) local self = setmetatable({}, https_server) local host local hosts if type(hostname) == "table" then hosts = hostname host = "" for _, h in ipairs(hostname) do host = fmt("%s %s", host, h) end else hosts = {hostname} host = hostname end self.check_hostname = check_hostname or false self.delay = tonumber(delay) or 0 self.host = host or "localhost" self.hosts = hosts self.http_port = port self.logs_dir = "logs" self.protocol = protocol or "http" self.worker_num = workers or 2 return self end return https_server
tests(fixtures/https_server): retry if Nginx failed to start
tests(fixtures/https_server): retry if Nginx failed to start
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong