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
97d2e3f2a3211e86705275898db8fa4b768c3c8e
modulefiles/Core/geant4/10.02.lua
modulefiles/Core/geant4/10.02.lua
help( [[ This module loads Geant4 10.02. Geant4 is a detector simulator for HEP. ]]) whatis("Loads Geant4 10.02") local version = "10.02" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/"..version prepend_path("PATH", pathJoin(base, "bin")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) family('geant4') load('gcc/4.9.2', 'clhep/2.3.1.1')
help( [[ This module loads Geant4 10.02. Geant4 is a detector simulator for HEP. ]]) whatis("Loads Geant4 10.02") local version = "10.02" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/"..version prepend_path("PATH", pathJoin(base, "bin")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib64")) prepend_path("LD_LIBRARY_PATH", "/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/lib64/geant4/Linux-g++") prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib64")) pushenv("G4NEUTRONHPDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4NDL4.5") pushenv("G4LEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4EMLOW6.48") pushenv("G4LEVELGAMMADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/PhotonEvaporation3.2") pushenv("G4RADIOACTIVEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/RadioactiveDecay4.3") pushenv("G4NEUTRONXSDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4NEUTRONXS1.4") pushenv("G4PIIDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4PII1.3") pushenv("G4REALSURFACEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/RealSurface1.0") pushenv("G4SAIDXSDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4SAIDDATA1.1") pushenv("G4ABLADATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4ABLA3.0") pushenv("G4ENSDFSTATEDATA","/cvmfs/oasis.opensciencegrid.org/osg/modules/geant4/10.02/share/Geant4-10.2.0/data/G4ENSDFSTATE1.2") family('geant4') load('gcc/4.9.2', 'clhep/2.3.1.1')
Add minor fixes for Geant4 10.02 module
Add minor fixes for Geant4 10.02 module
Lua
apache-2.0
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
742a3d85e38b570c53b4c189111bfacad12d22e8
tests/tls-sni.lua
tests/tls-sni.lua
-- Tests Copas with a simple Echo server -- -- Run the test file and the connect to the server using telnet on the used port. -- The server should be able to echo any input, to stop the test just send the command "quit" local port = 20000 local copas = require("copas") local socket = require("socket") local ssl = require("ssl") local server local server_params = { wrap = { mode = "server", protocol = "tlsv1", key = "tests/certs/serverAkey.pem", certificate = "tests/certs/serverA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, }, sni = { strict = true, -- only allow connection 'myhost.com' names = {} } } server_params.sni.names["myhost.com"] = ssl.newcontext(server_params.wrap) local client_params = { wrap = { mode = "client", protocol = "tlsv1", key = "tests/certs/clientAkey.pem", certificate = "tests/certs/clientA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, }, sni = { names = "" -- will be added in test below } } local function echoHandler(skt) while true do local data, err = skt:receive() if not data then if err ~= "closed" then return error("client connection error: "..tostring(err)) else return -- client closed the connection end elseif data == "quit" then return -- close this client connection elseif data == "exit" then copas.removeserver(server) return -- close this client connection, after stopping the server end skt:send(data) end end server = assert(socket.bind("*", port)) copas.addserver(server, copas.handler(echoHandler, server_params)) copas.addthread(function() copas.sleep(0.5) -- allow server socket to be ready ---------------------- -- Tests start here -- ---------------------- -- try with a bad SNI (non matching) client_params.sni.names = "badhost.com" local skt = copas.wrap(socket.tcp(), client_params) local _, err = pcall(skt.connect, skt, "localhost", port) if not tostring(err):match("TLS/SSL handshake failed:") then print "expected handshake to fail" os.exit(1) end -- try again with a proper SNI (matching) client_params.sni.names = "myhost.com" local skt = copas.wrap(socket.tcp(), client_params) local success, ok = pcall(skt.connect, skt, "localhost", port) if not (success and ok) then print "expected connection to be completed" os.exit(1) end print "succesfully completed test" os.exit(0) end) -- no ugly errors please, comment out when debugging copas.setErrorHandler(function() end, true) copas.loop()
-- Tests Copas with a simple Echo server -- -- Run the test file and the connect to the server using telnet on the used port. -- The server should be able to echo any input, to stop the test just send the command "quit" local port = 20000 local copas = require("copas") local socket = require("socket") local ssl = require("ssl") local server if _VERSION=="Lua 5.1" and not jit then -- obsolete: only for Lua 5.1 compatibility pcall = require("coxpcall").pcall -- luacheck: ignore end local server_params = { wrap = { mode = "server", protocol = "tlsv1", key = "tests/certs/serverAkey.pem", certificate = "tests/certs/serverA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, }, sni = { strict = true, -- only allow connection 'myhost.com' names = {} } } server_params.sni.names["myhost.com"] = ssl.newcontext(server_params.wrap) local client_params = { wrap = { mode = "client", protocol = "tlsv1", key = "tests/certs/clientAkey.pem", certificate = "tests/certs/clientA.pem", cafile = "tests/certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, }, sni = { names = "" -- will be added in test below } } local function echoHandler(skt) while true do local data, err = skt:receive() if not data then if err ~= "closed" then return error("client connection error: "..tostring(err)) else return -- client closed the connection end elseif data == "quit" then return -- close this client connection elseif data == "exit" then copas.removeserver(server) return -- close this client connection, after stopping the server end skt:send(data) end end server = assert(socket.bind("*", port)) copas.addserver(server, copas.handler(echoHandler, server_params)) copas.addthread(function() copas.sleep(0.5) -- allow server socket to be ready ---------------------- -- Tests start here -- ---------------------- -- try with a bad SNI (non matching) client_params.sni.names = "badhost.com" local skt = copas.wrap(socket.tcp(), client_params) local _, err = pcall(skt.connect, skt, "localhost", port) if not tostring(err):match("TLS/SSL handshake failed:") then print "expected handshake to fail" os.exit(1) end -- try again with a proper SNI (matching) client_params.sni.names = "myhost.com" local skt = copas.wrap(socket.tcp(), client_params) local success, ok = pcall(skt.connect, skt, "localhost", port) if not (success and ok) then print "expected connection to be completed" os.exit(1) end print "succesfully completed test" os.exit(0) end) -- no ugly errors please, comment out when debugging copas.setErrorHandler(function() end, true) copas.loop()
fix(test) sni test for Lua 5.1
fix(test) sni test for Lua 5.1
Lua
mit
keplerproject/copas
52e95c07e2e4f252873027314fb1b9f331eb8db9
lua/entities/gmod_wire_starfall_screen/init.lua
lua/entities/gmod_wire_starfall_screen/init.lua
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") local context = SF.CreateContext() local screens = {} util.AddNetworkString("starfall_screen_download") util.AddNetworkString("starfall_screen_update") local function sendScreenCode(screen, owner, files, mainfile, recipient) --print("Sending SF code") net.Start("starfall_screen_download") net.WriteEntity(screen) net.WriteEntity(owner) net.WriteString(mainfile) if recipient then net.Send(recipient) else net.Broadcast() end --print("\tHeader sent") local fname = next(files) while fname do --print("\tSending data for:", fname) local fdata = files[fname] local offset = 1 repeat net.Start("starfall_screen_download") net.WriteBit(false) net.WriteString(fname) local data = fdata:sub(offset, offset+60000) net.WriteString(data) if recipient then net.Send(recipient) else net.Broadcast() end --print("\t\tSent data from", offset, "to", offset + #data) offset = offset + #data + 1 until offset > #fdata fname = next(files, fname) end net.Start("starfall_screen_download") net.WriteBit(true) if recipient then net.Send(recipient) else net.Broadcast() end --print("Done sending") end net.Receive("starfall_screen_download", function(len, ply) local screen = net.ReadEntity() if not screen.mainfile then return end sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply) end) function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetUseType( 3 ) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) local r,g,b,a = self:GetColor() end function ENT:OnRestore() end function ENT:UpdateName(state) if state ~= "" then state = "\n"..state end if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state) else self:SetOverlayText("Starfall Processor"..state) end end function ENT:Error(msg, override) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateName("Inactive (Error)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:CodeSent(ply, files, mainfile) if ply ~= self.owner then return end self.files = files self.mainfile = mainfile screens[self] = self net.Start("starfall_screen_update") net.WriteEntity(self) for k,v in pairs(files) do net.WriteBit(false) net.WriteString(k) net.WriteString(util.CRC(v)) end net.WriteBit(true) net.Broadcast() --sendScreenCode(self, ply, files, mainfile) local ppdata = {} SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata) if ppdata.sharedscreen then local ok, instance = SF.Compiler.Compile(files,context,mainfile,ply) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end self:UpdateName("") local r,g,b,a = self:GetColor() self:SetColor(Color(255, 255, 255, a)) self.sharedscreen = true end end function ENT:Think() self.BaseClass.Think(self) self:NextThink(CurTime()) if self.instance and not self.instance.error then self.instance:resetOps() self:runScriptHook("think") end return true end -- Sends a umsg to all clients about the use. function ENT:Use( activator ) if activator:IsPlayer() then umsg.Start( "starfall_screen_used" ) umsg.Short( self:EntIndex() ) umsg.Short( activator:EntIndex() ) umsg.End( ) end if self.sharedscreen then self:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) ) end end function ENT:OnRemove() if not self.instance then return end screens[self] = nil self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:runScriptHook("input",key,value) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile) return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply local code, main = SF.DeserializeCode(info.starfall) local task = {files = code, mainfile = main} self:CodeSent(ply, task) end
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") local context = SF.CreateContext() local screens = {} util.AddNetworkString("starfall_screen_download") util.AddNetworkString("starfall_screen_update") local function sendScreenCode(screen, owner, files, mainfile, recipient) --print("Sending SF code") net.Start("starfall_screen_download") net.WriteEntity(screen) net.WriteEntity(owner) net.WriteString(mainfile) if recipient then net.Send(recipient) else net.Broadcast() end --print("\tHeader sent") local fname = next(files) while fname do --print("\tSending data for:", fname) local fdata = files[fname] local offset = 1 repeat net.Start("starfall_screen_download") net.WriteBit(false) net.WriteString(fname) local data = fdata:sub(offset, offset+60000) net.WriteString(data) if recipient then net.Send(recipient) else net.Broadcast() end --print("\t\tSent data from", offset, "to", offset + #data) offset = offset + #data + 1 until offset > #fdata fname = next(files, fname) end net.Start("starfall_screen_download") net.WriteBit(true) if recipient then net.Send(recipient) else net.Broadcast() end --print("Done sending") end local requests = {} local function retryCodeRequests() for k,v in pairs(requests) do sendCodeRequest(v.player, k) v.tries = v.tries + 1 if v.tries >= 3 then requests[k] = nil end end end local function sendCodeRequest(ply, screen) if not screen.mainfile then requests[screen] = {player = ply, tries = 0} if timer.Exists("starfall_send_code_request") then return end timer.Create("starfall_send_code_request", .5, 1, retryCodeRequests) end requests[screen] = nil sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply) end net.Receive("starfall_screen_download", function(len, ply) local screen = net.ReadEntity() sendCodeRequest(ply, screen) end) function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetUseType( 3 ) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) local r,g,b,a = self:GetColor() end function ENT:OnRestore() end function ENT:UpdateName(state) if state ~= "" then state = "\n"..state end if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state) else self:SetOverlayText("Starfall Processor"..state) end end function ENT:Error(msg, override) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateName("Inactive (Error)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:CodeSent(ply, files, mainfile) if ply ~= self.owner then return end local update = self.mainfile ~= nil self.files = files self.mainfile = mainfile screens[self] = self if update then net.Start("starfall_screen_update") net.WriteEntity(self) for k,v in pairs(files) do net.WriteBit(false) net.WriteString(k) net.WriteString(util.CRC(v)) end net.WriteBit(true) net.Broadcast() --sendScreenCode(self, ply, files, mainfile) end local ppdata = {} SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata) if ppdata.sharedscreen then local ok, instance = SF.Compiler.Compile(files,context,mainfile,ply) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end self:UpdateName("") local r,g,b,a = self:GetColor() self:SetColor(Color(255, 255, 255, a)) self.sharedscreen = true end end function ENT:Think() self.BaseClass.Think(self) self:NextThink(CurTime()) if self.instance and not self.instance.error then self.instance:resetOps() self:runScriptHook("think") end return true end -- Sends a umsg to all clients about the use. function ENT:Use( activator ) if activator:IsPlayer() then umsg.Start( "starfall_screen_used" ) umsg.Short( self:EntIndex() ) umsg.Short( activator:EntIndex() ) umsg.End( ) end if self.sharedscreen then self:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) ) end end function ENT:OnRemove() if not self.instance then return end screens[self] = nil self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:runScriptHook("input",key,value) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile) return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply local code, main = SF.DeserializeCode(info.starfall) local task = {files = code, mainfile = main} self:CodeSent(ply, task) end
[Fix] occasional error when sending screen code
[Fix] occasional error when sending screen code ...hopefully Hopefully fixes #54
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,INPStarfall/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall
23a9b6e1b03f801e61f475cc8ce1ff24043f6ec9
userspace/falco/lua/output.lua
userspace/falco/lua/output.lua
local mod = {} levels = {"Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Informational", "Debug"} mod.levels = levels local outputs = {} function mod.stdout(level, msg) print (msg) end function mod.file_validate(options) if (not type(options.filename) == 'string') then error("File output needs to be configured with a valid filename") end file, err = io.open(options.filename, "a+") if file == nil then error("Error with file output: "..err) end file:close() end function mod.file(level, msg) file = io.open(options.filename, "a+") file:write(msg, "\n") file:close() end function mod.syslog(level, msg) falco.syslog(level, msg) end function mod.program(level, msg) -- XXX Ideally we'd check that the program ran -- successfully. However, the luajit we're using returns true even -- when the shell can't run the program. file = io.popen(options.program, "w") file:write(msg, "\n") file:close() end local function level_of(s) s = string.lower(s) for i,v in ipairs(levels) do if (string.find(string.lower(v), "^"..s)) then return i - 1 -- (syslog levels start at 0, lua indices start at 1) end end error("Invalid severity level: "..s) end function output_event(event, rule, priority, format) local level = level_of(priority) format = "*%evt.time: "..levels[level+1].." "..format formatter = falco.formatter(format) msg = falco.format_event(event, rule, levels[level+1], formatter) for index,o in ipairs(outputs) do o.output(level, msg) end falco.free_formatter(formatter) end function add_output(output_name, config) if not (type(mod[output_name]) == 'function') then error("rule_loader.add_output(): invalid output_name: "..output_name) end -- outputs can optionally define a validation function so that we don't -- find out at runtime (when an event finally matches a rule!) that the config is invalid if (type(mod[output_name.."_validate"]) == 'function') then mod[output_name.."_validate"](config) end table.insert(outputs, {output = mod[output_name], config=config}) end return mod
local mod = {} levels = {"Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Informational", "Debug"} mod.levels = levels local outputs = {} function mod.stdout(level, msg) print (msg) end function mod.file_validate(options) if (not type(options.filename) == 'string') then error("File output needs to be configured with a valid filename") end file, err = io.open(options.filename, "a+") if file == nil then error("Error with file output: "..err) end file:close() end function mod.file(level, msg, options) file = io.open(options.filename, "a+") file:write(msg, "\n") file:close() end function mod.syslog(level, msg, options) falco.syslog(level, msg) end function mod.program(level, msg, options) -- XXX Ideally we'd check that the program ran -- successfully. However, the luajit we're using returns true even -- when the shell can't run the program. file = io.popen(options.program, "w") file:write(msg, "\n") file:close() end local function level_of(s) s = string.lower(s) for i,v in ipairs(levels) do if (string.find(string.lower(v), "^"..s)) then return i - 1 -- (syslog levels start at 0, lua indices start at 1) end end error("Invalid severity level: "..s) end function output_event(event, rule, priority, format) local level = level_of(priority) format = "*%evt.time: "..levels[level+1].." "..format formatter = falco.formatter(format) msg = falco.format_event(event, rule, levels[level+1], formatter) for index,o in ipairs(outputs) do o.output(level, msg, o.config) end falco.free_formatter(formatter) end function add_output(output_name, config) if not (type(mod[output_name]) == 'function') then error("rule_loader.add_output(): invalid output_name: "..output_name) end -- outputs can optionally define a validation function so that we don't -- find out at runtime (when an event finally matches a rule!) that the config is invalid if (type(mod[output_name.."_validate"]) == 'function') then mod[output_name.."_validate"](config) end table.insert(outputs, {output = mod[output_name], config=config}) end return mod
Fix output methods that take configurations.
Fix output methods that take configurations. The falco engine changes broke the output methods that take configuration (like the filename for file output, or the program for program output). Fix that by properly passing the options argument to each method's output function.
Lua
apache-2.0
draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco
f96ca354b74e59a25c45ed190dfcf1c0b0603c46
examples/route_guide/route_guide_client.lua
examples/route_guide/route_guide_client.lua
--- Route guide example client. -- route_guide_client.lua require("init_package_path") local grpc = require("grpc_lua.grpc_lua") local db = require("db") local inspect = require("inspect") local SVC = "routeguide.RouteGuide" local c_channel -- C `Channel` object local kCoordFactor = 10000000.0 -- New stub on the same channel. local function new_stub() return grcp.service_stub(c_channel, SVC) end local function point(latitude, longitude) return { latitude = latitude, longitude = longitude } end -- point() local function rectangle(lo_latitude, lo_longitude, hi_latitude, hi_longitude) return { lo = point(lo_latitude, lo_longitude), hi = point(hi_latitude, hi_longitude) } end -- rectangle() local function route_note(name, latitude, longitude) return { name = name, location = point(latitude, longitude) } end -- route_note() local notes = { route_note("First message", 0, 0), route_note("Second message", 0, 1), route_note("Third message", 1, 0), route_note("Fourth message", 0, 0) } local function print_route_summary(summary) print(string.format( [[[Finished trip with %d points Passed %d features Traveled %d meters It took %d seconds]]], summary.point_count, summary.feature_count, summary.distance, summary.elapsed_time)) end local function sync_get_feature() print("Sync get feature...") local stub = new_stub() local feature feature = stub.sync_request("GetFeature", point(409146138, -746188906)) print("Get feature: "..inspect(feature)) feature = stub.sync_request("GetFeature", point(0, 0) print("Get feature: "..inspect(feature)) end -- sync_get_feature() local function sync_list_features() print("Sync list features...") local stub = new_stub() local rect = rectangle(400000000, -750000000, 420000000, -730000000) print("Looking for features between 40, -75 and 42, -73") local sync_reader = stub:sync_request_read("ListFeatures", rect) -- request_read, request_write, request_rdwr ? XXX while true do local feature = sync_reader.read_one() if not feature then break end print("Found feature: "..inspect(feature)) end -- while -- sync_reader.recv_status() XXX print("ListFeatures rpc succeeded.") -- print("ListFeatures rpc failed.") end -- sync_list_features() local function sync_record_route() print("Sync record route...") local stub = new_stub() local sync_writer = stub.sync_request_write("RecordRoute") for i = 1, 10 do local feature = db.get_rand_feature() local loc = assert(feature.location) print(string.format("Visiting point (%f, %f)", loc.latitude()/kCoordFactor, loc.longitude()/kCoordFactor)) if not sync_writer.write(loc) then print("Failed to sync write.") break end -- if end -- for -- Recv status and reponse. local summary, error_str, status_code = sync_writer.close() -- Todo: timeout if not summary then print(string.format("RecordRoute rpc failed: (%d)%s.", status_code, error_str) return end print_route_sumary(summary) end -- sync_record_route() local function sync_route_chat() print("Sync route chat...") local stub = new_stub() local sync_rdwr = stub.sync_request_rdwr("RouteChat") -- XXX for _, note in ipairs(notes) do -- write one then read one print("Sending message: " .. inspect(note)) sync_rdwr.write(note) local server_note = sync_rdwr.read_one() if server_note then print("Got message: "..inspect(server_note)) end } sync_rdwr.close_writing() -- read remaining while true do local server_note = sync_rdwr.read_one() if not server_note then break end print("Got message: "..inspect(server_note)) end -- while end -- sync_route_chat() local function get_feature_async() print("Get feature async...") local stub = new_stub() stub.async_request("GetFeature", point()) -- ignore response stub.async_request("GetFeature", point(409146138, -746188906), function(resp) print("Get feature: "..inspect(resp)) stub.shutdown() -- to return end) stub.run() -- run async requests until stub.shutdown() end -- get_feature_async() local function list_features_async() print("List features async...") local stub = new_stub() local rect = rectangle(400000000, -750000000, 420000000, -730000000) print("Looking for features between 40, -75 and 42, -73") -- XXX stub.async_request_read("ListFeatures", rect, function(f) print(string.format("Got feature %s at %f,%f", f.name, f.location.latitude/kCoordFactor, f.location.longitude/kCoordFactor)) end, function(status) -- XXX print("End status: "..inspect(status)) stub.shutdown() -- To break Run(). end) stub.run() -- until stub.shutdown() end -- list_features_async() local function record_route_async() print("Record route async...") local stub = new_stub() -- XXX // ClientAsyncWriter<Point, RouteSummary> async_writer; local async_writer = stub.async_request_write("RecordRoute") for i = 1, 10 do local f = db.get_rand_feature() local loc = f.location print(string.format("Visiting point %f,%f", loc.latitude/kCoordFactor, loc.longitude/kCoordFactor)) -- XXX if not async_writer:write(loc) do break end -- Broken stream. end -- for -- Recv reponse and status. async_writer.close( -- XXX function(status, resp) assert("table" == type(resp)) if not status.ok then print("RecordRoute rpc failed. "..inspect(status)) else print_route_summary(resp) end -- if stub.shutdown() -- to break run() end) stub.run() -- until stutdown() end -- record_route_async() local function route_chat_async() print("Route chat async...") local stub = new_stub() -- XXX local rdwr = stub.async_request_rdwr("RouteChat", function(status) if not status.ok then print("RouteChat rpc failed. " .. inspect(status)) end -- if stub.shutdown() -- to break run() end) for _, note in ipairs(notes) do print("Sending message: " .. inspect(note)) rdwr.write(note) -- XXX end rdwr.close_writing() -- Optional. rdwr.read_each(print_server_note) -- XXX stub.run() -- until shutdown() end -- route_chat_async() local function main() db.load() grpc.import_proto_file("route_guide.proto") c_channel = grpc.channel("localhost:50051") sync_get_feature() sync_list_features() sync_record_route() sync_route_chat() get_feature_async() list_features_async() record_route_async() route_chat_async() end -- main() main()
--- Route guide example client. -- route_guide_client.lua require("init_package_path") local grpc = require("grpc_lua.grpc_lua") local db = require("db") local inspect = require("inspect") local SVC = "routeguide.RouteGuide" local c_channel -- C `Channel` object local kCoordFactor = 10000000.0 -- New stub on the same channel. local function new_stub() return grcp.service_stub(c_channel, SVC) end local function point(latitude, longitude) return { latitude = latitude, longitude = longitude } end -- point() local function rectangle(lo_latitude, lo_longitude, hi_latitude, hi_longitude) return { lo = point(lo_latitude, lo_longitude), hi = point(hi_latitude, hi_longitude) } end -- rectangle() local function route_note(name, latitude, longitude) return { name = name, location = point(latitude, longitude) } end -- route_note() local notes = { route_note("First message", 0, 0), route_note("Second message", 0, 1), route_note("Third message", 1, 0), route_note("Fourth message", 0, 0) } local function print_route_summary(summary) print(string.format( [[[Finished trip with %d points Passed %d features Traveled %d meters It took %d seconds]]], summary.point_count, summary.feature_count, summary.distance, summary.elapsed_time)) end local function sync_get_feature() print("Sync get feature...") local stub = new_stub() local feature feature = stub.sync_request("GetFeature", point(409146138, -746188906)) print("Get feature: "..inspect(feature)) feature = stub.sync_request("GetFeature", point(0, 0) print("Get feature: "..inspect(feature)) end -- sync_get_feature() local function sync_list_features() print("Sync list features...") local stub = new_stub() local rect = rectangle(400000000, -750000000, 420000000, -730000000) print("Looking for features between 40, -75 and 42, -73") local sync_reader = stub:sync_request_read("ListFeatures", rect) -- request_read, request_write, request_rdwr ? XXX while true do local feature = sync_reader.read_one() if not feature then break end print("Found feature: "..inspect(feature)) end -- while -- sync_reader.recv_status() XXX print("ListFeatures rpc succeeded.") -- print("ListFeatures rpc failed.") end -- sync_list_features() local function sync_record_route() print("Sync record route...") local stub = new_stub() local sync_writer = stub.sync_request_write("RecordRoute") for i = 1, 10 do local feature = db.get_rand_feature() local loc = assert(feature.location) print(string.format("Visiting point (%f, %f)", loc.latitude()/kCoordFactor, loc.longitude()/kCoordFactor)) if not sync_writer.write(loc) then print("Failed to sync write.") break end -- if end -- for -- Recv status and reponse. local summary, error_str, status_code = sync_writer.close() -- Todo: timeout if not summary then print(string.format("RecordRoute rpc failed: (%d)%s.", status_code, error_str) return end print_route_sumary(summary) end -- sync_record_route() local function sync_route_chat() print("Sync route chat...") local stub = new_stub() local sync_rdwr = stub.sync_request_rdwr("RouteChat") -- XXX for _, note in ipairs(notes) do -- write one then read one print("Sending message: " .. inspect(note)) sync_rdwr.write(note) local server_note = sync_rdwr.read_one() if server_note then print("Got message: "..inspect(server_note)) end } sync_rdwr.close_writing() -- read remaining while true do local server_note = sync_rdwr.read_one() if not server_note then break end print("Got message: "..inspect(server_note)) end -- while end -- sync_route_chat() local function get_feature_async() print("Get feature async...") local stub = new_stub() stub.async_request("GetFeature", point()) -- ignore response stub.async_request("GetFeature", point(409146138, -746188906), function(resp) print("Get feature: "..inspect(resp)) stub.shutdown() -- to return end) stub.run() -- run async requests until stub.shutdown() end -- get_feature_async() local function list_features_async() print("List features async...") local stub = new_stub() local rect = rectangle(400000000, -750000000, 420000000, -730000000) print("Looking for features between 40, -75 and 42, -73") stub.async_request_read("ListFeatures", rect, function(f) print(string.format("Got feature %s at %f,%f", f.name, f.location.latitude/kCoordFactor, f.location.longitude/kCoordFactor)) end, function(error_str, status_code) print(string.format("End status: (%d)%s", status_code, error_str) stub.shutdown() -- To break Run(). end) stub.run() -- until stub.shutdown() end -- list_features_async() local function record_route_async() print("Record route async...") local stub = new_stub() -- XXX // ClientAsyncWriter<Point, RouteSummary> async_writer; local async_writer = stub.async_request_write("RecordRoute") for i = 1, 10 do local f = db.get_rand_feature() local loc = f.location print(string.format("Visiting point %f,%f", loc.latitude/kCoordFactor, loc.longitude/kCoordFactor)) -- XXX if not async_writer:write(loc) do break end -- Broken stream. end -- for -- Recv reponse and status. async_writer.close( -- XXX function(status, resp) assert("table" == type(resp)) if not status.ok then print("RecordRoute rpc failed. "..inspect(status)) else print_route_summary(resp) end -- if stub.shutdown() -- to break run() end) stub.run() -- until stutdown() end -- record_route_async() local function route_chat_async() print("Route chat async...") local stub = new_stub() -- XXX local rdwr = stub.async_request_rdwr("RouteChat", function(status) if not status.ok then print("RouteChat rpc failed. " .. inspect(status)) end -- if stub.shutdown() -- to break run() end) for _, note in ipairs(notes) do print("Sending message: " .. inspect(note)) rdwr.write(note) -- XXX end rdwr.close_writing() -- Optional. rdwr.read_each(print_server_note) -- XXX stub.run() -- until shutdown() end -- route_chat_async() local function main() db.load() grpc.import_proto_file("route_guide.proto") c_channel = grpc.channel("localhost:50051") sync_get_feature() sync_list_features() sync_record_route() sync_route_chat() get_feature_async() list_features_async() record_route_async() route_chat_async() end -- main() main()
Fix list_features_async().
Fix list_features_async().
Lua
bsd-3-clause
jinq0123/grpc-lua,jinq0123/grpc-lua,jinq0123/grpc-lua
263309d0f353ea1e1333daab3145918540d8f533
frontend/apps/reader/modules/readerlink.lua
frontend/apps/reader/modules/readerlink.lua
local InputContainer = require("ui/widget/container/inputcontainer") local GestureRange = require("ui/gesturerange") local LinkBox = require("ui/widget/linkbox") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Screen = require("device").screen local Device = require("device") local Event = require("ui/event") local DEBUG = require("dbg") local _ = require("gettext") local ReaderLink = InputContainer:new{ link_states = {} } function ReaderLink:init() if Device:isTouchDevice() then self:initGesListener() end self.ui:registerPostInitCallback(function() self.ui.menu:registerToMainMenu(self) end) end function ReaderLink:onReadSettings(config) -- called when loading new document self.link_states = {} end function ReaderLink:initGesListener() if Device:isTouchDevice() then self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, Swipe = { GestureRange:new{ ges = "swipe", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), } } }, } end end function ReaderLink:addToMainMenu(tab_item_table) -- insert table to main reader menu table.insert(tab_item_table.navi, { text = _("Follow links"), checked_func = function() return G_reader_settings:readSetting("follow_links") == true end, callback = function() local follow_links = G_reader_settings:readSetting("follow_links") G_reader_settings:saveSetting("follow_links", not follow_links) end }) end function ReaderLink:onSetDimensions(dimen) -- update listening according to new screen dimen if Device:isTouchDevice() then self:initGesListener() end end function ReaderLink:onTap(arg, ges) if G_reader_settings:readSetting("follow_links") ~= true then return end if self.ui.document.info.has_pages then local pos = self.view:screenToPageTransform(ges.pos) if pos then -- link box in native page local link, lbox = self.ui.document:getLinkFromPosition(pos.page, pos) if link and lbox then -- screen box that holds the link local sbox = self.view:pageToScreenTransform(pos.page, self.ui.document:nativeToPageRectTransform(pos.page, lbox)) if sbox then UIManager:show(LinkBox:new{ box = sbox, timeout = FOLLOW_LINK_TIMEOUT, callback = function() self:onGotoLink(link) end }) return true end end end else local link = self.ui.document:getLinkFromPosition(ges.pos) if link ~= "" then return self:onGotoLink(link) end end end function ReaderLink:onGotoLink(link) if self.ui.document.info.has_pages then table.insert(self.link_states, self.view.state.page) self.ui:handleEvent(Event:new("GotoPage", link.page + 1)) else table.insert(self.link_states, self.ui.document:getXPointer()) self.ui:handleEvent(Event:new("GotoXPointer", link)) end return true end function ReaderLink:onSwipe(arg, ges) if ges.direction == "east" then if self.ui.document.info.has_pages then local last_page = table.remove(self.link_states) if last_page then self.ui:handleEvent(Event:new("GotoPage", last_page)) return true end else local last_xp = table.remove(self.link_states) if last_xp then self.ui:handleEvent(Event:new("GotoXPointer", last_xp)) return true end end end end return ReaderLink
local InputContainer = require("ui/widget/container/inputcontainer") local GestureRange = require("ui/gesturerange") local LinkBox = require("ui/widget/linkbox") local UIManager = require("ui/uimanager") local Geom = require("ui/geometry") local Screen = require("device").screen local Device = require("device") local Event = require("ui/event") local DEBUG = require("dbg") local _ = require("gettext") local ReaderLink = InputContainer:new{ link_states = {} } function ReaderLink:init() if Device:isTouchDevice() then self:initGesListener() end self.ui:registerPostInitCallback(function() self.ui.menu:registerToMainMenu(self) end) end function ReaderLink:onReadSettings(config) -- called when loading new document self.link_states = {} end function ReaderLink:initGesListener() if Device:isTouchDevice() then self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, Swipe = { GestureRange:new{ ges = "swipe", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), } } }, } end end local function is_follow_links_on() return G_reader_settings:readSetting("follow_links") ~= false end local function swipe_to_go_back() return G_reader_settings:readSetting("swipe_to_go_back") ~= false end function ReaderLink:addToMainMenu(tab_item_table) -- insert table to main reader menu table.insert(tab_item_table.navi, { text = _("Follow links"), sub_item_table = { { text_func = function() return is_follow_links_on() and _("Disable") or _("Enable") end, callback = function() G_reader_settings:saveSetting("follow_links", not is_follow_links_on()) end }, { text = _("Go back"), enabled_func = function() return #self.link_states > 0 end, callback = function() self:onGoBackLink() end, }, { text = _("Swipe to go back"), checked_func = function() return swipe_to_go_back() end, callback = function() G_reader_settings:saveSetting("swipe_to_go_back", not swipe_to_go_back()) end, }, } }) end function ReaderLink:onSetDimensions(dimen) -- update listening according to new screen dimen if Device:isTouchDevice() then self:initGesListener() end end function ReaderLink:onTap(arg, ges) if not is_follow_links_on() then return end if self.ui.document.info.has_pages then local pos = self.view:screenToPageTransform(ges.pos) if pos then -- link box in native page local link, lbox = self.ui.document:getLinkFromPosition(pos.page, pos) if link and lbox then -- screen box that holds the link local sbox = self.view:pageToScreenTransform(pos.page, self.ui.document:nativeToPageRectTransform(pos.page, lbox)) if sbox then UIManager:show(LinkBox:new{ box = sbox, timeout = FOLLOW_LINK_TIMEOUT, callback = function() self:onGotoLink(link) end }) return true end end end else local link = self.ui.document:getLinkFromPosition(ges.pos) if link ~= "" then return self:onGotoLink(link) end end end function ReaderLink:onGotoLink(link) if self.ui.document.info.has_pages then table.insert(self.link_states, self.view.state.page) self.ui:handleEvent(Event:new("GotoPage", link.page + 1)) else table.insert(self.link_states, self.ui.document:getXPointer()) self.ui:handleEvent(Event:new("GotoXPointer", link)) end return true end function ReaderLink:onGoBackLink() local last_page_or_xp = table.remove(self.link_states) if last_page_or_xp then local event = self.ui.document.info.has_pages and "GotoPage" or "GotoXPointer" self.ui:handleEvent(Event:new(event, last_page_or_xp)) return true end end function ReaderLink:onSwipe(arg, ges) if ges.direction == "east" and swipe_to_go_back() then return self:onGoBackLink() end end return ReaderLink
Add option to disable swipe to go back and add a menu entry "Go back". This should fix #1443.
Add option to disable swipe to go back and add a menu entry "Go back". This should fix #1443.
Lua
agpl-3.0
mihailim/koreader,robert00s/koreader,Frenzie/koreader,mwoz123/koreader,frankyifei/koreader,noname007/koreader,apletnev/koreader,poire-z/koreader,koreader/koreader,houqp/koreader,NiLuJe/koreader,poire-z/koreader,pazos/koreader,NiLuJe/koreader,lgeek/koreader,NickSavage/koreader,Frenzie/koreader,ashang/koreader,Hzj-jie/koreader,chihyang/koreader,ashhher3/koreader,chrox/koreader,koreader/koreader,Markismus/koreader
da02f87964896881f28319917ec3822c325dd010
game/scripts/vscripts/modules/illusions/illusions.lua
game/scripts/vscripts/modules/illusions/illusions.lua
Illusions = Illusions or {} function Illusions:_copyAbilities(unit, illusion) for slot = 0, unit:GetAbilityCount() - 1 do local illusionAbility = illusion:GetAbilityByIndex(slot) local unitAbility = unit:GetAbilityByIndex(slot) if unitAbility then local newName = unitAbility:GetAbilityName() if illusionAbility then if illusionAbility:GetAbilityName() ~= newName then illusion:RemoveAbility(illusionAbility:GetAbilityName()) illusionAbility = illusion:AddNewAbility(newName, true) end else illusionAbility = illusion:AddNewAbility(newName, true) end illusionAbility:SetHidden(unitAbility:IsHidden()) local ualevel = unitAbility:GetLevel() if ualevel > 0 and illusionAbility:GetAbilityName() ~= "meepo_divided_we_stand" then illusionAbility:SetLevel(ualevel) end elseif illusionAbility then illusion:RemoveAbility(illusionAbility:GetAbilityName()) end end end function Illusions:_copyItems(unit, illusion) for slot = 0, 5 do local item = unit:GetItemInSlot(slot) if item then local illusion_item = illusion:AddItem(CreateItem(item:GetName(), illusion, illusion)) illusion_item:SetCurrentCharges(item:GetCurrentCharges()) end end end function Illusions:_copyShards(unit, illusion) if unit.Additional_str then illusion:ModifyStrength(unit.Additional_str) end if unit.Additional_agi then illusion:ModifyAgility(unit.Additional_agi) end if unit.Additional_int then illusion:ModifyIntellect(unit.Additional_int) end if unit.Additional_attackspeed then local modifier = illusion:FindModifierByName("modifier_item_shard_attackspeed_stack") if not modifier then modifier = illusion:AddNewModifier(caster, nil, "modifier_item_shard_attackspeed_stack", nil) end if modifier then modifier:SetStackCount(unit.Additional_attackspeed) end end end function Illusions:_copyLevel(unit, illusion) local level = unit:GetLevel() for i = 1, level - 1 do illusion:HeroLevelUp(false) end end function Illusions:_copySpecialCustomFields(unit, illusion) if unit.GetEnergy and unit.GetMaxEnergy then illusion.SavedEnergyStates = { Energy = unit:GetEnergy(), MaxEnergy = unit:GetMaxEnergy() } end end function Illusions:_copyAppearance(unit, illusion) illusion:SetModelScale(unit:GetModelScale()) if unit:GetModelName() ~= illusion:GetModelName() then illusion.ModelOverride = unit:GetModelName() illusion:SetModel(illusion.ModelOverride) illusion:SetOriginalModel(illusion.ModelOverride) end local rc = unit:GetRenderColor() if rc ~= Vector(255, 255, 255) then illusion:SetRenderColor(rc.x, rc.y, rc.z) end end function Illusions:create(info) local ability = info.ability local unit = info.unit local origin = info.origin or unit:GetAbsOrigin() local team = info.team or unit:GetTeamNumber() local isOwned = info.isOwned if isOwned == nil then isOwned = true end local illusion = CreateUnitByName( unit:GetUnitName(), origin, true, isOwned and unit or nil, isOwned and unit:GetPlayerOwner() or nil, team ) if isOwned then illusion:SetControllableByPlayer(unit:GetPlayerID(), true) end FindClearSpaceForUnit(illusion, origin, true) illusion:SetForwardVector(unit:GetForwardVector()) Illusions:_copyLevel(unit, illusion) illusion:SetAbilityPoints(0) Illusions:_copySpecialCustomFields(unit, illusion) Illusions:_copyAbilities(unit, illusion) Illusions:_copyItems(unit, illusion) Illusions:_copyAppearance(unit, illusion) illusion:SetHealth(unit:GetHealth()) illusion:SetMana(unit:GetMana()) illusion:AddNewModifier(unit, ability, "modifier_illusion", { duration = info.duration, outgoing_damage = info.damageOutgoing - 100, incoming_damage = info.damageIncoming - 100, }) illusion:MakeIllusion() Illusions:_copyShards(unit, illusion) illusion.UnitName = unit.UnitName illusion:SetNetworkableEntityInfo("unit_name", illusion:GetFullName()) local heroName = unit:GetFullName() if not NPC_HEROES[heroName] and NPC_HEROES_CUSTOM[heroName] then TransformUnitClass(illusion, NPC_HEROES_CUSTOM[heroName], true) end return illusion end
Illusions = Illusions or {} function Illusions:_copyAbilities(unit, illusion) for slot = 0, unit:GetAbilityCount() - 1 do local illusionAbility = illusion:GetAbilityByIndex(slot) local unitAbility = unit:GetAbilityByIndex(slot) if unitAbility then local newName = unitAbility:GetAbilityName() if illusionAbility then if illusionAbility:GetAbilityName() ~= newName then illusion:RemoveAbility(illusionAbility:GetAbilityName()) illusionAbility = illusion:AddNewAbility(newName, true) end else illusionAbility = illusion:AddNewAbility(newName, true) end illusionAbility:SetHidden(unitAbility:IsHidden()) local ualevel = unitAbility:GetLevel() if ualevel > 0 and illusionAbility:GetAbilityName() ~= "meepo_divided_we_stand" then illusionAbility:SetLevel(ualevel) end elseif illusionAbility then illusion:RemoveAbility(illusionAbility:GetAbilityName()) end end end function Illusions:_copyItems(unit, illusion) for slot = 0, 5 do local illusion_item = illusion:GetItemInSlot(slot) if illusion_item then illusion:RemoveItem(illusion_item) end end for slot = 0, 5 do local item = unit:GetItemInSlot(slot) if item then local illusion_item = illusion:AddItem(CreateItem(item:GetName(), illusion, illusion)) illusion_item:SetCurrentCharges(item:GetCurrentCharges()) end end end function Illusions:_copyShards(unit, illusion) if unit.Additional_str then illusion:ModifyStrength(unit.Additional_str) end if unit.Additional_agi then illusion:ModifyAgility(unit.Additional_agi) end if unit.Additional_int then illusion:ModifyIntellect(unit.Additional_int) end if unit.Additional_attackspeed then local modifier = illusion:FindModifierByName("modifier_item_shard_attackspeed_stack") if not modifier then modifier = illusion:AddNewModifier(caster, nil, "modifier_item_shard_attackspeed_stack", nil) end if modifier then modifier:SetStackCount(unit.Additional_attackspeed) end end end function Illusions:_copyLevel(unit, illusion) local level = unit:GetLevel() for i = 1, level - 1 do illusion:HeroLevelUp(false) end end function Illusions:_copySpecialCustomFields(unit, illusion) if unit.GetEnergy and unit.GetMaxEnergy then illusion.SavedEnergyStates = { Energy = unit:GetEnergy(), MaxEnergy = unit:GetMaxEnergy() } end end function Illusions:_copyAppearance(unit, illusion) illusion:SetModelScale(unit:GetModelScale()) if unit:GetModelName() ~= illusion:GetModelName() then illusion.ModelOverride = unit:GetModelName() illusion:SetModel(illusion.ModelOverride) illusion:SetOriginalModel(illusion.ModelOverride) end local rc = unit:GetRenderColor() if rc ~= Vector(255, 255, 255) then illusion:SetRenderColor(rc.x, rc.y, rc.z) end end function Illusions:create(info) local ability = info.ability local unit = info.unit local origin = info.origin or unit:GetAbsOrigin() local team = info.team or unit:GetTeamNumber() local isOwned = info.isOwned if isOwned == nil then isOwned = true end local illusion = CreateUnitByName( unit:GetUnitName(), origin, true, isOwned and unit or nil, isOwned and unit:GetPlayerOwner() or nil, team ) if isOwned then illusion:SetControllableByPlayer(unit:GetPlayerID(), true) end FindClearSpaceForUnit(illusion, origin, true) illusion:SetForwardVector(unit:GetForwardVector()) Illusions:_copyLevel(unit, illusion) illusion:SetAbilityPoints(0) Illusions:_copySpecialCustomFields(unit, illusion) Illusions:_copyAbilities(unit, illusion) Illusions:_copyItems(unit, illusion) Illusions:_copyAppearance(unit, illusion) illusion:SetHealth(unit:GetHealth()) illusion:SetMana(unit:GetMana()) illusion:AddNewModifier(unit, ability, "modifier_illusion", { duration = info.duration, outgoing_damage = info.damageOutgoing - 100, incoming_damage = info.damageIncoming - 100, }) illusion:MakeIllusion() Illusions:_copyShards(unit, illusion) illusion.UnitName = unit.UnitName illusion:SetNetworkableEntityInfo("unit_name", illusion:GetFullName()) local heroName = unit:GetFullName() if not NPC_HEROES[heroName] and NPC_HEROES_CUSTOM[heroName] then TransformUnitClass(illusion, NPC_HEROES_CUSTOM[heroName], true) end return illusion end
fix(illusions): illusions have hero-only first spawn bonus items (#198)
fix(illusions): illusions have hero-only first spawn bonus items (#198) * Illusions no longer spawn with TP scrolls or mangoes in their invventory * Update illusions.lua * Update illusions.lua
Lua
mit
ark120202/aabs
1dc4c8f4d8b196a7af180cb770b25495c4636a30
core/hyphenator-liang.lua
core/hyphenator-liang.lua
local function addPattern(h, p) local t = h.trie; bits = SU.splitUtf8(p) for i = 1,#bits do char = bits[i] if not char:find("%d") then if not(t[char]) then t[char] = {} end t = t[char] end end t["_"] = {}; local lastWasDigit = 0 for i = 1,#bits do char = bits[i] if char:find("%d") then lastWasDigit = 1 table.insert(t["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(t["_"], 0) end end end local function registerException(h, exc) local k = exc:gsub("-", "") h.exceptions[k] = { } j = 1 for i=1,#exc do j = j + 1 if exc[i] == "-" then j = j - 1 h.exceptions[k][j] = 1 else h.exceptions[k][j] = 0 end end end function loadPatterns(h, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language]; if not (languageset) then print("No patterns for language "..language) return end for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end if not languageset.exceptions then languageset.exceptions = {} end for _,exc in pairs(languageset.exceptions) do registerException(h, exc) end end function _hyphenate(self, w) if string.len(w) < self.minWord then return {w} end local points = self.exceptions[w:lower()] local word = SU.splitUtf8(w) if not points then points = SU.map(function()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local t = self.trie for j = i, #work do if not t[work[j]] then break end t = t[work[j]] local p = t["_"] if p then for k = 1, #p do if points[i+k - 2] and points[i+k -2] < p[k] then points[i+k -2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1,self.leftmin do points[i] = 0 end for i = #points-self.rightmin,#points do points[i] = 0 end end local pieces = {""} for i = 1,#word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {}; _hyphenators = {}; local hyphenateNode = function(n) if not n:isNnode() or not n.text then return {n} end if not _hyphenators[n.language] then _hyphenators[n.language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} }; loadPatterns(_hyphenators[n.language], n.language) end local breaks = _hyphenate(_hyphenators[n.language],n.text); if #breaks > 1 then local newnodes = {} for j, b in ipairs(breaks) do if not(b=="") then for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do if nn:isNnode() then nn.parent = n table.insert(newnodes, nn) end end if not (j == #breaks) then d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), n.options) }) d.parent = n table.insert(newnodes, d) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end n.children = newnodes n.hyphenated = false n.done = false return newnodes end return {n} end showHyphenationPoints = function (word, language) language = language or "en" if not _hyphenators[language] then _hyphenators[language] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} }; loadPatterns(_hyphenators[language], language) end return SU.concat(_hyphenate(_hyphenators[language], word), SILE.settings.get("font.hyphenchar")) end SILE.hyphenate = function (nodelist) local newlist = {} for i = 1,#nodelist do local n = nodelist[i] local newnodes = hyphenateNode(n) for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end end return newlist end
local function addPattern(h, p) local t = h.trie; bits = SU.splitUtf8(p) for i = 1,#bits do char = bits[i] if not char:find("%d") then if not(t[char]) then t[char] = {} end t = t[char] end end t["_"] = {}; local lastWasDigit = 0 for i = 1,#bits do char = bits[i] if char:find("%d") then lastWasDigit = 1 table.insert(t["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(t["_"], 0) end end end local function registerException(h, exc) local k = exc:gsub("-", "") h.exceptions[k] = { } j = 1 for i=1,#exc do j = j + 1 if exc[i] == "-" then j = j - 1 h.exceptions[k][j] = 1 else h.exceptions[k][j] = 0 end end end function loadPatterns(h, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language]; if not (languageset) then print("No patterns for language "..language) return end for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end if not languageset.exceptions then languageset.exceptions = {} end for _,exc in pairs(languageset.exceptions) do registerException(h, exc) end end function _hyphenate(self, w) if string.len(w) < self.minWord then return {w} end local points = self.exceptions[w:lower()] local word = SU.splitUtf8(w) if not points then points = SU.map(function()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local t = self.trie for j = i, #work do if not t[work[j]] then break end t = t[work[j]] local p = t["_"] if p then for k = 1, #p do if points[i+k - 2] and points[i+k -2] < p[k] then points[i+k -2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1,self.leftmin do points[i] = 0 end for i = #points-self.rightmin,#points do points[i] = 0 end end local pieces = {""} for i = 1,#word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {}; _hyphenators = {}; local initHyphenator = function (lang) if not _hyphenators[lang] then _hyphenators[lang] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} }; loadPatterns(_hyphenators[lang], lang) end end local hyphenateNode = function(n) if not n:isNnode() or not n.text then return {n} end initHyphenator(n.language) local breaks = _hyphenate(_hyphenators[n.language],n.text); if #breaks > 1 then local newnodes = {} for j, b in ipairs(breaks) do if not(b=="") then for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do if nn:isNnode() then nn.parent = n table.insert(newnodes, nn) end end if not (j == #breaks) then d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), n.options) }) d.parent = n table.insert(newnodes, d) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end n.children = newnodes n.hyphenated = false n.done = false return newnodes end return {n} end showHyphenationPoints = function (word, language) language = language or "en" initHyphenator(language) return SU.concat(_hyphenate(_hyphenators[language], word), SILE.settings.get("font.hyphenchar")) end SILE.hyphenate = function (nodelist) local newlist = {} for i = 1,#nodelist do local n = nodelist[i] local newnodes = hyphenateNode(n) for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end end return newlist end SILE.registerCommand("hyphenator:add-exceptions", function (o,c) local language = o.lang or SILE.settings.get("document.language") SILE.languageSupport.loadLanguage(language) initHyphenator(language) for token in SU.gtoke(c[1]) do if token.string then registerException(_hyphenators[language],token.string) end end end)
(Undocumented) command to add hyphenation exceptions. Fixes #265
(Undocumented) command to add hyphenation exceptions. Fixes #265
Lua
mit
neofob/sile,neofob/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile
dfb2d225e16d94c48ddd310a7e7b8a2adc14eab7
NoisyReLU.lua
NoisyReLU.lua
local NoisyReLU, parent = torch.class('nn.NoisyReLU','nn.Module') function NoisyReLU:__init(sparsityFactor, threshold_lr, alpha_range, std) -- Params -- sparsityFactor: the micro sparsity of signals through each neuron -- threshold_lr: the rate for learning the optimum threshold for each neuron -- so that the activeness of the neuron approaches sparsityFactor -- alpha_range: {start_weight, num_batches, final_weight} for setting the weight on the -- contemporary sparsity when calculating the mean sparsity over many batches. -- For the start, it will place more weight on the contemporary, but as more -- epoch goes through, the weight on contemporary batch should decrease, so -- that mean_sparsity will be more stable. parent.__init(self) self.sparsityFactor = sparsityFactor or 0.1 self.threshold_lr = threshold_lr or 0.1 -- std for the noise self.std = std or 1 -- larger alpha means putting more weights on contemporary value -- when calculating the moving average mean self.alpha_range = alpha_range or {0.5, 1000, 0.1} assert(self.alpha_range[2] % 1 == 0 and self.alpha_range[2] > 0) -- is an int and > 0 assert(self.alpha_range[1] >= self.alpha_range[3] and self.alpha_range[3] >= 0) self.alpha = self.alpha_range[1] self.decrement = (self.alpha_range[1] - self.alpha_range[3]) / self.alpha_range[2] assert(0 <= self.sparsityFactor and self.sparsityFactor <= 1, 'sparsityFactor not within range [0, 1]') assert(0 < self.alpha and self.alpha < 1, 'alpha not within range (0, 1)') assert(self.std >= 0, 'std has be >= 0') self.threshold = torch.Tensor() self.mean_sparsity = torch.Tensor() self.noise = torch.Tensor() self.activated = torch.Tensor() self.sparsity = torch.Tensor() self.threshold_delta = torch.Tensor() self.train = true self.batchSize = 0 end function NoisyReLU:updateOutput(input) assert(input:dim() == 2, "Only works with 2D inputs (batch-mode)") if self.batchSize ~= input:size(1) then self.output:resizeAs(input) self.noise:resizeAs(input) self.activated:resizeAs(input) self.threshold:resize(1, input:size(2)) if not self._setup then self.threshold:resize(1, input:size(2)):zero() self._setup = true end -- setting noise if self.std > 0 then self.noise:normal(0, self.std) end self.batchSize = input:size(1) end self.output:copy(input) if self.train then self.output:add(self.noise) end -- check if a neuron is active self.activated:gt(self.output, self.threshold:expandAs(input)) self.output:cmul(self.activated) self.output:add(-1, self.threshold:expandAs(input)) -- find the activeness of a neuron in each batch self.sparsity:mean(self.activated, 1) -- recalculate mean sparsity, using exponential moving average if self.mean_sparsity:nElement() == 0 then self.mean_sparsity:resize(input:size(2)) self.mean_sparsity:copy(self.sparsity) self.threshold_delta:resizeAs(self.mean_sparsity) else if self.alpha - self.decrement < self.alpha_range[3] then self.alpha = self.alpha_range[3] else self.alpha = self.alpha - self.decrement end self.mean_sparsity:mul(1-self.alpha):add(self.alpha, self.sparsity) end return self.output end function NoisyReLU:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) self.gradInput:copy(gradOutput):cmul(self.activated) -- update threshold, raise the threshold if the training -- activeness is larger than the desired activeness self.threshold_delta:copy(self.mean_sparsity) self.threshold_delta:add(-self.sparsityFactor) self.threshold:add(self.threshold_lr, self.threshold_delta) return self.gradInput end
local NoisyReLU, parent = torch.class('nn.NoisyReLU','nn.Module') function NoisyReLU:__init(sparsityFactor, threshold_lr, alpha_range, std) -- Params -- sparsityFactor: the micro sparsity of signals through each neuron -- threshold_lr: the rate for learning the optimum threshold for each neuron -- so that the activeness of the neuron approaches sparsityFactor -- alpha_range: {start_weight, num_batches, final_weight} for setting the weight on the -- contemporary sparsity when calculating the mean sparsity over many batches. -- For the start, it will place more weight on the contemporary, but as more -- epoch goes through, the weight on contemporary batch should decrease, so -- that mean_sparsity will be more stable. parent.__init(self) self.sparsityFactor = sparsityFactor or 0.1 self.threshold_lr = threshold_lr or 0.1 -- std for the noise self.std = std or 1 -- larger alpha means putting more weights on contemporary value -- when calculating the moving average mean self.alpha_range = alpha_range or {0.5, 1000, 0.1} assert(self.alpha_range[2] % 1 == 0 and self.alpha_range[2] > 0) -- is an int and > 0 assert(self.alpha_range[1] >= self.alpha_range[3] and self.alpha_range[3] >= 0) self.alpha = self.alpha_range[1] self.decrement = (self.alpha_range[1] - self.alpha_range[3]) / self.alpha_range[2] assert(0 <= self.sparsityFactor and self.sparsityFactor <= 1, 'sparsityFactor not within range [0, 1]') assert(0 < self.alpha and self.alpha < 1, 'alpha not within range (0, 1)') assert(self.std >= 0, 'std has be >= 0') self.threshold = torch.Tensor() self.mean_sparsity = torch.Tensor() self.noise = torch.Tensor() self.activated = torch.Tensor() self.sparsity = torch.Tensor() self.threshold_delta = torch.Tensor() self.train = true self.batchSize = 0 end function NoisyReLU:updateOutput(input) assert(input:dim() == 2, "Only works with 2D inputs (batch-mode)") if self.batchSize ~= input:size(1) then self.output:resizeAs(input) self.noise:resizeAs(input) self.activated:resizeAs(input) self.threshold:resize(1, input:size(2)) if not self._setup then self.threshold:resize(1, input:size(2)):zero() self._setup = true end self.batchSize = input:size(1) end self.output:copy(input) if self.train and self.std > 0 then self.noise:normal(0, self.std) self.output:add(self.noise) end -- check if a neuron is active self.activated:gt(self.output, self.threshold:expandAs(input)) self.output:cmul(self.activated) self.output:add(-1, self.threshold:expandAs(input)) -- find the activeness of a neuron in each batch self.sparsity:mean(self.activated, 1) -- recalculate mean sparsity, using exponential moving average if self.mean_sparsity:nElement() == 0 then self.mean_sparsity:resize(input:size(2)) self.mean_sparsity:copy(self.sparsity) self.threshold_delta:resizeAs(self.mean_sparsity) else if self.alpha - self.decrement < self.alpha_range[3] then self.alpha = self.alpha_range[3] else self.alpha = self.alpha - self.decrement end self.mean_sparsity:mul(1-self.alpha):add(self.alpha, self.sparsity) end return self.output end function NoisyReLU:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) self.gradInput:copy(gradOutput):cmul(self.activated) -- update threshold, raise the threshold if the training -- activeness is larger than the desired activeness self.threshold_delta:copy(self.mean_sparsity) self.threshold_delta:add(-self.sparsityFactor) self.threshold:add(self.threshold_lr, self.threshold_delta) return self.gradInput end
fixed NoisyReLU.noise bug
fixed NoisyReLU.noise bug
Lua
bsd-3-clause
LinusU/cunnx,nicholas-leonard/cunnx
fb9561784a75de0043bb00e12c340ab74b3fd5f8
init.lua
init.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 logging = require('logging') local debugm = require('debug') local fmt = require('string').format local MonitoringAgent = require('./agent').Agent local Setup = require('./setup').Setup local constants = require('./util/constants') local protocolConnection = require('/protocol/virgo_connection') local agentClient = require('/client/virgo_client') local connectionStream = require('/client/virgo_connection_stream') local argv = require("options") .usage('Usage: ') .describe("i", "use insecure tls cert") .describe("i", "insecure") .describe("e", "entry module") .describe("x", "check to run") .describe("s", "state directory path") .describe("c", "config file path") .describe("p", "pid file path") .describe("o", "skip automatic upgrade") .describe("d", "enable debug logging") .alias({['o'] = 'no-upgrade'}) .alias({['d'] = 'debug'}) .describe("u", "setup") .alias({['u'] = 'setup'}) .describe("U", "username") .alias({['U'] = 'username'}) .describe("K", "apikey") .alias({['K'] = 'apikey'}) .argv("idonhU:K:e:x:p:c:s:n:k:u") local Entry = {} function Entry.run() if argv.args.d then logging.set_level(logging.EVERYTHING) else logging.set_level(logging.INFO) end if argv.args.crash then return virgo.force_crash() end local options = {} if argv.args.s then options.stateDirectory = argv.args.s end options.configFile = argv.args.c or constants.DEFAULT_CONFIG_PATH if argv.args.p then options.pidFile = argv.p end if argv.args.i then options.tls = { rejectUnauthorized = false, ca = require('./certs').caCertsDebug } end if argv.args.e then local mod = require(argv.args.e) return mod.run(argv.args) end local types = {} types.ProtocolConnection = protocolConnection types.AgentClient = agentClient types.ConnectionStream = connectionStream -- hacks to make monitoring specific config files compatible with a generic agent.lua virgo.config['endpoints'] = virgo.config['monitoring_endpoints'] virgo.config['upgrade'] = virgo.config['monitoring_upgrade'] virgo.config['id'] = virgo.config['monitoring_id'] virgo.config['token'] = virgo.config['monitoring_token'] virgo.config['guid'] = virgo.config['monitoring_guid'] virgo.config['query_endpoints'] = virgo.config['monitoring_query_endpoints'] virgo.config['snet_region'] = virgo.config['monitoring_snet_region'] local agent = MonitoringAgent:new(options, types) if not argv.args.u then return agent:start(options) end Setup:new(argv, options.configFile, agent):run() end return Entry
--[[ 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 logging = require('logging') local debugm = require('debug') local fmt = require('string').format local MonitoringAgent = require('./agent').Agent local Setup = require('./setup').Setup local constants = require('./util/constants') local protocolConnection = require('/protocol/virgo_connection') local agentClient = require('/client/virgo_client') local connectionStream = require('/client/virgo_connection_stream') local argv = require("options") .usage('Usage: ') .describe("i", "use insecure tls cert") .describe("i", "insecure") .describe("e", "entry module") .describe("x", "check to run") .describe("s", "state directory path") .describe("c", "config file path") .describe("p", "pid file path") .describe("o", "skip automatic upgrade") .describe("d", "enable debug logging") .alias({['o'] = 'no-upgrade'}) .alias({['p'] = 'pidfile'}) .alias({['d'] = 'debug'}) .describe("u", "setup") .alias({['u'] = 'setup'}) .describe("U", "username") .alias({['U'] = 'username'}) .describe("K", "apikey") .alias({['K'] = 'apikey'}) .argv("idonhU:K:e:x:p:c:s:n:k:u") local Entry = {} function Entry.run() if argv.args.d then logging.set_level(logging.EVERYTHING) else logging.set_level(logging.INFO) end if argv.args.crash then return virgo.force_crash() end local options = {} if argv.args.s then options.stateDirectory = argv.args.s end options.configFile = argv.args.c or constants.DEFAULT_CONFIG_PATH if argv.args.p then options.pidFile = argv.args.p end if argv.args.i then options.tls = { rejectUnauthorized = false, ca = require('./certs').caCertsDebug } end if argv.args.e then local mod = require(argv.args.e) return mod.run(argv.args) end local types = {} types.ProtocolConnection = protocolConnection types.AgentClient = agentClient types.ConnectionStream = connectionStream -- hacks to make monitoring specific config files compatible with a generic agent.lua virgo.config['endpoints'] = virgo.config['monitoring_endpoints'] virgo.config['upgrade'] = virgo.config['monitoring_upgrade'] virgo.config['id'] = virgo.config['monitoring_id'] virgo.config['token'] = virgo.config['monitoring_token'] virgo.config['guid'] = virgo.config['monitoring_guid'] virgo.config['query_endpoints'] = virgo.config['monitoring_query_endpoints'] virgo.config['snet_region'] = virgo.config['monitoring_snet_region'] local agent = MonitoringAgent:new(options, types) if not argv.args.u then return agent:start(options) end Setup:new(argv, options.configFile, agent):run() end return Entry
fix: read correct argv field for pidfile
fix: read correct argv field for pidfile
Lua
apache-2.0
christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent
d54414e0ba1758c8056e67e16ffe9e2edbd87e8f
tests/test.lua
tests/test.lua
-- Prosody IM v0.3 -- 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. -- function run_all_tests() dotest "util.jid" dotest "util.multitable" dotest "core.stanza_router" dotest "core.s2smanager" dotest "core.configmanager" dotest "util.stanza" dosingletest("test_sasl.lua", "latin1toutf8"); end local verbosity = tonumber(arg[1]) or 2; package.path = package.path..";../?.lua"; package.cpath = package.cpath..";../?.so"; require "util.import" local env_mt = { __index = function (t,k) return rawget(_G, k) or print("WARNING: Attempt to access nil global '"..tostring(k).."'"); end }; function testlib_new_env(t) return setmetatable(t or {}, env_mt); end function assert_equal(a, b, message, level) if not (a == b) then error("\n assert_equal failed: "..tostring(a).." ~= "..tostring(b)..(message and ("\n Message: "..message) or ""), (level or 1) + 1); elseif verbosity >= 4 then print("assert_equal succeeded: "..tostring(a).." == "..tostring(b)); end end function assert_table(a, message, level) assert_equal(type(a), "table", message, (level or 1) + 1); end function assert_function(a, message, level) assert_equal(type(a), "function", message, (level or 1) + 1); end function assert_string(a, message, level) assert_equal(type(a), "string", message, (level or 1) + 1); end function assert_boolean(a, message) assert_equal(type(a), "boolean", message); end function assert_is(a, message) assert_equal(not not a, true, message); end function assert_is_not(a, message) assert_equal(not not a, false, message); end function dosingletest(testname, fname) local tests = setmetatable({}, { __index = _G }); tests.__unit = testname; tests.__test = fname; local chunk, err = loadfile(testname); if not chunk then print("WARNING: ", "Failed to load tests for "..testname, err); return; end setfenv(chunk, tests); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise tests for "..testname, err); return; end if type(tests[fname]) ~= "function" then error(testname.." has no test '"..fname.."'", 0); end local line_hook, line_info = new_line_coverage_monitor(testname); debug.sethook(line_hook, "l") local success, ret = pcall(tests[fname]); debug.sethook(); if not success then print("TEST FAILED! Unit: ["..testname.."] Function: ["..fname.."]"); print(" Location: "..ret:gsub(":%s*\n", "\n")); line_info(fname, false, report_file); elseif verbosity >= 2 then print("TEST SUCCEEDED: ", testname, fname); print(string.format("TEST COVERED %d/%d lines", line_info(fname, true, report_file))); else line_info(name, success, report_file); end end function dotest(unitname) local tests = setmetatable({}, { __index = _G }); tests.__unit = unitname; local chunk, err = loadfile("test_"..unitname:gsub("%.", "_")..".lua"); if not chunk then print("WARNING: ", "Failed to load tests for "..unitname, err); return; end setfenv(chunk, tests); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise tests for "..unitname, err); return; end local unit = setmetatable({}, { __index = setmetatable({ module = function () end }, { __index = _G }) }); local fn = "../"..unitname:gsub("%.", "/")..".lua"; local chunk, err = loadfile(fn); if not chunk then print("WARNING: ", "Failed to load module: "..unitname, err); return; end setfenv(chunk, unit); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise module: "..unitname, err); return; end for name, f in pairs(unit) do local test = rawget(tests, name); if type(f) ~= "function" then if verbosity >= 3 then print("INFO: ", "Skipping "..unitname.."."..name.." because it is not a function"); end elseif type(test) ~= "function" then if verbosity >= 1 then print("WARNING: ", unitname.."."..name.." has no test!"); end else local line_hook, line_info = new_line_coverage_monitor(fn); debug.sethook(line_hook, "l") local success, ret = pcall(test, f, unit); debug.sethook(); if not success then print("TEST FAILED! Unit: ["..unitname.."] Function: ["..name.."]"); print(" Location: "..ret:gsub(":%s*\n", "\n")); line_info(name, false, report_file); elseif verbosity >= 2 then print("TEST SUCCEEDED: ", unitname, name); print(string.format("TEST COVERED %d/%d lines", line_info(name, true, report_file))); else line_info(name, success, report_file); end end end end function runtest(f, msg) if not f then print("SUBTEST NOT FOUND: "..(msg or "(no description)")); return; end local success, ret = pcall(f); if success and verbosity >= 2 then print("SUBTEST PASSED: "..(msg or "(no description)")); elseif (not success) and verbosity >= 0 then print("SUBTEST FAILED: "..(msg or "(no description)")); error(ret, 0); end end function new_line_coverage_monitor(file) local lines_hit, funcs_hit = {}, {}; local total_lines, covered_lines = 0, 0; for line in io.lines(file) do total_lines = total_lines + 1; end return function (event, line) -- Line hook if not lines_hit[line] then local info = debug.getinfo(2, "fSL") if not info.source:find(file) then return; end if not funcs_hit[info.func] and info.activelines then funcs_hit[info.func] = true; for line in pairs(info.activelines) do lines_hit[line] = false; -- Marks it as hittable, but not hit yet end end if lines_hit[line] == false then --print("New line hit: "..line.." in "..debug.getinfo(2, "S").source); lines_hit[line] = true; covered_lines = covered_lines + 1; end end end, function (test_name, success) -- Get info local fn = file:gsub("^%W*", ""); local total_active_lines = 0; local coverage_file = io.open("reports/coverage_"..fn:gsub("%W+", "_")..".report", "a+"); for line, active in pairs(lines_hit) do if active ~= nil then total_active_lines = total_active_lines + 1; end if coverage_file then if active == false then coverage_file:write(fn, "|", line, "|", name or "", "|miss\n"); else coverage_file:write(fn, "|", line, "|", name or "", "|", tostring(success), "\n"); end end end if coverage_file then coverage_file:close(); end return covered_lines, total_active_lines, lines_hit; end end run_all_tests()
-- Prosody IM v0.3 -- 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. -- function run_all_tests() dotest "util.jid" dotest "util.multitable" dotest "core.stanza_router" dotest "core.s2smanager" dotest "core.configmanager" dotest "util.stanza" dosingletest("test_sasl.lua", "latin1toutf8"); end local verbosity = tonumber(arg[1]) or 2; if os.getenv("WINDIR") then package.path = package.path..";..\\?.lua"; package.cpath = package.cpath..";..\\?.dll"; else package.path = package.path..";../?.lua"; package.cpath = package.cpath..";../?.so"; end require "util.import" local env_mt = { __index = function (t,k) return rawget(_G, k) or print("WARNING: Attempt to access nil global '"..tostring(k).."'"); end }; function testlib_new_env(t) return setmetatable(t or {}, env_mt); end function assert_equal(a, b, message, level) if not (a == b) then error("\n assert_equal failed: "..tostring(a).." ~= "..tostring(b)..(message and ("\n Message: "..message) or ""), (level or 1) + 1); elseif verbosity >= 4 then print("assert_equal succeeded: "..tostring(a).." == "..tostring(b)); end end function assert_table(a, message, level) assert_equal(type(a), "table", message, (level or 1) + 1); end function assert_function(a, message, level) assert_equal(type(a), "function", message, (level or 1) + 1); end function assert_string(a, message, level) assert_equal(type(a), "string", message, (level or 1) + 1); end function assert_boolean(a, message) assert_equal(type(a), "boolean", message); end function assert_is(a, message) assert_equal(not not a, true, message); end function assert_is_not(a, message) assert_equal(not not a, false, message); end function dosingletest(testname, fname) local tests = setmetatable({}, { __index = _G }); tests.__unit = testname; tests.__test = fname; local chunk, err = loadfile(testname); if not chunk then print("WARNING: ", "Failed to load tests for "..testname, err); return; end setfenv(chunk, tests); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise tests for "..testname, err); return; end if type(tests[fname]) ~= "function" then error(testname.." has no test '"..fname.."'", 0); end local line_hook, line_info = new_line_coverage_monitor(testname); debug.sethook(line_hook, "l") local success, ret = pcall(tests[fname]); debug.sethook(); if not success then print("TEST FAILED! Unit: ["..testname.."] Function: ["..fname.."]"); print(" Location: "..ret:gsub(":%s*\n", "\n")); line_info(fname, false, report_file); elseif verbosity >= 2 then print("TEST SUCCEEDED: ", testname, fname); print(string.format("TEST COVERED %d/%d lines", line_info(fname, true, report_file))); else line_info(name, success, report_file); end end function dotest(unitname) local tests = setmetatable({}, { __index = _G }); tests.__unit = unitname; local chunk, err = loadfile("test_"..unitname:gsub("%.", "_")..".lua"); if not chunk then print("WARNING: ", "Failed to load tests for "..unitname, err); return; end setfenv(chunk, tests); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise tests for "..unitname, err); return; end local unit = setmetatable({}, { __index = setmetatable({ module = function () end }, { __index = _G }) }); local fn = "../"..unitname:gsub("%.", "/")..".lua"; local chunk, err = loadfile(fn); if not chunk then print("WARNING: ", "Failed to load module: "..unitname, err); return; end setfenv(chunk, unit); local success, err = pcall(chunk); if not success then print("WARNING: ", "Failed to initialise module: "..unitname, err); return; end for name, f in pairs(unit) do local test = rawget(tests, name); if type(f) ~= "function" then if verbosity >= 3 then print("INFO: ", "Skipping "..unitname.."."..name.." because it is not a function"); end elseif type(test) ~= "function" then if verbosity >= 1 then print("WARNING: ", unitname.."."..name.." has no test!"); end else local line_hook, line_info = new_line_coverage_monitor(fn); debug.sethook(line_hook, "l") local success, ret = pcall(test, f, unit); debug.sethook(); if not success then print("TEST FAILED! Unit: ["..unitname.."] Function: ["..name.."]"); print(" Location: "..ret:gsub(":%s*\n", "\n")); line_info(name, false, report_file); elseif verbosity >= 2 then print("TEST SUCCEEDED: ", unitname, name); print(string.format("TEST COVERED %d/%d lines", line_info(name, true, report_file))); else line_info(name, success, report_file); end end end end function runtest(f, msg) if not f then print("SUBTEST NOT FOUND: "..(msg or "(no description)")); return; end local success, ret = pcall(f); if success and verbosity >= 2 then print("SUBTEST PASSED: "..(msg or "(no description)")); elseif (not success) and verbosity >= 0 then print("SUBTEST FAILED: "..(msg or "(no description)")); error(ret, 0); end end function new_line_coverage_monitor(file) local lines_hit, funcs_hit = {}, {}; local total_lines, covered_lines = 0, 0; for line in io.lines(file) do total_lines = total_lines + 1; end return function (event, line) -- Line hook if not lines_hit[line] then local info = debug.getinfo(2, "fSL") if not info.source:find(file) then return; end if not funcs_hit[info.func] and info.activelines then funcs_hit[info.func] = true; for line in pairs(info.activelines) do lines_hit[line] = false; -- Marks it as hittable, but not hit yet end end if lines_hit[line] == false then --print("New line hit: "..line.." in "..debug.getinfo(2, "S").source); lines_hit[line] = true; covered_lines = covered_lines + 1; end end end, function (test_name, success) -- Get info local fn = file:gsub("^%W*", ""); local total_active_lines = 0; local coverage_file = io.open("reports/coverage_"..fn:gsub("%W+", "_")..".report", "a+"); for line, active in pairs(lines_hit) do if active ~= nil then total_active_lines = total_active_lines + 1; end if coverage_file then if active == false then coverage_file:write(fn, "|", line, "|", name or "", "|miss\n"); else coverage_file:write(fn, "|", line, "|", name or "", "|", tostring(success), "\n"); end end end if coverage_file then coverage_file:close(); end return covered_lines, total_active_lines, lines_hit; end end run_all_tests()
Fixed tests/test.lua to work on Windows
Fixed tests/test.lua to work on Windows
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
396e2510c1cd64047c0a2a0804db9fb5ab649c43
OS/DiskOS/boot.lua
OS/DiskOS/boot.lua
--Building the peripherals APIs-- local perglob = {GPU = true, CPU = true, Keyboard = true} --The perihperals to make global not in a table. local _,perlist = coroutine.yield("BIOS:listPeripherals") for peripheral,funcs in pairs(perlist) do local holder if perglob[peripheral] then holder = _G else --Rename HDD to fs (Easier to spell) _G[peripheral == "HDD" and "fs" or peripheral] = {} holder = _G[peripheral == "HDD" and "fs" or peripheral] end for _,func in ipairs(funcs) do local command = peripheral..":"..func holder[func] = function(...) local args = {coroutine.yield(command,...)} if not args[1] then return error(args[2]) end local nargs = {} for k,v in ipairs(args) do if k >1 then table.insert(nargs,k-1,v) end end return unpack(nargs) end end end --A usefull split function function split(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end --Restore Require Function-- local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then nargs[k-factor] = v end end return nargs end package = {loaded = {}} --Fake package system function require(path,...) if type(path) ~= "string" then return error("Require path must be a string, provided: "..type(path)) end path = path:gsub("%.","/")..".lua" if package.loaded[path] then return unpack(package.loaded[path]) end local chunk, err = fs.load(path) if not chunk then return error(err or "Load error ("..tostring(path)..")") end local args = {pcall(chunk,path,...)} if not args[1] then return error(args[2] or "Runtime error") end package.loaded[path] = extractArgs(args,1) return unpack(package.loaded[path]) end keyrepeat(true) --Enable keyrepeat require("C://api") --Load CartOS APIs local terminal = require("C://terminal") terminal.loop()
--Building the peripherals APIs-- local perglob = {GPU = true, CPU = true, Keyboard = true} --The perihperals to make global not in a table. local _,perlist = coroutine.yield("BIOS:listPeripherals") for peripheral,funcs in pairs(perlist) do local holder if perglob[peripheral] then holder = _G else --Rename HDD to fs (Easier to spell) _G[peripheral == "HDD" and "fs" or peripheral] = {} holder = _G[peripheral == "HDD" and "fs" or peripheral] end for _,func in ipairs(funcs) do local command = peripheral..":"..func holder[func] = function(...) local args = {coroutine.yield(command,...)} if not args[1] then return error(args[2]) end local nargs = {} for k,v in ipairs(args) do if k >1 then table.insert(nargs,k-1,v) end end return unpack(nargs) end end end --A usefull split function function split(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end --Restore Require Function-- local function extractArgs(args,factor) local nargs = {} for k,v in ipairs(args) do if k > factor then nargs[k-factor] = v end end return nargs end package = {loaded = {}} --Fake package system function require(path,...) if type(path) ~= "string" then return error("Require path must be a string, provided: "..type(path)) end path = path:gsub("%.","/")..".lua" if package.loaded[path] then return unpack(package.loaded[path]) end local chunk, err = fs.load(path) if not chunk then return error(err or "Load error ("..tostring(path)..")") end local args = {pcall(chunk,path,...)} if not args[1] then return error(args[2] or "Runtime error") end package.loaded[path] = extractArgs(args,1) return unpack(package.loaded[path]) end keyrepeat(true) --Enable keyrepeat textinput(true) --Show the keyboard on mobile devices require("C://api") --Load CartOS APIs local terminal = require("C://terminal") terminal.loop()
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
3e3f6d46e2c347f35912eaf9916d5a086dca3f8c
OS/DiskOS/Programs/pastebin.lua
OS/DiskOS/Programs/pastebin.lua
--This program is based on ComputerCraft one: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/programs/http/pastebin.lua local term = require("C://terminal") local function printUsage() color(9) print("Usages:") color(7) print("pastebin put <filename>") print("pastebin get <code> <filename>") end local function printError(str) color(8) print(str) color(7) end local function getName(str) local path, name, ext = string.match(str, "(.-)([^\\]-([^%.]+))$") return name end local function request(url, args) local ticket = WEB.send(url,args) for event, id, url, data, errnum, errmsg, errline in pullEvent do if event == "webrequest" then if id == ticket then if data then data.code = tonumber(data.code) if data.code < 200 or data.code >= 300 then return false, "HTTP Error: "..data.code end if data.body:sub(1,15) == "Bad API request" then return false, "API Error: "..data.body end return data.body else return false, errmsg end end end end end local tArgs = { ... } if #tArgs < 2 then printUsage() return end if not WEB then printError( "Pastebin requires WEB peripheral" ) printError( "Edit /bios/bconf.lua and make sure that the WEB peripheral exists" ) return end local function get(paste) color(9) print("Connecting to pastebin.com...") flip() color(7) local response, err = request("https://pastebin.com/raw/"..WEB.urlEncode(paste)) if response then color(11) print( "Success." ) color(7) flip() sleep(0.01) return response else printError("Failed: "..tostring(err)) end end local sCommand = tArgs[1] if sCommand == "put" then -- Upload a file to pastebin.com -- Determine file to upload local sFile = tArgs[2] local sPath = term.resolve(sFile) if not fs.exists(sPath) or fs.isDirectory(sPath) then printError("No such file") return end -- Read in the file local sName = getName(sPath) local sText = fs.read(sPath) -- POST the contents to pastebin color(9) print("Connecting to pastebin.com...") color(7) flip() local key = "e31065c6df5a451f3df3fdf5f4c2be61" local response, err = request("https://pastebin.com/api/api_post.php",{ method = "POST", data = "api_option=paste&".. "api_dev_key="..key.."&".. "api_paste_format=lua&".. "api_paste_name="..WEB.urlEncode(sName).."&".. "api_paste_code="..WEB.urlEncode(sText) }) if response then color(11) print("Success.") flip() sleep(0.01) color(7) local sCode = string.match(response, "[^/]+$") color(12) print("Uploaded as "..response) sleep(0.01) color(7) print('Run "',false) color(6) print('pastebin get '..sCode,false) color(7) print('" to download anywhere') sleep(0.01) else printError("Failed: "..tostring(err)) end elseif sCommand == "get" then -- Download a file from pastebin.com if #tArgs < 3 then printUsage() return end --Determine file to download local sCode = tArgs[2] local sFile = tArgs[3] local sPath = term.resolve(sFile) if fs.exists( sPath ) then printError("File already exists") return end -- GET the contents from pastebin local res = get(sCode) if res then fs.write(sPath,res) color(12) print("Downloaded as "..sFile) sleep(0.01) color(7) end else printUsage() return end
--This program is based on ComputerCraft one: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/programs/http/pastebin.lua local term = require("C://terminal") local function printUsage() color(9) print("Usages:") color(7) print("pastebin put <filename>") print("pastebin get <code> <filename>") end local function printError(str) color(8) print(str) color(7) end local function getName(str) local path, name, ext = string.match(str, "(.-)([^\\/]-%.?([^%.\\/]*))$") return name end local function request(url, args) local ticket = WEB.send(url,args) for event, id, url, data, errnum, errmsg, errline in pullEvent do if event == "webrequest" then if id == ticket then if data then data.code = tonumber(data.code) if (data.code < 200 or data.code >= 300) and data.body:sub(1,21) ~= "https://pastebin.com/" then cprint("Body: "..tostring(data.body)) return false, "HTTP Error: "..data.code end if data.body:sub(1,15) == "Bad API request" then return false, "API Error: "..data.body end return data.body else return false, errmsg end end end end end local tArgs = { ... } if #tArgs < 2 then printUsage() return end if not WEB then printError( "Pastebin requires WEB peripheral" ) printError( "Edit /bios/bconf.lua and make sure that the WEB peripheral exists" ) return end local function get(paste) color(9) print("Connecting to pastebin.com...") flip() color(7) local response, err = request("https://pastebin.com/raw/"..WEB.urlEncode(paste)) if response then color(11) print( "Success." ) color(7) flip() sleep(0.01) return response else printError("Failed: "..tostring(err)) end end local sCommand = tArgs[1] if sCommand == "put" then -- Upload a file to pastebin.com -- Determine file to upload local sFile = tArgs[2] local sPath = term.resolve(sFile) if not fs.exists(sPath) or fs.isDirectory(sPath) then printError("No such file") return end -- Read in the file local sName = getName(sPath:gsub("///","/")) local sText = fs.read(sPath) -- POST the contents to pastebin color(9) print("Connecting to pastebin.com...") color(7) flip() local key = "e31065c6df5a451f3df3fdf5f4c2be61" local response, err = request("https://pastebin.com/api/api_post.php",{ method = "POST", data = "api_option=paste&".. "api_dev_key="..key.."&".. "api_paste_format=lua&".. "api_paste_name="..WEB.urlEncode(sName).."&".. "api_paste_code="..WEB.urlEncode(sText) }) if response then color(11) print("Success.") flip() sleep(0.01) color(7) local sCode = string.match(response, "[^/]+$") color(12) print("Uploaded as "..response) sleep(0.01) color(7) print('Run "',false) color(6) print('pastebin get '..sCode,false) color(7) print('" to download anywhere') sleep(0.01) else printError("Failed: "..tostring(err)) end elseif sCommand == "get" then -- Download a file from pastebin.com if #tArgs < 3 then printUsage() return end --Determine file to download local sCode = tArgs[2] local sFile = tArgs[3] local sPath = term.resolve(sFile) if fs.exists( sPath ) then printError("File already exists") return end -- GET the contents from pastebin local res = get(sCode) if res then fs.write(sPath,res) color(12) print("Downloaded as "..sFile) sleep(0.01) color(7) end else printUsage() return end
Bugfixes
Bugfixes
Lua
mit
RamiLego4Game/LIKO-12
7e719a3fd0ee7a220920f6609300a39d9f21ffc9
lib/resty/chash/server.lua
lib/resty/chash/server.lua
local jchash = require "resty.chash.jchash" local ok, new_table = pcall(require, "table.new") if not ok then new_table = function (narr, nrec) return {} end end local function svname(server) -- @server: {addr, port, id} -- @return: concat the addr and port with ":" as seperator return server[1] .. ":" .. tostring(server[2]) .. "#" .. tostring(server[3]) end local function init_name2index(servers) -- map server name to index local map = {} for index, s in ipairs(servers) do -- name is just the concat of addr , port and inner id map[ svname(s) ] = index end return map end local function expand_servers(servers) -- expand servers list of {addr, port, weight} into a list of {addr, port, id} local total_weight = 0 for _, s in ipairs(servers) do total_weight = total_weight + (s[3] or 1) end local expanded_servers = new_table(total_weight, 0) local weight for _, s in ipairs(servers) do weight = s[3] or 1 for id = 1, weight do expanded_servers[#expanded_servers + 1] = {s[1], s[2], id} end end assert(#expanded_servers == total_weight, "expand_servers size not match") return expanded_servers end local function update_name2index(old_servers, new_servers) -- new servers may have some servers of the same name in the old ones. -- we could assign the same index(if in range) to the server of same name, -- and as to new servers whose name are new will be assigned to indexs that're -- not occupied local old_name2index = init_name2index(old_servers) local new_name2index = init_name2index(new_servers) local new_size = #new_servers -- new_size is also the maxmuim index local old_size = #old_servers local unused_indexs = {} for old_index, old_sv in ipairs(old_servers) do if old_index <= new_size then local old_sv_name = svname(old_sv) if new_name2index[ old_sv_name ] then -- restore the old_index new_name2index[ old_sv_name ] = old_index else -- old_index can be recycled unused_indexs[#unused_indexs + 1] = old_index end else -- index that exceed maxmium index is of no use, we should mark it nil. -- the next next loop (assigning unused_indexs) will make use of this mark old_name2index[ svname(old_sv) ] = nil end end for i = old_size + 1, new_size do -- only loop when old_size < new_size unused_indexs[#unused_indexs + 1] = i end -- assign the unused_indexs to the real new servers local index = 1 for _, new_sv in ipairs(new_servers) do local new_sv_name = svname(new_sv) if not old_name2index[ new_sv_name ] then -- it's a new server, or an old server whose old index is too big assert(index <= #unused_indexs, "no enough indexs for new server") new_name2index[ new_sv_name ] = unused_indexs[index] index = index + 1 end end assert(index == #unused_indexs + 1, "recycled indexs are not exhausted") return new_name2index end local _M = {} local mt = { __index = _M } function _M.new(servers) assert(servers, "nil servers") return setmetatable({servers = expand_servers(servers)}, mt) end -- instance methods function _M.lookup(self, key) -- @key: user defined string, eg. uri -- @return: {addr, port, id} -- the `id` is a number in [1, weight], to identify server of same addr and port, if #self.servers == 0 then return nil end local index = jchash.hash_short_str(key, #self.servers) return self.servers[index] end function _M.update_servers(self, new_servers) -- @new_servers: remove all old servers, and use the new servers -- but we would keep the server whose name is not changed -- in the same `id` slot, so consistence is maintained. assert(new_servers, "nil new_servers") local old_servers = self.servers local new_servers = expand_servers(new_servers) local name2index = update_name2index(old_servers, new_servers) self.servers = new_table(#new_servers, 0) for _, s in ipairs(new_servers) do self.servers[name2index[ svname(s) ]] = s end end function _M.debug(self) print("* Instance Info *") print("* size: " .. tostring(#self.servers)) print("* servers -> id ") for id, s in ipairs(self.servers) do print(svname(s) .. " -> " .. tostring(id)) end print("\n") end function _M.dump(self) -- @return: deepcopy a self.servers -- this can be use to save the server list to a file or something -- and restore it back some time later. eg. nginx restart/reload -- -- please NOTE: the data being dumped is not the same as the data we -- use to do _M.new or _M.update_servers, though it looks the same, the third -- field in the {addr, port, id} is an `id`, NOT a `weight` local servers = {} for index, sv in ipairs(self.servers) do servers[index] = {sv[1], sv[2], sv[3]} -- {addr, port, id} end return servers end function _M.restore(self, servers) assert(servers, "nil servers") -- restore servers from dump (deepcopy the servers) self.servers = {} for index, sv in ipairs(servers) do self.servers[index] = {sv[1], sv[2], sv[3]} end end _M._VERSION = "0.1.0" return _M
local jchash = require "resty.chash.jchash" local ok, new_table = pcall(require, "table.new") if not ok then new_table = function (narr, nrec) return {} end end local function svname(server) -- @server: {addr, port, id} -- @return: concat the addr and port with ":" as seperator return string.format("%s:%s#%s", tostring(server[1]), tostring(server[2]), tostring(server[3])) end local function init_name2index(servers) -- map server name to index local map = {} for index, s in ipairs(servers) do -- name is just the concat of addr , port and inner id map[ svname(s) ] = index end return map end local function expand_servers(servers) -- expand servers list of {addr, port, weight} into a list of {addr, port, id} local total_weight = 0 for _, s in ipairs(servers) do total_weight = total_weight + (s[3] or 1) end local expanded_servers = new_table(total_weight, 0) local weight for _, s in ipairs(servers) do weight = s[3] or 1 for id = 1, weight do expanded_servers[#expanded_servers + 1] = {s[1], s[2], id} end end assert(#expanded_servers == total_weight, "expand_servers size not match") return expanded_servers end local function update_name2index(old_servers, new_servers) -- new servers may have some servers of the same name in the old ones. -- we could assign the same index(if in range) to the server of same name, -- and as to new servers whose name are new will be assigned to indexs that're -- not occupied local old_name2index = init_name2index(old_servers) local new_name2index = init_name2index(new_servers) local new_size = #new_servers -- new_size is also the maxmuim index local old_size = #old_servers local unused_indexs = {} for old_index, old_sv in ipairs(old_servers) do if old_index <= new_size then local old_sv_name = svname(old_sv) if new_name2index[ old_sv_name ] then -- restore the old_index new_name2index[ old_sv_name ] = old_index else -- old_index can be recycled unused_indexs[#unused_indexs + 1] = old_index end else -- index that exceed maxmium index is of no use, we should mark it nil. -- the next next loop (assigning unused_indexs) will make use of this mark old_name2index[ svname(old_sv) ] = nil end end for i = old_size + 1, new_size do -- only loop when old_size < new_size unused_indexs[#unused_indexs + 1] = i end -- assign the unused_indexs to the real new servers local index = 1 for _, new_sv in ipairs(new_servers) do local new_sv_name = svname(new_sv) if not old_name2index[ new_sv_name ] then -- it's a new server, or an old server whose old index is too big assert(index <= #unused_indexs, "no enough indexs for new server") new_name2index[ new_sv_name ] = unused_indexs[index] index = index + 1 end end assert(index == #unused_indexs + 1, "recycled indexs are not exhausted") return new_name2index end local _M = {} local mt = { __index = _M } function _M.new(servers) assert(servers, "nil servers") return setmetatable({servers = expand_servers(servers)}, mt) end -- instance methods function _M.lookup(self, key) -- @key: user defined string, eg. uri -- @return: {addr, port, id} -- the `id` is a number in [1, weight], to identify server of same addr and port, if #self.servers == 0 then return nil end local index = jchash.hash_short_str(key, #self.servers) return self.servers[index] end function _M.update_servers(self, new_servers) -- @new_servers: remove all old servers, and use the new servers -- but we would keep the server whose name is not changed -- in the same `id` slot, so consistence is maintained. assert(new_servers, "nil new_servers") local old_servers = self.servers local new_servers = expand_servers(new_servers) local name2index = update_name2index(old_servers, new_servers) self.servers = new_table(#new_servers, 0) for _, s in ipairs(new_servers) do self.servers[name2index[ svname(s) ]] = s end end function _M.debug(self) print("* Instance Info *") print("* size: " .. tostring(#self.servers)) print("* servers -> id ") for id, s in ipairs(self.servers) do print(svname(s) .. " -> " .. tostring(id)) end print("\n") end function _M.dump(self) -- @return: deepcopy a self.servers -- this can be use to save the server list to a file or something -- and restore it back some time later. eg. nginx restart/reload -- -- please NOTE: the data being dumped is not the same as the data we -- use to do _M.new or _M.update_servers, though it looks the same, the third -- field in the {addr, port, id} is an `id`, NOT a `weight` local servers = {} for index, sv in ipairs(self.servers) do servers[index] = {sv[1], sv[2], sv[3]} -- {addr, port, id} end return servers end function _M.restore(self, servers) assert(servers, "nil servers") -- restore servers from dump (deepcopy the servers) self.servers = {} for index, sv in ipairs(servers) do self.servers[index] = {sv[1], sv[2], sv[3]} end end _M._VERSION = "0.1.1" return _M
fix snname func, convert all data to string before concat
fix snname func, convert all data to string before concat
Lua
mit
ruoshan/lua-resty-jump-consistent-hash,ruoshan/lua-resty-jump-consistent-hash
0ccd128622327417649bd83aad6eda088b2f7dfe
pages/shop/checkout/post.lua
pages/shop/checkout/post.lua
function post() if not app.Shop.Enabled then http:redirect("/") return end if not session:isLogged() then http:redirect("/subtopic/login") return end local cart = session:get("shop-cart") if cart == nil then http:redirect("/") return end local cartdata = {} local totalprice = 0 for name, count in pairs(cart) do cartdata[name] = {} cartdata[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) if cartdata[name].offer == nil then http:redirect("/") return end totalprice = tonumber(cartdata[name].offer.price) * count cartdata[name].count = count end local discount = db:singleQuery("SELECT id, valid_till, discount, uses, unlimited FROM castro_shop_discounts WHERE code = ?", http.postValues.discount) if discount ~= nil then if os.time() < tonumber(discount.valid_till) then if discount.unlimited or tonumber(discount.uses) > 0 then totalprice = totalprice - ((tonumber(discount.discount) * totalprice) / 100) db:execute("UPDATE castro_shop_discounts SET uses = uses - 1 WHERE id = ?", discount.id) end end end local account = session:loggedAccount() if account.castro.Points < totalprice then session:setFlash("error", "You need more points") http:redirect("/subtopic/shop/view") return end db:execute("UPDATE castro_accounts SET points = points - ? WHERE account_id = ?", totalprice, account.Id) session:setFlash("success", "You paid " .. totalprice .. " for all your cart items") http:redirect("/subtopic/shop/view") end
function post() if not app.Shop.Enabled then http:redirect("/") return end if not session:isLogged() then http:redirect("/subtopic/login") return end local cart = session:get("shop-cart") if cart == nil then http:redirect("/") return end local cartdata = {} local totalprice = 0 for name, count in pairs(cart) do cartdata[name] = {} cartdata[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) if cartdata[name].offer == nil then http:redirect("/") return end totalprice = tonumber(cartdata[name].offer.price) * count cartdata[name].count = count end local discount = db:singleQuery("SELECT id, valid_till, discount, uses, unlimited FROM castro_shop_discounts WHERE code = ?", http.postValues.discount) if discount ~= nil then if os.time() < tonumber(discount.valid_till) then if discount.unlimited or tonumber(discount.uses) > 0 then totalprice = totalprice - ((tonumber(discount.discount) * totalprice) / 100) db:execute("UPDATE castro_shop_discounts SET uses = uses - 1 WHERE id = ?", discount.id) end end end local account = session:loggedAccount() if account.castro.Points < totalprice then session:setFlash("error", "You need more points") http:redirect("/subtopic/shop/view") return end db:execute("UPDATE castro_accounts SET points = points - ? WHERE account_id = ?", totalprice, account.ID) session:set("shop-cart", {}) session:setFlash("success", "You paid " .. totalprice .. " for all your cart items") http:redirect("/subtopic/shop/view") end
Shop checkout
Shop checkout Fix a typo which caused points to not get removed Empty cart after checkout
Lua
mit
Raggaer/castro,Raggaer/castro,Raggaer/castro
6db3ca42966c8b1e22b2df2cddee556653b5b710
Modules/Shared/TimeSync/TimeSyncService.lua
Modules/Shared/TimeSync/TimeSyncService.lua
--- Syncronizes time -- @module TimeSyncService local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local RunService = game:GetService("RunService") local GetRemoteEvent = require("GetRemoteEvent") local GetRemoteFunction = require("GetRemoteFunction") local MasterClock = require("MasterClock") local Promise = require("Promise") local PromiseGetRemoteEvent = require("PromiseGetRemoteEvent") local PromiseGetRemoteFunction = require("PromiseGetRemoteFunction") local PromiseUtils = require("PromiseUtils") local SlaveClock = require("SlaveClock") local TimeSyncConstants = require("TimeSyncConstants") local TimeSyncUtils = require("TimeSyncUtils") local TimeSyncService = {} function TimeSyncService:Init() assert(not self._clockPromise, "TimeSyncService is already initialized!") self._clockPromise = Promise.new() if RunService:IsServer() then self._clockPromise:Resolve(self:_buildMasterClock()) end if RunService:IsClient() then -- This also handles play solo edgecase where self._clockPromise:Resolve(self:_promiseSlaveClock()) end end function TimeSyncService:IsSynced() return self._clockPromise:IsResolved() end function TimeSyncService:WaitForSyncedClock() return self._clockPromise:Wait() end function TimeSyncService:GetSyncedClock() if self._clockPromise:IsResolved() then return self._clockPromise:Wait() end return nil end function TimeSyncService:PromiseSyncedClock() return Promise.resolved(self._clockPromise) end function TimeSyncService:_buildMasterClock() local remoteEvent = GetRemoteEvent(TimeSyncConstants.REMOTE_EVENT_NAME) local remoteFunction = GetRemoteFunction(TimeSyncConstants.REMOTE_FUNCTION_NAME) return MasterClock.new(remoteEvent, remoteFunction) end function TimeSyncService:_promiseSlaveClock() return PromiseUtils.all({ PromiseGetRemoteEvent(TimeSyncConstants.REMOTE_EVENT_NAME); PromiseGetRemoteFunction(TimeSyncConstants.REMOTE_FUNCTION_NAME); }):Then(function(remoteEvent, remoteFunction) return TimeSyncUtils.promiseClockSynced(SlaveClock.new(remoteEvent, remoteFunction)) end) end return TimeSyncService
--- Syncronizes time -- @module TimeSyncService local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local RunService = game:GetService("RunService") local GetRemoteEvent = require("GetRemoteEvent") local GetRemoteFunction = require("GetRemoteFunction") local MasterClock = require("MasterClock") local Promise = require("Promise") local PromiseGetRemoteEvent = require("PromiseGetRemoteEvent") local PromiseGetRemoteFunction = require("PromiseGetRemoteFunction") local PromiseUtils = require("PromiseUtils") local SlaveClock = require("SlaveClock") local TimeSyncConstants = require("TimeSyncConstants") local TimeSyncUtils = require("TimeSyncUtils") local TimeSyncService = {} function TimeSyncService:Init() assert(not self._clockPromise, "TimeSyncService is already initialized!") self._clockPromise = Promise.new() if RunService:IsServer() then self._clockPromise:Resolve(self:_buildMasterClock()) end if RunService:IsClient() then -- This also handles play solo edgecase where self._clockPromise:Resolve(self:_promiseSlaveClock()) end end function TimeSyncService:IsSynced() assert(self._clockPromise) return self._clockPromise:IsFulfilled() end function TimeSyncService:WaitForSyncedClock() assert(self._clockPromise) return self._clockPromise:Wait() end function TimeSyncService:GetSyncedClock() assert(self._clockPromise) if self._clockPromise:IsFulfilled() then return self._clockPromise:Wait() end return nil end function TimeSyncService:PromiseSyncedClock() assert(self._clockPromise) return Promise.resolved(self._clockPromise) end function TimeSyncService:_buildMasterClock() local remoteEvent = GetRemoteEvent(TimeSyncConstants.REMOTE_EVENT_NAME) local remoteFunction = GetRemoteFunction(TimeSyncConstants.REMOTE_FUNCTION_NAME) return MasterClock.new(remoteEvent, remoteFunction) end function TimeSyncService:_promiseSlaveClock() return PromiseUtils.all({ PromiseGetRemoteEvent(TimeSyncConstants.REMOTE_EVENT_NAME); PromiseGetRemoteFunction(TimeSyncConstants.REMOTE_FUNCTION_NAME); }):Then(function(remoteEvent, remoteFunction) return TimeSyncUtils.promiseClockSynced(SlaveClock.new(remoteEvent, remoteFunction)) end) end return TimeSyncService
Fix time sync
Fix time sync
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
f1491ad1d1df3e0b4d22af8329c95106e794ba01
MCServer/Plugins/DiamondMover/DiamondMover.lua
MCServer/Plugins/DiamondMover/DiamondMover.lua
-- DiamondMover.lua -- An example Lua plugin using the cBlockArea object -- When a player rclks with a diamond in their hand, an area around the clicked block is moved in the direction the player is facing -- Global variables MOVER_SIZE_X = 4; MOVER_SIZE_Y = 4; MOVER_SIZE_Z = 4; function Initialize(Plugin) Plugin:SetName("DiamondMover"); Plugin:SetVersion(1); cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_USED_ITEM, OnPlayerUsedItem); return true; end function OnPlayerUsedItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ) -- Don't check if the direction is in the air if (BlockFace == -1) then return false; end; if (Player:HasPermission("diamondmover.move") == false) then return true; end; -- Rclk with a diamond to push in the direction the player is facing if (Player:GetEquippedItem().m_ItemType == E_ITEM_DIAMOND) then local Area = cBlockArea(); Area:Read(Player:GetWorld(), BlockX - MOVER_SIZE_X, BlockX + MOVER_SIZE_X, BlockY - MOVER_SIZE_Y, BlockY + MOVER_SIZE_Y, BlockZ - MOVER_SIZE_Z, BlockZ + MOVER_SIZE_Z ); local PlayerPitch = Player:GetPitch(); if (PlayerPitch < -70) then -- looking up BlockY = BlockY + 1; else if (PlayerPitch > 70) then -- looking down BlockY = BlockY - 1; else local PlayerRot = Player:GetRotation() + 180; -- Convert [-180, 180] into [0, 360] for simpler conditions if ((PlayerRot < 45) or (PlayerRot > 315)) then BlockZ = BlockZ - 1; else if (PlayerRot < 135) then BlockX = BlockX + 1; else if (PlayerRot < 225) then BlockZ = BlockZ + 1; else BlockX = BlockX - 1; end; end; end; end; end; Area:Write(Player:GetWorld(), BlockX - MOVER_SIZE_X, BlockY - MOVER_SIZE_Y, BlockZ - MOVER_SIZE_Z); return false; end end
-- DiamondMover.lua -- An example Lua plugin using the cBlockArea object -- When a player rclks with a diamond in their hand, an area around the clicked block is moved in the direction the player is facing -- Global variables MOVER_SIZE_X = 4; MOVER_SIZE_Y = 4; MOVER_SIZE_Z = 4; function Initialize(Plugin) Plugin:SetName("DiamondMover"); Plugin:SetVersion(1); cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_USED_ITEM, OnPlayerUsedItem); LOG("Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()); return true; end function OnPlayerUsedItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ) -- Don't check if the direction is in the air if (BlockFace == -1) then return false; end; if (not Player:HasPermission("diamondmover.move")) then return false; end; -- Rclk with a diamond to push in the direction the player is facing if (Player:GetEquippedItem().m_ItemType == E_ITEM_DIAMOND) then local Area = cBlockArea(); Area:Read(Player:GetWorld(), BlockX - MOVER_SIZE_X, BlockX + MOVER_SIZE_X, BlockY - MOVER_SIZE_Y, BlockY + MOVER_SIZE_Y, BlockZ - MOVER_SIZE_Z, BlockZ + MOVER_SIZE_Z ); local PlayerPitch = Player:GetPitch(); if (PlayerPitch < -70) then -- looking up BlockY = BlockY + 1; else if (PlayerPitch > 70) then -- looking down BlockY = BlockY - 1; else local PlayerRot = Player:GetYaw() + 180; -- Convert [-180, 180] into [0, 360] for simpler conditions if ((PlayerRot < 45) or (PlayerRot > 315)) then BlockZ = BlockZ - 1; else if (PlayerRot < 135) then BlockX = BlockX + 1; else if (PlayerRot < 225) then BlockZ = BlockZ + 1; else BlockX = BlockX - 1; end; end; end; end; end; Area:Write(Player:GetWorld(), BlockX - MOVER_SIZE_X, BlockY - MOVER_SIZE_Y, BlockZ - MOVER_SIZE_Z); return false; end end
Fixed diamond mover plugin
Fixed diamond mover plugin
Lua
apache-2.0
mmdk95/cuberite,jammet/MCServer,Frownigami1/cuberite,Tri125/MCServer,linnemannr/MCServer,Fighter19/cuberite,nicodinh/cuberite,zackp30/cuberite,guijun/MCServer,kevinr/cuberite,electromatter/cuberite,tonibm19/cuberite,nichwall/cuberite,HelenaKitty/EbooMC,HelenaKitty/EbooMC,birkett/cuberite,bendl/cuberite,marvinkopf/cuberite,thetaeo/cuberite,kevinr/cuberite,jammet/MCServer,zackp30/cuberite,Howaner/MCServer,kevinr/cuberite,jammet/MCServer,QUSpilPrgm/cuberite,mc-server/MCServer,tonibm19/cuberite,guijun/MCServer,zackp30/cuberite,Tri125/MCServer,johnsoch/cuberite,Schwertspize/cuberite,nevercast/cuberite,nichwall/cuberite,SamOatesPlugins/cuberite,Fighter19/cuberite,electromatter/cuberite,Altenius/cuberite,ionux/MCServer,nichwall/cuberite,birkett/cuberite,electromatter/cuberite,electromatter/cuberite,Tri125/MCServer,birkett/MCServer,guijun/MCServer,Howaner/MCServer,Tri125/MCServer,Haxi52/cuberite,SamOatesPlugins/cuberite,marvinkopf/cuberite,mmdk95/cuberite,birkett/cuberite,Schwertspize/cuberite,ionux/MCServer,Schwertspize/cuberite,mc-server/MCServer,johnsoch/cuberite,guijun/MCServer,QUSpilPrgm/cuberite,birkett/MCServer,Haxi52/cuberite,nounoursheureux/MCServer,QUSpilPrgm/cuberite,birkett/MCServer,johnsoch/cuberite,QUSpilPrgm/cuberite,birkett/MCServer,nicodinh/cuberite,jammet/MCServer,nounoursheureux/MCServer,Altenius/cuberite,Fighter19/cuberite,QUSpilPrgm/cuberite,Fighter19/cuberite,Fighter19/cuberite,bendl/cuberite,HelenaKitty/EbooMC,mc-server/MCServer,ionux/MCServer,Schwertspize/cuberite,Altenius/cuberite,Schwertspize/cuberite,thetaeo/cuberite,birkett/MCServer,marvinkopf/cuberite,linnemannr/MCServer,kevinr/cuberite,SamOatesPlugins/cuberite,ionux/MCServer,nicodinh/cuberite,thetaeo/cuberite,birkett/cuberite,nichwall/cuberite,mjssw/cuberite,zackp30/cuberite,mc-server/MCServer,nounoursheureux/MCServer,guijun/MCServer,zackp30/cuberite,nichwall/cuberite,nevercast/cuberite,guijun/MCServer,electromatter/cuberite,Haxi52/cuberite,nevercast/cuberite,nevercast/cuberite,Altenius/cuberite,marvinkopf/cuberite,nichwall/cuberite,mjssw/cuberite,tonibm19/cuberite,Fighter19/cuberite,linnemannr/MCServer,nevercast/cuberite,nicodinh/cuberite,nicodinh/cuberite,nounoursheureux/MCServer,linnemannr/MCServer,thetaeo/cuberite,mjssw/cuberite,SamOatesPlugins/cuberite,ionux/MCServer,mc-server/MCServer,tonibm19/cuberite,electromatter/cuberite,thetaeo/cuberite,mjssw/cuberite,mjssw/cuberite,ionux/MCServer,HelenaKitty/EbooMC,QUSpilPrgm/cuberite,Frownigami1/cuberite,jammet/MCServer,bendl/cuberite,kevinr/cuberite,Howaner/MCServer,Howaner/MCServer,SamOatesPlugins/cuberite,mmdk95/cuberite,Frownigami1/cuberite,birkett/cuberite,nounoursheureux/MCServer,mmdk95/cuberite,Tri125/MCServer,Howaner/MCServer,Frownigami1/cuberite,johnsoch/cuberite,marvinkopf/cuberite,tonibm19/cuberite,mc-server/MCServer,bendl/cuberite,Altenius/cuberite,mjssw/cuberite,mmdk95/cuberite,zackp30/cuberite,johnsoch/cuberite,Haxi52/cuberite,Tri125/MCServer,thetaeo/cuberite,mmdk95/cuberite,HelenaKitty/EbooMC,linnemannr/MCServer,marvinkopf/cuberite,tonibm19/cuberite,kevinr/cuberite,nounoursheureux/MCServer,bendl/cuberite,birkett/MCServer,Howaner/MCServer,birkett/cuberite,jammet/MCServer,Haxi52/cuberite,Frownigami1/cuberite,nevercast/cuberite,nicodinh/cuberite,linnemannr/MCServer,Haxi52/cuberite
0512da959c3c3cf21d656a01fd7439efda7af222
KataAnimalQuiz.lua
KataAnimalQuiz.lua
#! /usr/bin/lua -- utils function read_yn() local resp repeat resp = io.read() until (resp == 'y') or (resp == 'n') return resp end -- Animal --------------------- local Animal = {} Animal.__index = Animal function Animal.create(name) local a = {} setmetatable(a, Animal) a.name = name a.is_a = 'Animal' return a end ------------------------------- -- Question ------------------- local Question = {} Question.__index = Question function Question.create(s, y_resp, n_resp) local q = {} setmetatable(q, Question) q.string = s q.y_resp = y_resp q.n_resp = n_resp q.is_a = 'Question' return q end function Question:ask() print(self.string .. '? (y/n) ') if (read_yn() == 'y') then return self.y_resp end return self.n_resp end ------------------------------- -- Node ----------------------- local Node = {} Node.__index = Node function Node.create(value) local n = {} setmetatable(n, Node) n.value = value return n end -- change current value into a question function Node:Make_question(q_string, y_resp, n_resp) self.value = Question.create(q_string, y_resp, n_resp) end ------------------------------- -- Quiz ----------------------- local Quiz = {} Quiz.__index = Quiz function Quiz.create(root) local q = {} local n setmetatable(q, Quiz) if (type(root) == 'string') then n = Node.create(Animal.create(root)) else if (type(root_node) == 'table') then n = Node.create(root) else return nil end end q.root = n q.current_node = n return q end function Quiz.create_animal(name) return Animal.create(name) end function Quiz.create_question(q_string, y_resp, n_resp) return Question.create(q_string, y_resp, n_resp) end function Quiz:ask() return self.current_node.ask() end function Quiz:answer() print("It's a " .. self.current_node.value.name .. ".") print("Am I right? (y/n) ") if (read_yn() == 'n') then local old_value = self.current_node.value -- TODO end print("Play again? (y/n) ") if (read_yn() == 'y') then self.start() end end function Quiz:next() if (self.current_node.value.is_a == 'Animal') then self.answer() else -- if self.current_node.value.is_a == 'Question' self.current_node = self.ask() end end function Quiz:init() self.current_node = self.root end function Quiz:start() self.init() print("Think of an animal…\n") self.next() end ------------------------------- --[[ TODO: - add a .load() and .dump() functions to load/dump "database" (animals) into a file (just for fun) - use a tree structure to store animals, e.g.: Q1 y/ \n A1 Q2 y/ \n A2 A3 with Qx = questions, Ax = animals (y: yes, n: no) ]] return Quiz
#! /usr/bin/lua -- utils function read_yn() local resp repeat resp = io.read() until (resp == 'y') or (resp == 'n') return resp end -- Animal --------------------- local Animal = {} Animal.__index = Animal function Animal.create(name) local a = {} setmetatable(a, Animal) a.name = name a.is_a = 'Animal' return a end ------------------------------- -- Question ------------------- local Question = {} Question.__index = Question function Question.create(s, y_resp, n_resp) local q = {} setmetatable(q, Question) q.string = s q.y_resp = y_resp q.n_resp = n_resp q.is_a = 'Question' return q end function Question:ask() print(self.string .. '? (y/n) ') if (read_yn() == 'y') then return self.y_resp end return self.n_resp end ------------------------------- -- Node ----------------------- local Node = {} Node.__index = Node function Node.create(value) local n = {} setmetatable(n, Node) n.value = value return n end -- change current value into a question function Node:Make_question(q_string, y_resp, n_resp) self.value = Question.create(q_string, y_resp, n_resp) end ------------------------------- -- Quiz ----------------------- local Quiz = {} Quiz.__index = Quiz function Quiz.create(root) local q = {} local n setmetatable(q, Quiz) if (type(root) == 'string') then n = Node.create(Animal.create(root)) else if (type(root_node) == 'table') then n = Node.create(root) else return nil end end q.root = n q.current_node = n return q end function Quiz.create_animal(name) return Animal.create(name) end function Quiz.create_question(q_string, y_resp, n_resp) return Question.create(q_string, y_resp, n_resp) end function Quiz:ask() return Question.ask(self.current_node.value) end function Quiz:answer() print("It's a " .. self.current_node.value.name .. ".") print("Am I right? (y/n) ") if (read_yn() == 'n') then local old_value = self.current_node.value print("What were you thinking of? ") local good_value = io.read() -- TODO end print("Play again? (y/n) ") if (read_yn() == 'y') then Quiz.start(self) end end function Quiz:next() if (self.current_node.value.is_a == 'Animal') then Quiz.answer(self) else -- if self.current_node.value.is_a == 'Question' self.current_node = Quiz.ask(self) end end function Quiz:init() self.current_node = self.root end function Quiz:start() Quiz.init(self) print("Think of an animal…\n") Quiz.next(self) end ------------------------------- --[[ TODO: - add a .load() and .dump() functions to load/dump "database" (animals) into a file (just for fun) - use a tree structure to store animals, e.g.: Q1 y/ \n A1 Q2 y/ \n A2 A3 with Qx = questions, Ax = animals (y: yes, n: no) ]] return Quiz
objects calls fixed
objects calls fixed
Lua
mit
bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas
56875f636c46f2b7abd1b4295ef919156513862b
Log.lua
Log.lua
--[[ -- stores a log of various aspects of training for the purpose of visualization ]] local json = require 'cjson' local paths = require 'paths' local function write_json(file, t) local filename = file .. '.json' local f = io.open(filename, 'w') f:write(json.encode(t)) f:close() end local function load_json(file) local filename = file .. '.json' if not paths.filep(filename) then return nil end local f = io.open(filename, 'r') local contents = f:read('*a') f:close() return json.decode(contents) end local Log = torch.class("Log") function Log:__init(name, hyperparams, saveDir, xLabel, saveFrequency) self.name = name self.xLabel = xLabel or "Iterations" -- name of the x axis, usually related to time / number of batches / epochs self.hyperparams = hyperparams self.saveLoc = paths.concat(saveDir, name) self.saveFrequency = saveFrequency or 0 self.data = {} self.updatesCounter = 0 if not paths.filep(self.saveLoc .. '.json') then write_json(self.saveLoc, {}) end -- update index file local indexLoc = paths.concat(saveDir, 'index') local models = {} for f in paths.files(saveDir, '.json') do table.insert(models, f:sub(1, -6)) end write_json(indexLoc, models) end --[[ -- adds the data point (x, ys), where ys is a dictionary of different statistics to keep track of ]] function Log:update(ys, x) local x = x or self.updatesCounter for name, y in pairs(ys) do local point = {x = x, y = y } -- if dataset doesn't exist, creat eit if not self.data[name] then self.data[name] = {} end -- add the point to it table.insert(self.data[name], point) end self.updatesCounter = self.updatesCounter + 1 if self.saveFrequency > 0 and self.updatesCounter % self.saveFrequency == 0 then self:save() end end --[[ -- Saves all the data as saveDir/name.json, along with the given statistics ]] function Log:save(stats) local stats = stats or {} write_json(self.saveLoc, { name = self.name, xLabel = self.xLabel, hyperparams = self.hyperparams, data = self.data, stats = stats }); end
--[[ -- stores a log of various aspects of training for the purpose of visualization ]] local json = require 'cjson' local paths = require 'paths' local function write_json(file, t) local filename = file .. '.json' local f = io.open(filename, 'w') f:write(json.encode(t)) f:close() end local function load_json(file) local filename = file .. '.json' if not paths.filep(filename) then return nil end local f = io.open(filename, 'r') local contents = f:read('*a') f:close() return json.decode(contents) end local Log = torch.class("Log") function Log:__init(name, hyperparams, saveDir, xLabel, saveFrequency) self.name = name self.xLabel = xLabel or "Iterations" -- name of the x axis, usually related to time / number of batches / epochs self.hyperparams = hyperparams self.saveLoc = paths.concat(saveDir, name) self.saveFrequency = saveFrequency or 0 self.data = {} self.updatesCounter = 0 if not paths.filep(self.saveLoc .. '.json') then write_json(self.saveLoc, {}) end -- update index file local indexLoc = paths.concat(saveDir, 'index') local models = {} for f in paths.files(saveDir, '.json') do if f ~= "index.json" then table.insert(models, f:sub(1, -6)) end end write_json(indexLoc, models) end --[[ -- adds the data point (x, ys), where ys is a dictionary of different statistics to keep track of ]] function Log:update(ys, x) local x = x or self.updatesCounter for name, y in pairs(ys) do local point = {x = x, y = y } -- if dataset doesn't exist, creat eit if not self.data[name] then self.data[name] = {} end -- add the point to it table.insert(self.data[name], point) end self.updatesCounter = self.updatesCounter + 1 if self.saveFrequency > 0 and self.updatesCounter % self.saveFrequency == 0 then self:save() end end --[[ -- Saves all the data as saveDir/name.json, along with the given statistics ]] function Log:save(stats) local stats = stats or {} write_json(self.saveLoc, { name = self.name, xLabel = self.xLabel, hyperparams = self.hyperparams, data = self.data, stats = stats }); end
Fix minor bug in visualization
Fix minor bug in visualization So we don't get redundant files displayed as options
Lua
mit
ivendrov/torch-logger,ivendrov/torch-logger,ivendrov/torch-logger
56c0a3d16457a937d5bda0dd60fe94c07496d2a7
Interface/AddOns/RayUI/libs/cargBags/base/itembutton.lua
Interface/AddOns/RayUI/libs/cargBags/base/itembutton.lua
--[[ cargBags: An inventory framework addon for World of Warcraft Copyright (C) 2010 Constantin "Cargor" Schomburg <xconstruct@gmail.com> cargBags is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. cargBags is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cargBags; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]] local addon, ns = ... local cargBags = ns.cargBags --[[! @class ItemButton This class serves as the basis for all itemSlots in a container ]] local ItemButton = cargBags:NewClass("ItemButton", nil, "Button") --[[! Gets a template name for the bagID @param bagID <number> [optional] @return tpl <string> ]] function ItemButton:GetTemplate(bagID) bagID = bagID or self.bagID return (bagID == -1 and "BankItemButtonGenericTemplate") or (bagID and "ContainerFrameItemButtonTemplate") or "ItemButtonTemplate" end local mt_gen_key = {__index = function(self,k) self[k] = {}; return self[k]; end} --[[! Fetches a new instance of the ItemButton, creating one if necessary @param bagID <number> @param slotID <number> @return button <ItemButton> ]] function ItemButton:New(bagID, slotID) self.recycled = self.recycled or setmetatable({}, mt_gen_key) local tpl = self:GetTemplate(bagID) local button = table.remove(self.recycled[tpl]) or self:Create(tpl) button.bagID = bagID button.slotID = slotID button:SetID(slotID) button:Show() return button end --[[! Creates a new ItemButton @param tpl <string> The template to use [optional] @return button <ItemButton> @callback button:OnCreate(tpl) ]] function ItemButton:Create(tpl) local impl = self.implementation impl.numSlots = (impl.numSlots or 0) + 1 local name = ("%sSlot%d"):format(impl.name, impl.numSlots) local button = setmetatable(CreateFrame("Button", name, nil, tpl), self.__index) local tex = _G[button:GetName().."NewItemTexture"] -- 5.4 fix if tex then tex:SetAlpha(0) end if(button.Scaffold) then button:Scaffold(tpl) end if(button.OnCreate) then button:OnCreate(tpl) end return button end --[[! Frees an ItemButton, storing it for later use ]] function ItemButton:Free() self:Hide() table.insert(self.recycled[self:GetTemplate()], self) end --[[! Fetches the item-info of the button, just a small wrapper for comfort @param item <table> [optional] @return item <table> ]] function ItemButton:GetItemInfo(item) return self.implementation:GetItemInfo(self.bagID, self.slotID, item) end
--[[ cargBags: An inventory framework addon for World of Warcraft Copyright (C) 2010 Constantin "Cargor" Schomburg <xconstruct@gmail.com> cargBags is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. cargBags is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cargBags; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]] local addon, ns = ... local cargBags = ns.cargBags --[[! @class ItemButton This class serves as the basis for all itemSlots in a container ]] local ItemButton = cargBags:NewClass("ItemButton", nil, "Button") --[[! Gets a template name for the bagID @param bagID <number> [optional] @return tpl <string> ]] function ItemButton:GetTemplate(bagID) bagID = bagID or self.bagID return (bagID == -3 and "ReagentBankItemButtonGenericTemplate") or (bagID == -1 and "BankItemButtonGenericTemplate") or (bagID and "ContainerFrameItemButtonTemplate") or "ItemButtonTemplate", (bagID == -3 and ReagentBankFrame) or (bagID == -1 and BankFrame) or (bagID and _G["ContainerFrame"..bagID + 1]) or "ItemButtonTemplate"; end local mt_gen_key = {__index = function(self,k) self[k] = {}; return self[k]; end} --[[! Fetches a new instance of the ItemButton, creating one if necessary @param bagID <number> @param slotID <number> @return button <ItemButton> ]] function ItemButton:New(bagID, slotID) self.recycled = self.recycled or setmetatable({}, mt_gen_key) local tpl, parent = self:GetTemplate(bagID) local button = table.remove(self.recycled[tpl]) or self:Create(tpl, parent) button.bagID = bagID button.slotID = slotID button:SetID(slotID) button:Show() return button end --[[! Creates a new ItemButton @param tpl <string> The template to use [optional] @return button <ItemButton> @callback button:OnCreate(tpl) ]] function ItemButton:Create(tpl, parent) local impl = self.implementation impl.numSlots = (impl.numSlots or 0) + 1 local name = ("%sSlot%d"):format(impl.name, impl.numSlots) local button = setmetatable(CreateFrame("Button", name, parent, tpl), self.__index) if(button.Scaffold) then button:Scaffold(tpl) end if(button.OnCreate) then button:OnCreate(tpl) end local btnNT = _G[button:GetName().."NormalTexture"] local btnNIT = button.NewItemTexture local btnBIT = button.BattlepayItemTexture if btnNT then btnNT:SetTexture("") end if btnNIT then btnNIT:SetTexture("") end if btnBIT then btnBIT:SetTexture("") end return button end --[[! Frees an ItemButton, storing it for later use ]] function ItemButton:Free() self:Hide() table.insert(self.recycled[self:GetTemplate()], self) end --[[! Fetches the item-info of the button, just a small wrapper for comfort @param item <table> [optional] @return item <table> ]] function ItemButton:GetItemInfo(item) return self.implementation:GetItemInfo(self.bagID, self.slotID, item) end
fix bag issue
fix bag issue
Lua
mit
fgprodigal/RayUI
1a7462fd34031adc05571734a43c5be85caf98c0
lua/libs/texttospeech.lua
lua/libs/texttospeech.lua
-- -- Newfies-Dialer License -- http://www.newfies-dialer.org -- -- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this file, -- You can obtain one at http://mozilla.org/MPL/2.0/. -- -- Copyright (C) 2011-2013 Star2Billing S.L. -- -- The Initial Developer of the Original Code is -- Arezqui Belaid <info@star2billing.com> -- package.path = package.path .. ";/usr/share/newfies-lua/?.lua"; package.path = package.path .. ";/usr/share/newfies-lua/libs/?.lua"; -- this file contain function to : -- -- excecute_command -- trim -- tts : produce texttospeec -- acapela -- require "md5" require "lfs" require "acapela" local inspect = require 'inspect' --load local config first require "acapela_config" if ACCOUNT_LOGIN == nil then --if local config failed, import settings require "settings" end --Set a default TTS engine if TTS_ENGINE == nil then TTS_ENGINE = 'flite' end function skip2(_,_, ...) -- return unpack(arg) end function simple_command(command) -- local file = assert(io.popen(command, 'r')) local output = file:read('*all') file:close() return output end -- Check file exists and readable function file_exists(path) local attr = lfs.attributes(path) if (attr ~= nil) then return true else return false end end -- Excecute Command function function excecute_command(cmd, quiet) -- quiet = quiet or 0 -- nul mask local rc,sout,serr -- We need some output to get the return code: cmd = cmd.." ; echo RC=$?" local f= io.popen( cmd ) local str= f:read'*a' f:close() -- By searching at the very end of the string, we avoid clashes -- with whatever the command itself spit out. -- local s1,s2 = skip2( string.find( str, "(.*)RC=(%d+)%s*$" ) ) rc = tonumber(s2) if quiet==0 then sout = s1 else io.write(s1) -- os.execute() would have shown the output end -- print( cmd, rc, sout, serr ) return rc, sout, serr end function trim(s) --trim text if s == nil then return '' end return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end -- -- Return the audio lenght in float -- function audio_lenght(audio_file) if not file_exists(audio_file) then return '0' else len_command = "soxi -D "..audio_file res = simple_command(len_command) if res then return trim(res) else return '0' end end end -- -- Create TTS audio using a speech processing engine -- function tts(text, tts_dir) if TTS_ENGINE == 'cepstral' then --Cepstral voice = "-n Allison-8kHz" frequency = 8000 text = trim(text) if string.len(text) == 0 then return false end hash = md5.sumhexa(voice..text) filename = tts_dir..'cepstral_'..hash output_file = filename..'.wav' txt_file = filename..'.txt' if not file_exists(output_file) then local out = assert(io.open(txt_file, "w")) out:write(text) assert(out:close()) swift_command = "swift -p speech/rate=150,audio/channels=1,audio/sampling-rate="..frequency.." "..voice.." -o "..output_file.." -f "..txt_file excecute_command(swift_command) return output_file end elseif TTS_ENGINE == 'flite' then --Flite voice = "slt" frequency = 8000 text = trim(text) if string.len(text) == 0 then return false end hash = md5.sumhexa(voice..text) filename = tts_dir..'flite_'..hash output_file = filename..'.wav' txt_file = filename..'.txt' if not file_exists(output_file) then local out = assert(io.open(txt_file, "w")) out:write(text) assert(out:close()) -- Convert file flite_command = 'flite -voice '..voice..' -f '..txt_file..' -o '..output_file --print(flite_command) excecute_command(flite_command) return output_file end elseif TTS_ENGINE == 'acapela' then --Acapela local tts_acapela = Acapela(ACCOUNT_LOGIN, APPLICATION_LOGIN, APPLICATION_PASSWORD, SERVICE_URL, QUALITY, tts_dir) tts_acapela:set_cache(true) tts_acapela:prepare(text, ACAPELA_LANG, ACAPELA_GENDER, ACAPELA_INTONATION) output_file = tts_acapela:run() end return output_file end -- -- Test Code -- if false then local ROOT_DIR = '/usr/share/newfies-lua/' local TTS_DIR = ROOT_DIR..'tts/' text = "Let's see if this works for us. Give a try!" output_file = tts(text, TTS_DIR) print("output_file => "..output_file) text = "Second attempt!" output_file = tts(text, TTS_DIR) print("output_file => "..output_file) -- print("\n\nGet Lenght Audio") -- res = audio_lenght('/usr/share/newfies/usermedia/recording/recording-103-35225576.wav') -- print(res) end
-- -- Newfies-Dialer License -- http://www.newfies-dialer.org -- -- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this file, -- You can obtain one at http://mozilla.org/MPL/2.0/. -- -- Copyright (C) 2011-2013 Star2Billing S.L. -- -- The Initial Developer of the Original Code is -- Arezqui Belaid <info@star2billing.com> -- package.path = package.path .. ";/usr/share/newfies-lua/?.lua"; package.path = package.path .. ";/usr/share/newfies-lua/libs/?.lua"; -- this file contain function to : -- -- excecute_command -- trim -- tts : produce texttospeec -- acapela -- require "md5" require "lfs" require "acapela" require "constant" local inspect = require 'inspect' --load local config first if file_exists(ROOT_DIR..'libs/acapela_config.lua') then require "acapela_config" end if ACCOUNT_LOGIN == nil then --if local config failed, import settings require "settings" end --Set a default TTS engine if TTS_ENGINE == nil then TTS_ENGINE = 'flite' end function skip2(_,_, ...) -- return unpack(arg) end function simple_command(command) -- local file = assert(io.popen(command, 'r')) local output = file:read('*all') file:close() return output end -- Check file exists and readable function file_exists(path) local attr = lfs.attributes(path) if (attr ~= nil) then return true else return false end end -- Excecute Command function function excecute_command(cmd, quiet) -- quiet = quiet or 0 -- nul mask local rc,sout,serr -- We need some output to get the return code: cmd = cmd.." ; echo RC=$?" local f= io.popen( cmd ) local str= f:read'*a' f:close() -- By searching at the very end of the string, we avoid clashes -- with whatever the command itself spit out. -- local s1,s2 = skip2( string.find( str, "(.*)RC=(%d+)%s*$" ) ) rc = tonumber(s2) if quiet==0 then sout = s1 else io.write(s1) -- os.execute() would have shown the output end -- print( cmd, rc, sout, serr ) return rc, sout, serr end function trim(s) --trim text if s == nil then return '' end return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end -- -- Return the audio lenght in float -- function audio_lenght(audio_file) if not file_exists(audio_file) then return '0' else len_command = "soxi -D "..audio_file res = simple_command(len_command) if res then return trim(res) else return '0' end end end -- -- Create TTS audio using a speech processing engine -- function tts(text, tts_dir) if TTS_ENGINE == 'cepstral' then --Cepstral voice = "-n Allison-8kHz" frequency = 8000 text = trim(text) if string.len(text) == 0 then return false end hash = md5.sumhexa(voice..text) filename = tts_dir..'cepstral_'..hash output_file = filename..'.wav' txt_file = filename..'.txt' if not file_exists(output_file) then local out = assert(io.open(txt_file, "w")) out:write(text) assert(out:close()) swift_command = "swift -p speech/rate=150,audio/channels=1,audio/sampling-rate="..frequency.." "..voice.." -o "..output_file.." -f "..txt_file excecute_command(swift_command) return output_file end elseif TTS_ENGINE == 'flite' then --Flite voice = "slt" frequency = 8000 text = trim(text) if string.len(text) == 0 then return false end hash = md5.sumhexa(voice..text) filename = tts_dir..'flite_'..hash output_file = filename..'.wav' txt_file = filename..'.txt' if not file_exists(output_file) then local out = assert(io.open(txt_file, "w")) out:write(text) assert(out:close()) -- Convert file flite_command = 'flite -voice '..voice..' -f '..txt_file..' -o '..output_file --print(flite_command) excecute_command(flite_command) return output_file end elseif TTS_ENGINE == 'acapela' then --Acapela local tts_acapela = Acapela(ACCOUNT_LOGIN, APPLICATION_LOGIN, APPLICATION_PASSWORD, SERVICE_URL, QUALITY, tts_dir) tts_acapela:set_cache(true) tts_acapela:prepare(text, ACAPELA_LANG, ACAPELA_GENDER, ACAPELA_INTONATION) output_file = tts_acapela:run() end return output_file end -- -- Test Code -- if false then local ROOT_DIR = '/usr/share/newfies-lua/' local TTS_DIR = ROOT_DIR..'tts/' text = "Let's see if this works for us. Give a try!" output_file = tts(text, TTS_DIR) print("output_file => "..output_file) text = "Second attempt!" output_file = tts(text, TTS_DIR) print("output_file => "..output_file) -- print("\n\nGet Lenght Audio") -- res = audio_lenght('/usr/share/newfies/usermedia/recording/recording-103-35225576.wav') -- print(res) end
LUA : fix local load config for acapela
LUA : fix local load config for acapela
Lua
mpl-2.0
newfies-dialer/newfies-dialer,newfies-dialer/newfies-dialer,saydulk/newfies-dialer,newfies-dialer/newfies-dialer,romonzaman/newfies-dialer,Star2Billing/newfies-dialer,saydulk/newfies-dialer,romonzaman/newfies-dialer,Star2Billing/newfies-dialer,Star2Billing/newfies-dialer,Star2Billing/newfies-dialer,berinhard/newfies-dialer,romonzaman/newfies-dialer,saydulk/newfies-dialer,romonzaman/newfies-dialer,berinhard/newfies-dialer,saydulk/newfies-dialer,newfies-dialer/newfies-dialer,berinhard/newfies-dialer
188fad365a36f52183b0d84d8467b6be9475fa13
config/nvim/lua/init/null-ls.lua
config/nvim/lua/init/null-ls.lua
local null_ls = require('null-ls') null_ls.config({ sources = { null_ls.builtins.diagnostics.eslint, null_ls.builtins.diagnostics.pylint, null_ls.builtins.diagnostics.rubocop, null_ls.builtins.diagnostics.vint, null_ls.builtins.formatting.black, null_ls.builtins.formatting.clang_format, null_ls.builtins.formatting.gofmt, null_ls.builtins.formatting.goimports, null_ls.builtins.formatting.lua_format, null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.shfmt, null_ls.builtins.formatting.terraform_fmt, null_ls.builtins.formatting.zigfmt } }) require('lspconfig')["null-ls"].setup({})
local null_ls = require('null-ls') null_ls.config({ sources = { null_ls.builtins.diagnostics.eslint, null_ls.builtins.diagnostics.pylint, null_ls.builtins.diagnostics.rubocop, null_ls.builtins.diagnostics.vint, null_ls.builtins.formatting.black, null_ls.builtins.formatting.clang_format, null_ls.builtins.formatting.gofmt, null_ls.builtins.formatting.goimports, null_ls.builtins.formatting.lua_format, null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.shfmt.with({ filetypes = {"sh", "zsh"}, args = {"-i", "2"} }), null_ls.builtins.formatting.terraform_fmt, null_ls.builtins.formatting.zigfmt } }) require('lspconfig')["null-ls"].setup({})
Fix shfmt configuration
Fix shfmt configuration
Lua
unlicense
raviqqe/dotfiles
eff818e5d457b351fd850f7644350826d2ffa0e3
forward/rewriting.lua
forward/rewriting.lua
local P = require("core.packet") local L = require("core.link") local GRE = require("lib.protocol.gre") local Datagram = require("lib.protocol.datagram") local Ethernet = require("lib.protocol.ethernet") local IPV4 = require("lib.protocol.ipv4") local bit = require("bit") local ffi = require("ffi") local band = bit.band local rshift = bit.rshift local godefs = require("godefs") local L3_IPV4 = 0x0800 local L3_IPV6 = 0x86DD local L4_TCP = 0x06 local L4_UDP = 0x11 local L4_GRE = 0x2f _G._NAME = "rewriting" -- Snabb requires this for some reason local ipv4_five_tuple = ffi.typeof("char[14]") local ipv4_five_tuple_len = 14 local ipv6_five_tuple = ffi.typeof("char[38]") local ipv6_five_tuple_len = 38 -- Create a five-tuple local function five_tuple(ip_protocol, src, src_port, dst, dst_port) local t, t_len if ip_protocol == L3_IPV4 then t = ipv4_five_tuple() t_len = ipv4_five_tuple_len ffi.copy(t + 6, src, 4) ffi.copy(t + 10, dst, 4) else t = ipv6_five_tuple() t_len = ipv6_five_tuple_len ffi.copy(t + 6, src, 16) ffi.copy(t + 22, dst, 16) end t[0] = band(ip_protocol, 0xff) t[1] = band(rshift(ip_protocol, 8), 0xff) t[2] = band(src_port, 0xff) t[3] = band(rshift(src_port, 8), 0xff) t[4] = band(dst_port, 0xff) t[5] = band(rshift(dst_port, 8), 0xff) return t, t_len end -- Return the backend associated with a five-tuple local function get_backend(five_tuple, five_tuple_len) return godefs.Lookup(five_tuple, five_tuple_len) end local Rewriting = {} -- Arguments: -- ipv4_addr or ipv6_addr (string) -- the IP address of the spike -- src_mac (string) -- the MAC address to send from; defaults to the -- destination MAC of incoming packets -- dst_mac (string) -- the MAC address to send packets to -- ttl (int, default 30) -- the TTL to set on outgoing packets function Rewriting:new(opts) local ipv4_addr, ipv6_addr, err if opts.ipv4_addr and opts.ipv6_addr then error("cannot specify both ipv4 and ipv6") end if not opts.ipv4_addr and not opts.ipv4_addr then error("need to specify either ipv4addr or ipv6addr") end if opts.ipv4_addr then ipv4_addr, err = IPV4:pton(opts.ipv4_addr) if not ipv4_addr then error(err) end end if opts.ipv6_addr then ipv6_addr, err = IPV6:pton(opts.ipv6_addr) if not ipv6_addr then error(err) end error("ipv6 not yet implemented") end if not opts.dst_mac then error("need to specify dst_mac") end return setmetatable( {ipv4_addr = ipv4_addr, ipv6_addr = ipv6_addr, src_mac = opts.src_mac and Ethernet:pton(opts.src_mac), dst_mac = Ethernet:pton(opts.dst_mac), ttl = opts.ttl or 30}, {__index = Rewriting}) end function Rewriting:push() local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") while not L.empty(i) do self:process_packet(i, o) end end function Rewriting:process_packet(i, o) local p = L.receive(i) local datagram = Datagram:new(p, nil, {delayed_commit = true}) local eth_header = datagram:parse_match(Ethernet) if eth_header == nil then P.free(p) return end local eth_dst = eth_header:dst() local l3_type = eth_header:type() if not (l3_type == L3_IPV4 or l3_type == L3_IPV6) then P.free(p) return end -- Maybe consider moving packet parsing after ethernet into go? local ip_class = eth_header:upper_layer() local ip_header = datagram:parse_match(ip_class) if ip_header == nil then P.free(p) return end local ip_src = ip_header:src() local ip_dst = ip_header:dst() local l4_type if l3_type == L3_IPV4 then l4_type = ip_header:protocol() else l4_type = ip_header:next_header() end if not (l4_type == L4_TCP or l4_type == L4_UDP) then P.free(p) return end local prot_class = ip_header:upper_layer() local prot_header = datagram:parse_match(prot_class) if prot_header == nil then P.free(p) return end local src_port = prot_header:src_port() local dst_port = prot_header:dst_port() local t, t_len = five_tuple(l3_type, ip_src, src_port, ip_dst, dst_port) local backend, backend_len = get_backend(t, t_len) if backend_len == 0 then P.free(p) return end if backend_len == 16 then error("ipv6 output not implemented") elseif backend_len ~= 4 then error("backend length must be 4 (for ipv4) or 16 (for ipv6)") end -- unparse L4 and L3 datagram:unparse(2) -- decapsulate from ethernet datagram:pop(1) local _, payload_len = datagram:payload() local gre_header = GRE:new({protocol = l3_type}) datagram:push(gre_header) local outer_ip_header = IPV4:new({src = self.ipv4_addr, dst = backend, protocol = L4_GRE, ttl = self.ttl}) outer_ip_header:total_length( payload_len + gre_header:sizeof() + outer_ip_header:sizeof()) datagram:push(outer_ip_header) local outer_eth_header = Ethernet:new({src = self.src_mac or eth_dst, dst = self.dst_mac, type = L3_IPV4}) datagram:push(outer_eth_header) datagram:commit() link.transmit(o, datagram:packet()) end return Rewriting
local P = require("core.packet") local L = require("core.link") local GRE = require("lib.protocol.gre") local Datagram = require("lib.protocol.datagram") local Ethernet = require("lib.protocol.ethernet") local IPV4 = require("lib.protocol.ipv4") local bit = require("bit") local ffi = require("ffi") local band = bit.band local rshift = bit.rshift local godefs = require("godefs") local L3_IPV4 = 0x0800 local L3_IPV6 = 0x86DD local L4_TCP = 0x06 local L4_UDP = 0x11 local L4_GRE = 0x2f _G._NAME = "rewriting" -- Snabb requires this for some reason local ipv4_five_tuple = ffi.typeof("char[14]") local ipv4_five_tuple_len = 14 local ipv6_five_tuple = ffi.typeof("char[38]") local ipv6_five_tuple_len = 38 -- Create a five-tuple local function five_tuple(ip_protocol, src, src_port, dst, dst_port) local t, t_len if ip_protocol == L3_IPV4 then t = ipv4_five_tuple() t_len = ipv4_five_tuple_len ffi.copy(t + 6, src, 4) ffi.copy(t + 10, dst, 4) else t = ipv6_five_tuple() t_len = ipv6_five_tuple_len ffi.copy(t + 6, src, 16) ffi.copy(t + 22, dst, 16) end t[0] = band(ip_protocol, 0xff) t[1] = band(rshift(ip_protocol, 8), 0xff) t[2] = band(src_port, 0xff) t[3] = band(rshift(src_port, 8), 0xff) t[4] = band(dst_port, 0xff) t[5] = band(rshift(dst_port, 8), 0xff) return t, t_len end -- Return the backend associated with a five-tuple local function get_backend(five_tuple, five_tuple_len) return godefs.Lookup(five_tuple, five_tuple_len) end local Rewriting = {} -- Arguments: -- ipv4_addr or ipv6_addr (string) -- the IP address of the spike -- src_mac (string) -- the MAC address to send from; defaults to the -- destination MAC of incoming packets -- dst_mac (string) -- the MAC address to send packets to -- ttl (int, default 30) -- the TTL to set on outgoing packets function Rewriting:new(opts) local ipv4_addr, ipv6_addr, err if opts.ipv4_addr and opts.ipv6_addr then error("cannot specify both ipv4 and ipv6") end if not opts.ipv4_addr and not opts.ipv4_addr then error("need to specify either ipv4addr or ipv6addr") end if opts.ipv4_addr then ipv4_addr, err = IPV4:pton(opts.ipv4_addr) if not ipv4_addr then error(err) end end if opts.ipv6_addr then ipv6_addr, err = IPV6:pton(opts.ipv6_addr) if not ipv6_addr then error(err) end error("ipv6 not yet implemented") end if not opts.dst_mac then error("need to specify dst_mac") end return setmetatable( {ipv4_addr = ipv4_addr, ipv6_addr = ipv6_addr, src_mac = opts.src_mac and Ethernet:pton(opts.src_mac), dst_mac = Ethernet:pton(opts.dst_mac), ttl = opts.ttl or 30}, {__index = Rewriting}) end function Rewriting:push() local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") while not L.empty(i) do self:process_packet(i, o) end end function Rewriting:process_packet(i, o) local p = L.receive(i) local datagram = Datagram:new(p, nil, {delayed_commit = true}) local eth_header = datagram:parse_match(Ethernet) if eth_header == nil then P.free(p) return end local eth_dst = eth_header:dst() local l3_type = eth_header:type() if not (l3_type == L3_IPV4 or l3_type == L3_IPV6) then P.free(p) return end -- Maybe consider moving packet parsing after ethernet into go? local ip_class = eth_header:upper_layer() local ip_header = datagram:parse_match(ip_class) if ip_header == nil then P.free(p) return end local ip_src = ip_header:src() local ip_dst = ip_header:dst() local l4_type if l3_type == L3_IPV4 then l4_type = ip_header:protocol() else l4_type = ip_header:next_header() end if not (l4_type == L4_TCP or l4_type == L4_UDP) then P.free(p) return end local prot_class = ip_header:upper_layer() local prot_header = datagram:parse_match(prot_class) if prot_header == nil then P.free(p) return end local src_port = prot_header:src_port() local dst_port = prot_header:dst_port() local t, t_len = five_tuple(l3_type, ip_src, src_port, ip_dst, dst_port) local backend, backend_len = get_backend(t, t_len) if backend_len == 0 then P.free(p) return end if backend_len == 16 then error("ipv6 output not implemented") elseif backend_len ~= 4 then error("backend length must be 4 (for ipv4) or 16 (for ipv6)") end -- unparse L4 and L3 datagram:unparse(2) -- decapsulate from ethernet datagram:pop(1) local _, payload_len = datagram:payload() local gre_header = GRE:new({protocol = l3_type}) datagram:push(gre_header) local outer_ip_header = IPV4:new({src = self.ipv4_addr, dst = backend, protocol = L4_GRE, ttl = self.ttl}) outer_ip_header:total_length( payload_len + gre_header:sizeof() + outer_ip_header:sizeof()) -- need to recompute checksum after changing total_length outer_ip_header:checksum() datagram:push(outer_ip_header) local outer_eth_header = Ethernet:new({src = self.src_mac or eth_dst, dst = self.dst_mac, type = L3_IPV4}) datagram:push(outer_eth_header) datagram:commit() link.transmit(o, datagram:packet()) end return Rewriting
fix recompute checksum bug without refactoring
fix recompute checksum bug without refactoring
Lua
mit
krawthekrow/spike,krawthekrow/spike
bcba4d20d1f3fbd1e78b386384b04f32724111c8
lua_scripts/pathmaps/tools/00_default.lua
lua_scripts/pathmaps/tools/00_default.lua
-- Copyright (C) 2008 Lauri Leukkunen <lle@rahina.org> -- Copyright (C) 2008 Nokia Corporation. -- Licensed under MIT license. -- "tools" mapping mode: Almost everything maps to tools_root. -- Rule file interface version, mandatory. -- rule_file_interface_version = "19" ---------------------------------- tools = tools_root if (not tools) then tools = "/" end -- If the permission token exists and contains "root", tools_root directories -- will be available in R/W mode. Otherwise it will be "mounted" R/O. local tools_root_is_readonly if sb.get_session_perm() == "root" then tools_root_is_readonly = false else tools_root_is_readonly = true end -- disable the gcc toolchain tricks. gcc & friends will be available, if -- those have been installed to tools_root enable_cross_gcc_toolchain = false -- This mode can also be used to redirect /var/lib/dpkg/status to another -- location (our dpkg-checkbuilddeps wrapper needs that) local var_lib_dpkg_status_location = os.getenv("SBOX_TOOLS_MODE_VAR_LIB_DPKG_STATUS_LOCATION") if var_lib_dpkg_status_location == nil or var_lib_dpkg_status_location == "" then -- Use the default location var_lib_dpkg_status_location = tools_root .. "/var/lib/dpkg/status" end mapall_chain = { next_chain = nil, binary = nil, rules = { {path = sbox_cputransparency_method, use_orig_path = true, readonly = true}, {path = "/usr/bin/sb2-show", use_orig_path = true, readonly = true}, -- tools_root should not be mapped twice. {prefix = tools, use_orig_path = true, readonly = true}, -- ldconfig is static binary, and needs to be wrapped {prefix = "/sb2/wrappers", replace_by = session_dir .. "/wrappers." .. active_mapmode, readonly = true}, -- {prefix = "/var/run", map_to = session_dir}, -- {prefix = session_dir, use_orig_path = true}, {prefix = "/tmp", map_to = session_dir}, -- {prefix = "/dev", use_orig_path = true}, {dir = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, {prefix = sbox_user_home_dir .. "/.scratchbox2", use_orig_path = true}, {prefix = sbox_dir .. "/share/scratchbox2", use_orig_path = true}, {prefix = "/etc/resolv.conf", use_orig_path = true, readonly = true}, {path = "/etc/passwd", use_orig_path = true, readonly = true}, -- ----------------------------------------------- -- home directories = not mapped, R/W access {prefix = "/home", use_orig_path = true}, -- ----------------------------------------------- {path = "/var/lib/dpkg/status", replace_by = var_lib_dpkg_status_location, readonly = tools_root_is_readonly}, -- The default is to map everything to tools_root {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools_root, readonly = tools_root_is_readonly} } } export_chains = { mapall_chain } -- Exec policy rules. default_exec_policy = { name = "Default" } -- For binaries from tools_root: -- we have "tools' native" and "host's native" binaries, that would look -- identical (and valid!) to the kernel. But they may need to use different -- loaders and dynamic libraries! The solution is that we use the location -- (as determined by the mapping engine) to decide the execution policy. tools_mode_tools_ld_so = nil -- default = not needed tools_mode_tools_ld_library_path = nil -- default = not needed -- used if libsb2.so is not available in tools_root: tools_mode_tools_ld_library_path_suffix = nil if (conf_tools_sb2_installed) then if (conf_tools_ld_so ~= nil) then -- use dynamic libraries from tools, -- when executing native binaries! tools_mode_tools_ld_so = conf_tools_ld_so tools_mode_tools_ld_library_path = conf_tools_ld_so_library_path -- FIXME: This exec policy should process (map components of) -- the current value of LD_LIBRARY_PATH, and add the results -- to tools_mode_tools_ld_library_path just before exec. -- This has not been done yet. end else tools_mode_tools_ld_library_path_suffix = conf_tools_ld_so_library_path end local exec_policy_tools = { name = "Tools_root", native_app_ld_so = tools_mode_tools_ld_so, native_app_ld_so_supports_argv0 = conf_tools_ld_so_supports_argv0, native_app_ld_library_path = tools_mode_tools_ld_library_path, native_app_ld_library_path_suffix = tools_mode_tools_ld_library_path_suffix, native_app_locale_path = conf_tools_locale_path, native_app_message_catalog_prefix = conf_tools_message_catalog_prefix, } -- Note that the real path (mapped path) is used when looking up rules! all_exec_policies_chain = { next_chain = nil, binary = nil, rules = { -- Tools binaries: {prefix = tools_root, exec_policy = exec_policy_tools}, -- DEFAULT RULE (must exist): {prefix = "/", exec_policy = default_exec_policy} } } exec_policy_chains = { all_exec_policies_chain } -- This table lists all exec policies - this is used when the current -- process wants to locate the currently active policy all_exec_policies = { exec_policy_tools, default_exec_policy, }
-- Copyright (C) 2008 Lauri Leukkunen <lle@rahina.org> -- Copyright (C) 2008 Nokia Corporation. -- Licensed under MIT license. -- "tools" mapping mode: Almost everything maps to tools_root. -- Rule file interface version, mandatory. -- rule_file_interface_version = "19" ---------------------------------- tools = tools_root if (not tools) then tools = "/" end -- Don't map the working directory where sb2 was started, unless -- that happens to be the root directory. if sbox_workdir == "/" then -- FIXME. There should be a way to skip a rule... unmapped_workdir = "/XXXXXX" else unmapped_workdir = sbox_workdir end -- If the permission token exists and contains "root", tools_root directories -- will be available in R/W mode. Otherwise it will be "mounted" R/O. local tools_root_is_readonly if sb.get_session_perm() == "root" then tools_root_is_readonly = false else tools_root_is_readonly = true end -- disable the gcc toolchain tricks. gcc & friends will be available, if -- those have been installed to tools_root enable_cross_gcc_toolchain = false -- This mode can also be used to redirect /var/lib/dpkg/status to another -- location (our dpkg-checkbuilddeps wrapper needs that) local var_lib_dpkg_status_location = os.getenv("SBOX_TOOLS_MODE_VAR_LIB_DPKG_STATUS_LOCATION") if var_lib_dpkg_status_location == nil or var_lib_dpkg_status_location == "" then -- Use the default location var_lib_dpkg_status_location = tools_root .. "/var/lib/dpkg/status" end mapall_chain = { next_chain = nil, binary = nil, rules = { {path = sbox_cputransparency_method, use_orig_path = true, readonly = true}, {path = "/usr/bin/sb2-show", use_orig_path = true, readonly = true}, -- tools_root should not be mapped twice. {prefix = tools, use_orig_path = true, readonly = true}, -- ldconfig is static binary, and needs to be wrapped {prefix = "/sb2/wrappers", replace_by = session_dir .. "/wrappers." .. active_mapmode, readonly = true}, -- {prefix = "/var/run", map_to = session_dir}, -- {prefix = session_dir, use_orig_path = true}, {prefix = "/tmp", map_to = session_dir}, -- {prefix = "/dev", use_orig_path = true}, {dir = "/proc", custom_map_funct = sb2_procfs_mapper, virtual_path = true}, {prefix = "/sys", use_orig_path = true}, {prefix = sbox_user_home_dir .. "/.scratchbox2", use_orig_path = true}, {prefix = sbox_dir .. "/share/scratchbox2", use_orig_path = true}, {prefix = "/etc/resolv.conf", use_orig_path = true, readonly = true}, {path = "/etc/passwd", use_orig_path = true, readonly = true}, -- ----------------------------------------------- -- home directories = not mapped, R/W access {prefix = "/home", use_orig_path = true}, -- ----------------------------------------------- {path = "/var/lib/dpkg/status", replace_by = var_lib_dpkg_status_location, readonly = tools_root_is_readonly}, -- The default is to map everything to tools_root, -- except that we don't map the directory tree where -- sb2 was started. {prefix = unmapped_workdir, use_orig_path = true}, {path = "/", use_orig_path = true}, {prefix = "/", map_to = tools_root, readonly = tools_root_is_readonly} } } export_chains = { mapall_chain } -- Exec policy rules. default_exec_policy = { name = "Default" } -- For binaries from tools_root: -- we have "tools' native" and "host's native" binaries, that would look -- identical (and valid!) to the kernel. But they may need to use different -- loaders and dynamic libraries! The solution is that we use the location -- (as determined by the mapping engine) to decide the execution policy. tools_mode_tools_ld_so = nil -- default = not needed tools_mode_tools_ld_library_path = nil -- default = not needed -- used if libsb2.so is not available in tools_root: tools_mode_tools_ld_library_path_suffix = nil if (conf_tools_sb2_installed) then if (conf_tools_ld_so ~= nil) then -- use dynamic libraries from tools, -- when executing native binaries! tools_mode_tools_ld_so = conf_tools_ld_so tools_mode_tools_ld_library_path = conf_tools_ld_so_library_path -- FIXME: This exec policy should process (map components of) -- the current value of LD_LIBRARY_PATH, and add the results -- to tools_mode_tools_ld_library_path just before exec. -- This has not been done yet. end else tools_mode_tools_ld_library_path_suffix = conf_tools_ld_so_library_path end local exec_policy_tools = { name = "Tools_root", native_app_ld_so = tools_mode_tools_ld_so, native_app_ld_so_supports_argv0 = conf_tools_ld_so_supports_argv0, native_app_ld_library_path = tools_mode_tools_ld_library_path, native_app_ld_library_path_suffix = tools_mode_tools_ld_library_path_suffix, native_app_locale_path = conf_tools_locale_path, native_app_message_catalog_prefix = conf_tools_message_catalog_prefix, } -- Note that the real path (mapped path) is used when looking up rules! all_exec_policies_chain = { next_chain = nil, binary = nil, rules = { -- Tools binaries: {prefix = tools_root, exec_policy = exec_policy_tools}, -- DEFAULT RULE (must exist): {prefix = "/", exec_policy = default_exec_policy} } } exec_policy_chains = { all_exec_policies_chain } -- This table lists all exec policies - this is used when the current -- process wants to locate the currently active policy all_exec_policies = { exec_policy_tools, default_exec_policy, }
"tools" mode bugfix: Don't map the directory where sb2 was started
"tools" mode bugfix: Don't map the directory where sb2 was started - this rule already exists in the "emulate" mode
Lua
lgpl-2.1
ldbox/ldbox,BinChengfei/scratchbox2,madscientist42/scratchbox2,lbt/scratchbox2,loganchien/scratchbox2,neeraj9/sbox2,OlegGirko/ldbox,freedesktop-unofficial-mirror/sbox2,lbt/scratchbox2,neeraj9/sbox2,lbt/scratchbox2,OlegGirko/ldbox,neeraj9/sbox2,loganchien/scratchbox2,BinChengfei/scratchbox2,madscientist42/scratchbox2,ldbox/ldbox,freedesktop-unofficial-mirror/sbox2,ldbox/ldbox,BinChengfei/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,h113331pp/scratchbox2,neeraj9/sbox2,ldbox/ldbox,h113331pp/scratchbox2,ldbox/ldbox,lbt/scratchbox2,loganchien/scratchbox2,lbt/scratchbox2,BinChengfei/scratchbox2,OlegGirko/ldbox,neeraj9/sbox2,OlegGirko/ldbox,OlegGirko/ldbox,madscientist42/scratchbox2,loganchien/scratchbox2,BinChengfei/scratchbox2,h113331pp/scratchbox2,h113331pp/scratchbox2,loganchien/scratchbox2,freedesktop-unofficial-mirror/sbox2,OlegGirko/ldbox,neeraj9/sbox2,freedesktop-unofficial-mirror/sbox2,h113331pp/scratchbox2,freedesktop-unofficial-mirror/sbox2,BinChengfei/scratchbox2,madscientist42/scratchbox2,loganchien/scratchbox2,madscientist42/scratchbox2
8207e4bdf20e56f91890f74c07b7ebdafe3b218e
frontend/ui/elements/screen_dpi_menu_table.lua
frontend/ui/elements/screen_dpi_menu_table.lua
local _ = require("gettext") local Screen = require("device").screen local T = require("ffi/util").template local function dpi() return G_reader_settings:readSetting("screen_dpi") 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 = T(_("DPI set to %1. This will take effect after restarting."), _dpi), }) G_reader_settings:saveSetting("screen_dpi", _dpi) Screen:setDPI(_dpi) end local dpi_auto = Screen:getDPI() 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 = T(_("Auto DPI (%1)"), dpi_auto), 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 = function() return dpi() == nil end, callback = function() setDPI() end }, { text = T(_("Small (%1)"), dpi_small), checked_func = function() 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() 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() 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() 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() 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() 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() 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 Screen = require("device").screen local T = require("ffi/util").template local function dpi() return G_reader_settings:readSetting("screen_dpi") 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) Screen:setDPI(_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 = function() return dpi() == nil end, callback = function() setDPI() end }, { text = T(_("Small (%1)"), dpi_small), checked_func = function() 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() 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() 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() 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() 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() 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() 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"), }, }, } }
[fix, lang] More accurate auto-DPI text (#4537)
[fix, lang] More accurate auto-DPI text (#4537) Simply don't mention any values when the device DPI isn't known. A more robust auto-DPI info function could be added to Screen but I'm not sure if it's worth the trouble. Fixes https://github.com/koreader/koreader/pull/4389#issuecomment-454552446
Lua
agpl-3.0
Hzj-jie/koreader,pazos/koreader,NiLuJe/koreader,houqp/koreader,NiLuJe/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader,poire-z/koreader,mwoz123/koreader,koreader/koreader,mihailim/koreader
84b762d7fe5deb10f49eec9ea5a911ce053fb573
spec/02-integration/09-hybrid_mode/02-start_stop_spec.lua
spec/02-integration/09-hybrid_mode/02-start_stop_spec.lua
local helpers = require "spec.helpers" local confs = helpers.get_clustering_protocols() for cluster_protocol, conf in pairs(confs) do describe("invalid config are rejected, protocol " .. cluster_protocol, function() describe("role is control_plane", function() it("can not disable admin_listen", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", admin_listen = "off", }) assert.False(ok) assert.matches("Error: admin_listen must be specified when role = \"control_plane\"", err, nil, true) end) it("can not disable cluster_listen", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_listen = "off", }) assert.False(ok) assert.matches("Error: cluster_listen must be specified when role = \"control_plane\"", err, nil, true) end) it("can not use DB-less mode", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", database = "off", }) assert.False(ok) assert.matches("Error: in-memory storage can not be used when role = \"control_plane\"", err, nil, true) end) it("must define cluster_ca_cert", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_mtls = "pki", }) assert.False(ok) assert.matches("Error: cluster_ca_cert must be specified when cluster_mtls = \"pki\"", err, nil, true) end) end) describe("role is proxy", function() it("can not disable proxy_listen", function() local ok, err = helpers.start_kong({ role = "data_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", proxy_listen = "off", }) assert.False(ok) assert.matches("Error: proxy_listen must be specified when role = \"data_plane\"", err, nil, true) end) it("can not use DB mode", function() local ok, err = helpers.start_kong({ role = "data_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", }) assert.False(ok) assert.matches("Error: only in-memory storage can be used when role = \"data_plane\"\n" .. "Hint: set database = off in your kong.conf", err, nil, true) end) end) for _, param in ipairs({ { "control_plane", "postgres" }, { "data_plane", "off" }, }) do describe("role is " .. param[1], function() it("errors if cluster certificate is not found", function() local ok, err = helpers.start_kong({ role = param[1], legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, database = param[2], prefix = "servroot2", }) assert.False(ok) assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true) end) it("errors if cluster certificate key is not found", function() local ok, err = helpers.start_kong({ role = param[1], legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, database = param[2], prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", }) assert.False(ok) assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true) end) end) end end) end -- note that lagacy modes still error when CP exits describe("when CP exits before DP", function() local need_exit = true setup(function() assert(helpers.start_kong({ role = "control_plane", prefix = "servroot1", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_listen = "127.0.0.1:9005", })) assert(helpers.start_kong({ role = "data_plane", prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_control_plane = "127.0.0.1:9005", proxy_listen = "0.0.0.0:9002", database = "off", })) end) teardown(function() if need_exit then helpers.stop_kong("servroot1") end helpers.stop_kong("servroot2") end) it("DP should not emit error message", function () helpers.clean_logfile("servroot2/logs/error.log") assert(helpers.stop_kong("servroot1")) need_exit = false assert.logfile("servroot2/logs/error.log").has.no.line("[error]", true) end) end)
local helpers = require "spec.helpers" local confs = helpers.get_clustering_protocols() for cluster_protocol, conf in pairs(confs) do describe("invalid config are rejected, protocol " .. cluster_protocol, function() describe("role is control_plane", function() it("can not disable admin_listen", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", admin_listen = "off", }) assert.False(ok) assert.matches("Error: admin_listen must be specified when role = \"control_plane\"", err, nil, true) end) it("can not disable cluster_listen", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_listen = "off", }) assert.False(ok) assert.matches("Error: cluster_listen must be specified when role = \"control_plane\"", err, nil, true) end) it("can not use DB-less mode", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", database = "off", }) assert.False(ok) assert.matches("Error: in-memory storage can not be used when role = \"control_plane\"", err, nil, true) end) it("must define cluster_ca_cert", function() local ok, err = helpers.start_kong({ role = "control_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_mtls = "pki", }) assert.False(ok) assert.matches("Error: cluster_ca_cert must be specified when cluster_mtls = \"pki\"", err, nil, true) end) end) describe("role is proxy", function() it("can not disable proxy_listen", function() local ok, err = helpers.start_kong({ role = "data_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", proxy_listen = "off", }) assert.False(ok) assert.matches("Error: proxy_listen must be specified when role = \"data_plane\"", err, nil, true) end) it("can not use DB mode", function() local ok, err = helpers.start_kong({ role = "data_plane", legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", }) assert.False(ok) assert.matches("Error: only in-memory storage can be used when role = \"data_plane\"\n" .. "Hint: set database = off in your kong.conf", err, nil, true) end) end) for _, param in ipairs({ { "control_plane", "postgres" }, { "data_plane", "off" }, }) do describe("role is " .. param[1], function() it("errors if cluster certificate is not found", function() local ok, err = helpers.start_kong({ role = param[1], legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, database = param[2], prefix = "servroot2", }) assert.False(ok) assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true) end) it("errors if cluster certificate key is not found", function() local ok, err = helpers.start_kong({ role = param[1], legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"), nginx_conf = conf, database = param[2], prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", }) assert.False(ok) assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true) end) end) end end) end -- note that lagacy modes still error when CP exits describe("when CP exits before DP", function() local need_exit = true setup(function() assert(helpers.start_kong({ role = "control_plane", prefix = "servroot1", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_listen = "127.0.0.1:9005", })) assert(helpers.start_kong({ role = "data_plane", prefix = "servroot2", cluster_cert = "spec/fixtures/kong_clustering.crt", cluster_cert_key = "spec/fixtures/kong_clustering.key", cluster_control_plane = "127.0.0.1:9005", proxy_listen = "0.0.0.0:9002", database = "off", })) end) teardown(function() if need_exit then helpers.stop_kong("servroot1") end helpers.stop_kong("servroot2") end) it("DP should not emit error message", function () helpers.clean_logfile("servroot2/logs/error.log") assert(helpers.stop_kong("servroot1")) need_exit = false -- it's possible for DP to reconnect immediately, and emit error message for it, so we just check for wRPC errors assert.logfile("servroot2/logs/error.log").has.no.line("error while receiving frame from peer", true) end) end)
fix test
fix test
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
24ca84a88383880ff9922e1c40ebcbae88d69357
Repeater.lua
Repeater.lua
------------------------------------------------------------------------ --[[ Repeater ]]-- -- Encapsulates an AbstractRecurrent instance (rnn) which is repeatedly -- presented with the same input for nStep time steps. -- The output is a table of nStep outputs of the rnn. ------------------------------------------------------------------------ local Repeater, parent = torch.class("nn.Repeater", "nn.Container") function Repeater:__init(nStep, rnn) parent.__init(self) self.nStep = nStep self.rnn = rnn assert(rnn.backwardThroughTime, "expecting AbstractRecurrent instance for arg 2") self.modules[1] = rnn self.output = {} end function Repeater:updateOutput(input) self.rnn:forget() for step=1,self.nStep do self.output[step] = self.rnn:updateOutput(input) end return self.output end function Repeater:updateGradInput(input, gradOutput) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:updateGradInput(input, gradOutput[step]) end -- back-propagate through time (BPTT) self.rnn.updateGradInputThroughTime() return self.rnn.gradInputs end function Repeater:accGradParameters(input, gradOutput, scale) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:accGradParameters(input, gradOutput[step], scale) end -- back-propagate through time (BPTT) self.rnn.accGradParametersThroughTime() end function Repeater:accUpdateGradParameters(input, gradOutput, lr) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:accGradParameters(input, gradOutput[step], 1) end -- back-propagate through time (BPTT) self.rnn.accUpdateGradParametersThroughTime(lr) end
------------------------------------------------------------------------ --[[ Repeater ]]-- -- Encapsulates an AbstractRecurrent instance (rnn) which is repeatedly -- presented with the same input for nStep time steps. -- The output is a table of nStep outputs of the rnn. ------------------------------------------------------------------------ local Repeater, parent = torch.class("nn.Repeater", "nn.Container") function Repeater:__init(nStep, rnn) parent.__init(self) self.nStep = nStep self.rnn = rnn assert(rnn.backwardThroughTime, "expecting AbstractRecurrent instance for arg 2") self.modules[1] = rnn self.output = {} end function Repeater:updateOutput(input) self.rnn:forget() for step=1,self.nStep do self.output[step] = self.rnn:updateOutput(input) end return self.output end function Repeater:updateGradInput(input, gradOutput) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:updateGradInput(input, gradOutput[step]) end -- back-propagate through time (BPTT) self.rnn:updateGradInputThroughTime() self.gradInput = self.rnn.gradInputs return self.gradInput end function Repeater:accGradParameters(input, gradOutput, scale) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:accGradParameters(input, gradOutput[step], scale) end -- back-propagate through time (BPTT) self.rnn:accGradParametersThroughTime() end function Repeater:accUpdateGradParameters(input, gradOutput, lr) assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps") assert(torch.type(gradOutput) == 'table', "expecting gradOutput table") assert(#gradOutput == self.nStep, "gradOutput should have nStep elements") for step=1,self.nStep do self.rnn.step = step + 1 self.rnn:accGradParameters(input, gradOutput[step], 1) end -- back-propagate through time (BPTT) self.rnn:accUpdateGradParametersThroughTime(lr) end
fix Repeater bugs
fix Repeater bugs
Lua
mit
clementfarabet/lua---nnx
3233a9e822c16d210f6e3af74504ee9b9c8b42eb
spec/plugins/keyauth/api_spec.lua
spec/plugins/keyauth/api_spec.lua
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" describe("Key Auth Credentials API", function() local BASE_URL, credential, consumer setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("/consumers/:consumer/keyauth/", function() setup(function() local fixtures = spec_helper.insert_fixtures { consumer = {{ username = "bob" }} } consumer = fixtures.consumer[1] BASE_URL = spec_helper.API_URL.."/consumers/bob/keyauth/" end) describe("POST", function() it("[SUCCESS] should create a keyauth credential", function() local response, status = http_client.post(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.post(BASE_URL, {}) assert.equal(400, status) assert.equal('{"key":"key is required"}\n', response) end) end) describe("PUT", function() setup(function() spec_helper.get_env().dao_factory.keyauth_credentials:delete({id = credential.id}) end) it("[SUCCESS] should create and update", function() local response, status = http_client.put(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.put(BASE_URL, {}) assert.equal(400, status) assert.equal('{"key":"key is required"}\n', response) end) end) describe("GET", function() it("should retrieve all", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.equal(1, #(body.data)) end) end) end) describe("/consumers/:consumer/keyauth/:id", function() describe("GET", function() it("should retrieve by id", function() local _, status = http_client.get(BASE_URL..credential.id) assert.equal(200, status) end) end) describe("PATCH", function() it("[SUCCESS] should update a credential", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "4321" }) assert.equal(200, status) credential = json.decode(response) assert.equal("4321", credential.key) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "" }) assert.equal(400, status) assert.equal('{"key":"key is not a string"}\n', response) end) end) describe("DELETE", function() it("[FAILURE] should return proper errors", function() local _, status = http_client.delete(BASE_URL.."blah") assert.equal(400, status) _, status = http_client.delete(BASE_URL.."00000000-0000-0000-0000-000000000000") assert.equal(404, status) end) it("[SUCCESS] should delete a credential", function() local _, status = http_client.delete(BASE_URL..credential.id) assert.equal(204, status) end) end) end) end)
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" describe("Key Auth Credentials API", function() local BASE_URL, credential, consumer setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("/consumers/:consumer/keyauth/", function() setup(function() local fixtures = spec_helper.insert_fixtures { consumer = {{ username = "bob" }} } consumer = fixtures.consumer[1] BASE_URL = spec_helper.API_URL.."/consumers/bob/keyauth/" end) describe("POST", function() it("[SUCCESS] should create a keyauth credential", function() local response, status = http_client.post(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[SUCCESS] should create a keyauth credential auto-generating the key", function() local response, status = http_client.post(BASE_URL, {}) assert.equal(201, status) end) end) describe("PUT", function() setup(function() spec_helper.get_env().dao_factory.keyauth_credentials:delete({id = credential.id}) end) it("[SUCCESS] should create and update", function() local response, status = http_client.put(BASE_URL, { key = "1234" }) assert.equal(201, status) credential = json.decode(response) assert.equal(consumer.id, credential.consumer_id) end) it("[SUCCESS] should create a keyauth credential auto-generating the key", function() local response, status = http_client.put(BASE_URL, {}) assert.equal(201, status) end) end) describe("GET", function() it("should retrieve all", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.equal(3, #(body.data)) end) end) end) describe("/consumers/:consumer/keyauth/:id", function() describe("GET", function() it("should retrieve by id", function() local _, status = http_client.get(BASE_URL..credential.id) assert.equal(200, status) end) end) describe("PATCH", function() it("[SUCCESS] should update a credential", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "4321" }) assert.equal(200, status) credential = json.decode(response) assert.equal("4321", credential.key) end) it("[FAILURE] should return proper errors", function() local response, status = http_client.patch(BASE_URL..credential.id, { key = "" }) assert.equal(400, status) assert.equal('{"key":"key is not a string"}\n', response) end) end) describe("DELETE", function() it("[FAILURE] should return proper errors", function() local _, status = http_client.delete(BASE_URL.."blah") assert.equal(400, status) _, status = http_client.delete(BASE_URL.."00000000-0000-0000-0000-000000000000") assert.equal(404, status) end) it("[SUCCESS] should delete a credential", function() local _, status = http_client.delete(BASE_URL..credential.id) assert.equal(204, status) end) end) end) end)
Fixing test
Fixing test
Lua
mit
vmercierfr/kong,chourobin/kong,bbalu/kong,ChristopherBiscardi/kong,peterayeni/kong,AnsonSmith/kong,Skyscanner/kong,sbuettner/kong,wakermahmud/kong,skynet/kong,paritoshmmmec/kong
5e146d6555237e24ae02e7a33b0be31d8c3e410a
vrp/modules/map.lua
vrp/modules/map.lua
local client_areas = {} -- free client areas when leaving AddEventHandler("vRP:playerLeave",function(user_id,source) -- leave areas local areas = client_areas[source] for k,area in pairs(areas) do if area.inside then area.leave(source,k) end end client_areas[source] = nil end) -- create/update a player area function vRP.setArea(source,name,x,y,z,radius,height,cb_enter,cb_leave) local areas = client_areas[source] or {} client_areas[source] = areas areas[name] = {enter=cb_enter,leave=cb_leave} vRPclient._setArea(source,name,x,y,z,radius,height) end -- delete a player area function vRP.removeArea(source,name) -- delete remote area vRPclient._removeArea(source,name) -- delete local area local areas = client_areas[source] if areas then areas[name] = nil end end -- TUNNER SERVER API function tvRP.enterArea(name) local areas = client_areas[source] if areas then local area = areas[name] if area and area.enter and not area.inside then -- trigger enter callback area.inside = true area.enter(source,name) end end end function tvRP.leaveArea(name) local areas = client_areas[source] if areas then local area = areas[name] if area and area.leave and area.inside then -- trigger leave callback area.inside = false area.leave(source,name) end end end local cfg = module("cfg/blips_markers") -- add additional static blips/markers AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn) if first_spawn then for k,v in pairs(cfg.blips) do vRPclient._addBlip(source,v[1],v[2],v[3],v[4],v[5],v[6]) end for k,v in pairs(cfg.markers) do vRPclient._addMarker(source,v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11]) end end end)
local client_areas = {} -- free client areas when leaving AddEventHandler("vRP:playerLeave",function(user_id,source) -- leave areas local areas = client_areas[source] if areas then for k,area in pairs(areas) do if area.inside then area.leave(source,k) end end end client_areas[source] = nil end) -- create/update a player area function vRP.setArea(source,name,x,y,z,radius,height,cb_enter,cb_leave) local areas = client_areas[source] or {} client_areas[source] = areas areas[name] = {enter=cb_enter,leave=cb_leave} vRPclient._setArea(source,name,x,y,z,radius,height) end -- delete a player area function vRP.removeArea(source,name) -- delete remote area vRPclient._removeArea(source,name) -- delete local area local areas = client_areas[source] if areas then areas[name] = nil end end -- TUNNER SERVER API function tvRP.enterArea(name) local areas = client_areas[source] if areas then local area = areas[name] if area and area.enter and not area.inside then -- trigger enter callback area.inside = true area.enter(source,name) end end end function tvRP.leaveArea(name) local areas = client_areas[source] if areas then local area = areas[name] if area and area.leave and area.inside then -- trigger leave callback area.inside = false area.leave(source,name) end end end local cfg = module("cfg/blips_markers") -- add additional static blips/markers AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn) if first_spawn then for k,v in pairs(cfg.blips) do vRPclient._addBlip(source,v[1],v[2],v[3],v[4],v[5],v[6]) end for k,v in pairs(cfg.markers) do vRPclient._addMarker(source,v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11]) end end end)
Fix area issue.
Fix area issue.
Lua
mit
ImagicTheCat/vRP,ImagicTheCat/vRP
f9eb871c9c58c8ba4bb5f0e99166166eb62a61cc
item/teleportgate.lua
item/teleportgate.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- teleporter gate -- Nop -- UPDATE common SET com_script='item.teleportgate' WHERE com_itemid IN (10,792,794,795) require("base.common") require("base.factions") module("item.teleportgate", package.seeall) --[[ --TargetName[ 1 ]="Galmair"; TargetCoor[ 1 ]={ 424, 245, 0 }; --TargetName[ 2 ]="Cadomyr"; TargetCoor[ 2 ]={ 127, 647, 0 }; --TargetName[ 3 ]="Runewick"; TargetCoor[ 3 ]={ 788, 826, 0 }; --TargetName[ 4 ]="Wilderland"; TargetCoor[ 4 ]={ 683, 307, 0 }; --TargetName[ 5 ]="Safepoint 1"; TargetCoor[ 5 ]={ 0, 7, 0 }; --TargetName[ 6 ]="Safepoint 2"; TargetCoor[ 6 ]={ 1, 7, 0 }; --TargetName[ 7 ]="Safepoint 3"; TargetCoor[ 7 ]={ 2, 7, 0 }; --TargetName[ 8 ]="Safepoint 4"; TargetCoor[ 8 ]={ 3, 7, 0 }; --TargetName[ 9 ]="Safepoint 5"; TargetCoor[ 9 ]={ 4, 7, 0 }; ]] function CharacterOnField( User ) if (User:getType() ~= 0) then -- only players, else end of script return end local SourceItem = world:getItemOnField( User.pos ); local destCoordX, destCoordY, destCoordZ local dest local destFound = false destCoordX = SourceItem:getData("destinationCoordsX") destCoordY = SourceItem:getData("destinationCoordsY") destCoordZ = SourceItem:getData("destinationCoordsZ") if (destCoordX ~= "") and (destCoordY ~= "") and (destCoordZ ~= "") then destCoordX = tonumber(destCoordX) destCoordY = tonumber(destCoordY) destCoordZ = tonumber(destCoordZ) dest = position(destCoordX,destCoordY,destCoordZ) destFound = true end if destFound then -- destination was defined world:makeSound( 13, dest ) world:gfx( 41, User.pos ) User:warp( dest ); world:gfx( 41, User.pos ) base.common.InformNLS( User, "Du machst eine magische Reise.", "You travel by the realm of magic." ); if ( SourceItem.wear ~= 255 ) then if ( SourceItem.quality > 200 ) then SourceItem.quality = SourceItem.quality - 100; world:changeItem( SourceItem ); else world:erase( SourceItem, SourceItem.number ); end end end end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE common SET com_script='item.teleportgate' WHERE com_itemid IN (10,792,794,795) require("base.common") module("item.teleportgate", package.seeall) function CharacterOnField( User ) if (User:getType() ~= 0) then -- only players, else end of script return end local SourceItem = world:getItemOnField( User.pos ); local destCoordX, destCoordY, destCoordZ local dest local destFound = false destCoordX = SourceItem:getData("destinationCoordsX") destCoordY = SourceItem:getData("destinationCoordsY") destCoordZ = SourceItem:getData("destinationCoordsZ") if (destCoordX ~= "") and (destCoordY ~= "") and (destCoordZ ~= "") then destCoordX = tonumber(destCoordX) destCoordY = tonumber(destCoordY) destCoordZ = tonumber(destCoordZ) dest = position(destCoordX,destCoordY,destCoordZ) destFound = true end if destFound then -- destination was defined world:makeSound( 13, dest ) world:gfx( 41, User.pos ) User:warp( dest ); world:gfx( 41, User.pos ) base.common.InformNLS( User, "Du machst eine magische Reise.", "You travel by the realm of magic." ); if ( SourceItem.wear ~= 255 ) then if ( SourceItem.quality > 200 ) then SourceItem.quality = SourceItem.quality - 100; world:changeItem( SourceItem ); else world:erase( SourceItem, SourceItem.number ); end end end end
whitespace fix and remove comment
whitespace fix and remove comment
Lua
agpl-3.0
KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content
708df23e42372a592b5dcf73a07ab0ca819b5499
BtUtils/project-manager.lua
BtUtils/project-manager.lua
--- Loads and allows to work with BETS projects. -- @module ProjectManager -- @pragma nostrip -- tag @pragma makes it so that the name of the module is not stripped from the function names if(not BtUtils)then VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) end local Utils = BtUtils return Utils:Assign("ProjectManager", function() local ProjectManager = {} local Debug = Utils.Debug local Logger = Debug.Logger local dirList, subDirs = Utils.dirList, Utils.subDirs local PROJECT_PATH = LUAUI_DIRNAME .. "BETS/Projects/" local INTERNAL_PROJECT_PATH = LUAUI_DIRNAME .. "Widgets/BtProjects/" local TMP_DIR = PROJECT_PATH .. ".bets/" local projects = {} local archives = {} local function loadArchives() for _, projectsRoot in ipairs({ PROJECT_PATH, INTERNAL_PROJECT_PATH }) do for i, archiveName in ipairs(dirList(projectsRoot, "*.sdz")) do local path = projectsRoot .. archiveName VFS.MapArchive(path) archives[archiveName] = { name = archiveName, path = path, } end end end local function unloadArchives() for name, archive in pairs(archives) do VFS.UnmapArchive(archive.path) end archives = {} end local function loadProjects() for _, projectsRoot in ipairs({ PROJECT_PATH, INTERNAL_PROJECT_PATH }) do for i, projectName in ipairs(subDirs(projectsRoot)) do if(projectName:sub(1,1) ~= "." and not projects[projectName])then local path = projectsRoot .. projectName .. "/" projects[projectName] = { name = projectName, path = path, isArchive = not subDirs(projectsRoot, projectName, VFS.RAW)[1], -- check whether the subdirectory exists outside of an archive } end end end end function ProjectManager.unload() projects = {} unloadArchives() end function ProjectManager.reload() ProjectManager.unload() ProjectManager.load() end function ProjectManager.load() loadArchives() loadProjects() end -- checks that the specified folder is empty local function checkEmptyDirectory(path) if(dirList(path)[1])then return false end for i, subdir in ipairs(subDirs(path)) do if(not checkEmptyDirectory(path .. subdir .. "/"))then return false end end return true end function ProjectManager.archivate(projectName) local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end Spring.CreateDir(TMP_DIR .. PROJECT_PATH) if(not checkEmptyDirectory(TMP_DIR))then error("The " .. TMP_DIR .. " directory is not empty. There may be some leftover files from previous archivations. Manual intervention necessary.") end os.rename(project.path, TMP_DIR .. PROJECT_PATH .. projectName) -- move to the archivation directory local success, msg = pcall(VFS.CompressFolder, TMP_DIR, "zip", PROJECT_PATH .. "/" .. projectName .. ".sdz", false, VFS.RAW) os.rename(TMP_DIR .. PROJECT_PATH .. projectName, project.path) -- move back return success, msg end function ProjectManager.getProjects() local result, i = {}, 1 for projectName, project in pairs(projects) do result[i] = project i = i + 1 end return result end function ProjectManager.findFile(contentType, qualifiedName, name) local projectName if(name)then projectName = qualifiedName name = name else projectName, name = qualifiedName:match("^(.-)%.(.+)$") end local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end local path = project.path .. (contentType.directoryName and (contentType.directoryName .. "/") or "") .. contentType.nameToFile(name) --[[ if(not VFS.FileExists(path))then return nil, "File " .. path .. " does not exist." end ]] return path, { project = projectName, name = name, qualifiedName = projectName .. "." .. name, exists = VFS.FileExists(path), readonly = project.isArchive } end local function listProjectInternal(result, i, project, contentType) for j, v in ipairs(dirList(project.path .. (contentType.directoryName or ""), contentType.fileMask)) do local name = contentType.fileToName(v) result[i] = { project = project.name, name = name, qualifiedName = project.name .. "." .. name, filename = v, path = project.path .. (contentType.directoryName and (contentType.directoryName .. "/") or "") .. v, } i = i + 1 end return result, i end function ProjectManager.listProject(projectName, contentType) local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end local result, i = {}, 1 return (listProjectInternal({}, 1, project, contentType)) end function ProjectManager.listAll(contentType) local result, i = {}, 1 for projectName, project in pairs(projects) do result, i = listProjectInternal(result, i, project, contentType) end return result end function ProjectManager.makeRegularContentType(subdirectory, extension) return { directoryName = subdirectory, fileMask = "*." .. extension, nameToFile = function(name) return name .. "." .. extension end, fileToName = Utils.removeExtension, } end ProjectManager.load() return ProjectManager end)
--- Loads and allows to work with BETS projects. -- @module ProjectManager -- @pragma nostrip -- tag @pragma makes it so that the name of the module is not stripped from the function names if(not BtUtils)then VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) end local Utils = BtUtils return Utils:Assign("ProjectManager", function() local ProjectManager = {} local Debug = Utils.Debug local Logger = Debug.Logger local dirList, subDirs = Utils.dirList, Utils.subDirs local PROJECT_PATH = LUAUI_DIRNAME .. "BETS/Projects/" local INTERNAL_PROJECT_PATH = LUAUI_DIRNAME .. "Widgets/BtProjects/" local TMP_DIR = PROJECT_PATH .. ".bets/" local CAPITALIZATION_FILE = ".capitalization" local projects = {} local archives = {} local function loadArchives() for _, projectsRoot in ipairs({ PROJECT_PATH, INTERNAL_PROJECT_PATH }) do for i, archiveName in ipairs(dirList(projectsRoot, "*.sdz")) do local path = projectsRoot .. archiveName VFS.MapArchive(path) archives[archiveName] = { name = archiveName, path = path, } end end end local function unloadArchives() for name, archive in pairs(archives) do VFS.UnmapArchive(archive.path) end archives = {} end local function loadProjects() for _, projectsRoot in ipairs({ PROJECT_PATH, INTERNAL_PROJECT_PATH }) do for i, projectName in ipairs(subDirs(projectsRoot)) do if(projectName:sub(1,1) ~= ".")then local path = projectsRoot .. projectName .. "/" local capitalization = VFS.LoadFile(path .. CAPITALIZATION_FILE) if(capitalization and capitalization:lower() == projectName:lower())then projectName = capitalization end if(not projects[projectName])then projects[projectName] = { name = projectName, path = path, isArchive = not subDirs(projectsRoot, projectName, VFS.RAW)[1], -- check whether the subdirectory exists outside of an archive } end end end end end function ProjectManager.unload() projects = {} unloadArchives() end function ProjectManager.reload() ProjectManager.unload() ProjectManager.load() end function ProjectManager.load() loadArchives() loadProjects() end -- checks that the specified folder is empty local function checkEmptyDirectory(path) if(dirList(path)[1])then return false end for i, subdir in ipairs(subDirs(path)) do if(not checkEmptyDirectory(path .. subdir .. "/"))then return false end end return true end function ProjectManager.archivate(projectName) local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end if(project.isArchive)then return nil, "Project " .. tostring(projectName) .. " is already in an archive." end Spring.CreateDir(TMP_DIR .. PROJECT_PATH) if(not checkEmptyDirectory(TMP_DIR))then error("The " .. TMP_DIR .. " directory is not empty. There may be some leftover files from previous archivations. Manual intervention necessary.") end os.rename(project.path, TMP_DIR .. PROJECT_PATH .. projectName) -- move to the archivation directory local success, msg = pcall(function() capitalizationFile = io.open(TMP_DIR .. PROJECT_PATH .. projectName .. "/" .. CAPITALIZATION_FILE, "w") capitalizationFile:write(projectName) capitalizationFile:close() return VFS.CompressFolder(TMP_DIR, "zip", PROJECT_PATH .. "/" .. projectName .. ".sdz", false, VFS.RAW) end) os.remove(TMP_DIR .. PROJECT_PATH .. projectName .. "/" .. CAPITALIZATION_FILE) os.rename(TMP_DIR .. PROJECT_PATH .. projectName, project.path) -- move back return success, msg end function ProjectManager.getProjects() local result, i = {}, 1 for projectName, project in pairs(projects) do result[i] = project i = i + 1 end return result end function ProjectManager.findFile(contentType, qualifiedName, name) local projectName if(name)then projectName = qualifiedName name = name else projectName, name = qualifiedName:match("^(.-)%.(.+)$") end local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end local path = project.path .. (contentType.directoryName and (contentType.directoryName .. "/") or "") .. contentType.nameToFile(name) --[[ if(not VFS.FileExists(path))then return nil, "File " .. path .. " does not exist." end ]] return path, { project = projectName, name = name, qualifiedName = projectName .. "." .. name, exists = VFS.FileExists(path), readonly = project.isArchive } end local function listProjectInternal(result, i, project, contentType) for j, v in ipairs(dirList(project.path .. (contentType.directoryName or ""), contentType.fileMask)) do local name = contentType.fileToName(v) result[i] = { project = project.name, name = name, qualifiedName = project.name .. "." .. name, filename = v, path = project.path .. (contentType.directoryName and (contentType.directoryName .. "/") or "") .. v, } i = i + 1 end return result, i end function ProjectManager.listProject(projectName, contentType) local project = projects[projectName] if(not project)then return nil, "Project " .. tostring(projectName) .. " could not be found." end local result, i = {}, 1 return (listProjectInternal({}, 1, project, contentType)) end function ProjectManager.listAll(contentType) local result, i = {}, 1 for projectName, project in pairs(projects) do result, i = listProjectInternal(result, i, project, contentType) end return result end function ProjectManager.makeRegularContentType(subdirectory, extension) return { directoryName = subdirectory, fileMask = "*." .. extension, nameToFile = function(name) return name .. "." .. extension end, fileToName = Utils.removeExtension, } end ProjectManager.load() return ProjectManager end)
Possibly a fix to the problem with case insensitiveness of files from archives. A special ".capitalization" file is added to the archive to preserve the original case
Possibly a fix to the problem with case insensitiveness of files from archives. A special ".capitalization" file is added to the archive to preserve the original case
Lua
mit
MartinFrancu/BETS
d4dd311a442e33cab051eefb91a8051bc0db9ef5
calibration.lua
calibration.lua
local co = coroutine function emufun.calibration() local W,H = love.graphics.getWidth(),love.graphics.getHeight() local message = "?" local controls = {} local function calibrate() local function ask_input(gesture) local key repeat key = co.yield(gesture) until not controls[key] return key end local function command(gesture, fn) controls[ask_input(gesture)] = fn end command("up", emufun.prev_game) command("down", emufun.next_game) command("left", emufun.prev_system) command("right", emufun.next_system) command("ok", emufun.down) command("cancel", emufun.up) table.copy(controls, input) input.key_any = nil input.joy_any = nil co.yield(nil) end local calibrator = co.wrap(calibrate) message = calibrator() function love.draw() local lg = love.graphics lg.printf("CALIBRATION", 0, 0, W, "center") lg.printf("Press button for "..message, 0, H/2-20, W, "center") end function input.key_any(key) message = calibrator("key_"..key) if not message then return emufun.loadgames() end end function input.joy_any(joy, type, a, b) local name if type == "button" then name = ("joy_%d_button_%d"):format(joy, a) elseif type == "axis" and b ~= "center" then name = ("joy_%d_axis_%d_%s"):format(joy, a, b) elseif type == "hat" and a ~= "c" then name = ("joy_%d_hat_%s"):format(joy, a) else return end message = calibrator(name) end end
local co = coroutine function emufun.calibration() local W,H = love.graphics.getWidth(),love.graphics.getHeight() local message = "?" local controls = {} local function calibrate() local function ask_input(gesture) local key repeat key = co.yield(gesture) until not controls[key] return key end local function command(gesture, fn) controls[ask_input(gesture)] = fn end command("up", emufun.prev_game) command("down", emufun.next_game) command("left", emufun.prev_system) command("right", emufun.next_system) command("ok", emufun.down) command("cancel", emufun.up) table.copy(controls, input) input.key_any = nil input.joy_any = nil co.yield(nil) end local calibrator = co.wrap(calibrate) message = calibrator() function love.draw() local lg = love.graphics lg.printf("CALIBRATION", 0, 0, W, "center") lg.printf("Press button for "..message, 0, H/2-20, W, "center") end function input.key_any(key) message = calibrator("key_"..key) if not message then return emufun.loadgames() end end function input.joy_any(joy, type, a, b) local name if type == "button" then name = ("joy_%d_button_%d"):format(joy, a) elseif type == "axis" and b ~= "center" then name = ("joy_%d_axis_%d_%s"):format(joy, a, b) elseif type == "hat" and a ~= "c" then name = ("joy_%d_hat_%s"):format(joy, a) else return end message = calibrator(name) if not message then return emufun.loadgames() end end end
Fixed a crash in the calibrator when using a gamepad.
Fixed a crash in the calibrator when using a gamepad.
Lua
mit
ToxicFrog/EmuFun
a58d88d0d313134878ae5b0bb060f5977f10511f
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
-- Detect layout change function handleLayoutChange(layout) if layout then local screenId = hs.window.focusedWindow():screen():id() setActiveScreen(screenId) print('current display ' .. screenId) end end function setActiveScreen(screenId) local devicePath = getSerialOutputDevice() if devicePath == "" then return end local file = assert(io.open(devicePath, "w")) file:write("set " .. screenId .. "\n") file:flush() file:close() end function getSerialOutputDevice() local command = "ioreg -c IOSerialBSDClient -r -t " .. "| awk 'f;/Photon/{f=1};/IOCalloutDevice/{exit}' " .. "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'" local handle = io.popen(command) local result = handle:read("*a") handle:close() -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua return result:match("^%s*(.-)%s*$") end hs.screen.watcher.newWithActiveScreen(handleLayoutChange):start() handleLayoutChange(true) -- set the initial screen -- Run this from the Hammerspoon console to get a listing of display IDs function listAllScreens () local primaryId = hs.screen.primaryScreen():id() for _, screen in pairs(hs.screen.allScreens()) do local screenId = screen:id() print( "id: " .. screenId .. " \"" .. screen:name() .. "\"" .. (screenId == primaryId and " (primary)" or "") ) end end
-- Detect layout change function handleLayoutChange() -- Always send the screenId, even on real layout changes (could be add/remove display) local screenId = hs.window.focusedWindow():screen():id() setActiveScreen(screenId) print('current display ' .. screenId) end function setActiveScreen(screenId) local devicePath = getSerialOutputDevice() if devicePath == "" then return end local file = assert(io.open(devicePath, "w")) file:write("set " .. screenId .. "\n") file:flush() file:close() end function getSerialOutputDevice() local command = "ioreg -c IOSerialBSDClient -r -t " .. "| awk 'f;/Photon/{f=1};/IOCalloutDevice/{exit}' " .. "| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'" local handle = io.popen(command) local result = handle:read("*a") handle:close() -- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua return result:match("^%s*(.-)%s*$") end hs.screen.watcher.newWithActiveScreen(handleLayoutChange):start() handleLayoutChange(true) -- set the initial screen -- Run this from the Hammerspoon console to get a listing of display IDs function listAllScreens () local primaryId = hs.screen.primaryScreen():id() for _, screen in pairs(hs.screen.allScreens()) do local screenId = screen:id() print( "id: " .. screenId .. " \"" .. screen:name() .. "\"" .. (screenId == primaryId and " (primary)" or "") ) end end
fix(Hammerspoon): Always update the current display, regardless of layout change
fix(Hammerspoon): Always update the current display, regardless of layout change
Lua
mit
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
8c78271dfa8e741e48e27179f30fa58734c57333
scen_edit/view/view.lua
scen_edit/view/view.lua
SB_VIEW_DIR = Path.Join(SB_DIR, "view/") SB_VIEW_MAIN_WINDOW_DIR = Path.Join(SB_VIEW_DIR, "main_window/") SB_VIEW_ACTIONS_DIR = Path.Join(SB_VIEW_DIR, "actions/") SB_VIEW_OBJECT_DIR = Path.Join(SB_VIEW_DIR, "object/") SB_VIEW_MAP_DIR = Path.Join(SB_VIEW_DIR, "map/") SB_VIEW_TRIGGER_DIR = Path.Join(SB_VIEW_DIR, "trigger/") SB_VIEW_GENERAL_DIR = Path.Join(SB_VIEW_DIR, "general/") SB_VIEW_FLOATING_DIR = Path.Join(SB_VIEW_DIR, "floating/") SB_VIEW_DIALOG_DIR = Path.Join(SB_VIEW_DIR, "dialog/") View = LCS.class{} function View:init() SB.IncludeDir(SB_VIEW_DIR) SB.Include(Path.Join(SB_VIEW_MAIN_WINDOW_DIR, "main_window_panel.lua")) SB.IncludeDir(SB_VIEW_MAIN_WINDOW_DIR) SB.Include(Path.Join(SB_VIEW_ACTIONS_DIR, "abstract_action.lua")) SB.IncludeDir(SB_VIEW_ACTIONS_DIR) SB.IncludeDir(SB_VIEW_OBJECT_DIR) SB.IncludeDir(SB_VIEW_MAP_DIR) SB.IncludeDir(SB_VIEW_TRIGGER_DIR) SB.IncludeDir(SB_VIEW_GENERAL_DIR) SB.IncludeDir(SB_VIEW_FLOATING_DIR) SB.IncludeDir(SB_VIEW_DIALOG_DIR) SB.clipboard = Clipboard() self.areaViews = {} self.selectionManager = SelectionManager() self.displayDevelop = true self.tabbedWindow = TabbedWindow() self.modelShaders = ModelShaders() self.bottomBar = BottomBar() self.teamSelector = TeamSelector() self.lobbyButton = LobbyButton() self.projectStatus = ProjectStatus() end function View:Update() if self.teamSelector then self.teamSelector:Update() end self.selectionManager:Update() self.bottomBar:Update() end function View:drawRect(x1, z1, x2, z2) if x1 < x2 then _x1 = x1 _x2 = x2 else _x1 = x2 _x2 = x1 end if z1 < z2 then _z1 = z1 _z2 = z2 else _z1 = z2 _z2 = z1 end gl.DrawGroundQuad(_x1, _z1, _x2, _z2) end function View:drawRects() gl.PushMatrix() for _, areaView in pairs(self.areaViews) do areaView:Draw() end gl.PopMatrix() end function View:DrawWorld() end function View:DrawWorldPreUnit() if self.displayDevelop then self:drawRects() end self.selectionManager:DrawWorldPreUnit() end function View:DrawScreen() gl.PushMatrix() local vsx, vsy = Spring.GetViewGeometry() if not rotate then rotate = 0 id = 0 end -- gl.PushMatrix() -- gl.DepthTest(GL.LEQUAL) -- gl.DepthMask(true) -- local shaderObj = SB.view.modelShaders:GetShader() -- gl.UseShader(shaderObj.shader) -- gl.Uniform(shaderObj.timeID, os.clock()) -- --gl.Translate(100, Spring.GetGroundHeight(100, 100), 100) -- gl.Translate(vsx / 2, 500, 50) -- gl.Rotate(30, 1, -1, 0) -- gl.Rotate(rotate, 0, 1, 0) -- gl.Scale(5, 5, 5) -- rotate = rotate + 5 -- if rotate % 360 == 0 then -- id = id + 1 -- end -- -- featureBridge.glObjectShapeTextures(id, true) -- -- featureBridge.glObjectShape(id, 0, true) -- -- featureBridge.glObjectShapeTextures(id, false) -- unitBridge.glObjectShapeTextures(id, true) -- unitBridge.glObjectShape(id, 0, true) -- unitBridge.glObjectShapeTextures(id, false) -- gl.UseShader(0) -- gl.PopMatrix() -- gl.PushMatrix() -- local i = 1 -- local step = 200 -- for texType, shadingTex in pairs(SB.model.textureManager.shadingTextures) do -- gl.Texture(shadingTex) -- gl.TexRect(i * step, 1 * step, (i+1) * step, 2 * step) -- i = i + 1 -- end -- i = 1 -- local mapTex = SB.model.textureManager.mapFBOTextures[0][0] -- if mapTex then -- gl.Texture(mapTex.texture) -- gl.TexRect(i * step, 1 * step, (i+1) * step, (1+1) * step) -- end -- gl.PopMatrix() gl.PopMatrix() end
SB_VIEW_DIR = Path.Join(SB_DIR, "view/") SB_VIEW_MAIN_WINDOW_DIR = Path.Join(SB_VIEW_DIR, "main_window/") SB_VIEW_ACTIONS_DIR = Path.Join(SB_VIEW_DIR, "actions/") SB_VIEW_OBJECT_DIR = Path.Join(SB_VIEW_DIR, "object/") SB_VIEW_MAP_DIR = Path.Join(SB_VIEW_DIR, "map/") SB_VIEW_TRIGGER_DIR = Path.Join(SB_VIEW_DIR, "trigger/") SB_VIEW_GENERAL_DIR = Path.Join(SB_VIEW_DIR, "general/") SB_VIEW_FLOATING_DIR = Path.Join(SB_VIEW_DIR, "floating/") SB_VIEW_DIALOG_DIR = Path.Join(SB_VIEW_DIR, "dialog/") View = LCS.class{} function View:init() SB.IncludeDir(SB_VIEW_DIR) SB.Include(Path.Join(SB_VIEW_MAIN_WINDOW_DIR, "main_window_panel.lua")) SB.IncludeDir(SB_VIEW_MAIN_WINDOW_DIR) SB.Include(Path.Join(SB_VIEW_ACTIONS_DIR, "abstract_action.lua")) SB.IncludeDir(SB_VIEW_ACTIONS_DIR) SB.IncludeDir(SB_VIEW_OBJECT_DIR) SB.IncludeDir(SB_VIEW_MAP_DIR) SB.IncludeDir(SB_VIEW_TRIGGER_DIR) SB.IncludeDir(SB_VIEW_GENERAL_DIR) SB.IncludeDir(SB_VIEW_FLOATING_DIR) SB.IncludeDir(SB_VIEW_DIALOG_DIR) SB.clipboard = Clipboard() self.areaViews = {} self.selectionManager = SelectionManager() self.displayDevelop = true self.tabbedWindow = TabbedWindow() self.modelShaders = ModelShaders() self.bottomBar = BottomBar() self.teamSelector = TeamSelector() self.lobbyButton = LobbyButton() self.projectStatus = ProjectStatus() end function View:Update() if self.teamSelector then self.teamSelector:Update() end self.selectionManager:Update() self.projectStatus:Update() self.bottomBar:Update() end function View:drawRect(x1, z1, x2, z2) if x1 < x2 then _x1 = x1 _x2 = x2 else _x1 = x2 _x2 = x1 end if z1 < z2 then _z1 = z1 _z2 = z2 else _z1 = z2 _z2 = z1 end gl.DrawGroundQuad(_x1, _z1, _x2, _z2) end function View:drawRects() gl.PushMatrix() for _, areaView in pairs(self.areaViews) do areaView:Draw() end gl.PopMatrix() end function View:DrawWorld() end function View:DrawWorldPreUnit() if self.displayDevelop then self:drawRects() end self.selectionManager:DrawWorldPreUnit() end function View:DrawScreen() gl.PushMatrix() local vsx, vsy = Spring.GetViewGeometry() if not rotate then rotate = 0 id = 0 end -- gl.PushMatrix() -- gl.DepthTest(GL.LEQUAL) -- gl.DepthMask(true) -- local shaderObj = SB.view.modelShaders:GetShader() -- gl.UseShader(shaderObj.shader) -- gl.Uniform(shaderObj.timeID, os.clock()) -- --gl.Translate(100, Spring.GetGroundHeight(100, 100), 100) -- gl.Translate(vsx / 2, 500, 50) -- gl.Rotate(30, 1, -1, 0) -- gl.Rotate(rotate, 0, 1, 0) -- gl.Scale(5, 5, 5) -- rotate = rotate + 5 -- if rotate % 360 == 0 then -- id = id + 1 -- end -- -- featureBridge.glObjectShapeTextures(id, true) -- -- featureBridge.glObjectShape(id, 0, true) -- -- featureBridge.glObjectShapeTextures(id, false) -- unitBridge.glObjectShapeTextures(id, true) -- unitBridge.glObjectShape(id, 0, true) -- unitBridge.glObjectShapeTextures(id, false) -- gl.UseShader(0) -- gl.PopMatrix() -- gl.PushMatrix() -- local i = 1 -- local step = 200 -- for texType, shadingTex in pairs(SB.model.textureManager.shadingTextures) do -- gl.Texture(shadingTex) -- gl.TexRect(i * step, 1 * step, (i+1) * step, 2 * step) -- i = i + 1 -- end -- i = 1 -- local mapTex = SB.model.textureManager.mapFBOTextures[0][0] -- if mapTex then -- gl.Texture(mapTex.texture) -- gl.TexRect(i * step, 1 * step, (i+1) * step, (1+1) * step) -- end -- gl.PopMatrix() gl.PopMatrix() end
fix project status update
fix project status update
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
03ccff35c3498c375f23c5ce27b651704db5f087
app/main.lua
app/main.lua
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local luvi = require('luvi') local bundle = luvi.bundle -- Manually register the require replacement system to bootstrap things bundle.register("luvit-require", "modules/require.lua"); -- Upgrade require system in-place local require = require('luvit-require')()("bundle:modules/main.lua") _G.require = require local uv = require('uv') local utils = require('utils') local startRepl = nil local combo = nil local script = nil local extra = {} local function usage() print("Usage: " .. args[0] .. " [options] script.lua [arguments]"..[[ Options: -h, --help Print this help screen. -v, --version Print the version. -e code_chunk Evaluate code chunk and print result. -i, --interactive Enter interactive repl after executing script. -n, --no-color Disable colors. (Note, if no script is provided, a repl is run instead.) ]]) startRepl = false end local function version() print("TODO: show luvit version") startRepl = false end local shorts = { h = "help", v = "version", e = "eval", i = "interactive", n = "no-color" } local flags = { help = usage, version = version, eval = function () local repl = require('repl')(utils.stdin, utils.stdout) combo = repl.evaluateLine startRepl = false end, interactive = function () startRepl = true end, ["no-color"] = function () utils.loadColors() end } for i = 1, #args do local arg = args[i] if script then extra[#extra + 1] = arg elseif combo then combo(arg) combo = nil elseif string.sub(arg, 1, 1) == "-" then local flag if (string.sub(arg, 2, 2) == "-") then flag = string.sub(arg, 3) else flag = shorts[string.sub(arg, 2)] end flags[flag]() else script = arg end end if combo then error("Missing flag value") end if startRepl == nil and not script then startRepl = true end if script then require(luvi.path.join(uv.cwd(), script)) end if startRepl then local c = utils.color local greeting = "Welcome to the " .. c("Bred") .. "L" .. c("Bgreen") .. "uv" .. c("Bblue") .. "it" .. c() .. " repl!" require('repl')(utils.stdin, utils.stdout, greeting, ...).start() end -- Start the event loop uv.run() -- When the loop exits, close all uv handles. uv.walk(uv.close) uv.run()
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local luvi = require('luvi') local bundle = luvi.bundle -- Manually register the require replacement system to bootstrap things bundle.register("luvit-require", "modules/require.lua"); -- Upgrade require system in-place local require = require('luvit-require')()("bundle:modules/main.lua") _G.require = require local uv = require('uv') local utils = require('utils') local startRepl = nil local combo = nil local script = nil local extra = {} local function usage() print("Usage: " .. args[0] .. " [options] script.lua [arguments]"..[[ Options: -h, --help Print this help screen. -v, --version Print the version. -e code_chunk Evaluate code chunk and print result. -i, --interactive Enter interactive repl after executing script. -n, --no-color Disable colors. -c, --16-colors Use simple ANSI colors -C, --256-colors Use 256-mode ANSI colors (Note, if no script is provided, a repl is run instead.) ]]) startRepl = false end local function version() print("TODO: show luvit version") startRepl = false end local shorts = { h = "help", v = "version", e = "eval", i = "interactive", n = "no-color", c = "16-colors", C = "256-colors", } local flags = { help = usage, version = version, eval = function () local repl = require('repl')(utils.stdin, utils.stdout) combo = repl.evaluateLine startRepl = false end, interactive = function () startRepl = true end, ["no-color"] = function () utils.loadColors() end, ["16-colors"] = function () utils.loadColors(16) end, ["256-colors"] = function () utils.loadColors(256) end, } for i = 1, #args do local arg = args[i] if script then extra[#extra + 1] = arg elseif combo then combo(arg) combo = nil elseif string.sub(arg, 1, 1) == "-" then local flag if (string.sub(arg, 2, 2) == "-") then flag = string.sub(arg, 3) else flag = shorts[string.sub(arg, 2)] end flags[flag]() else script = arg end end if combo then error("Missing flag value") end if startRepl == nil and not script then startRepl = true end if script then require(luvi.path.join(uv.cwd(), script)) end if startRepl then local c = utils.color local greeting = "Welcome to the " .. c("err") .. "L" .. c("quotes") .. "uv" .. c("table") .. "it" .. c() .. " repl!" require('repl')(utils.stdin, utils.stdout, greeting, ...).start() end -- Start the event loop uv.run() -- When the loop exits, close all uv handles. uv.walk(uv.close) uv.run()
Fix colors in main
Fix colors in main
Lua
apache-2.0
DBarney/luvit,bsn069/luvit,zhaozg/luvit,kaustavha/luvit,luvit/luvit,DBarney/luvit,bsn069/luvit,rjeli/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,rjeli/luvit,zhaozg/luvit,rjeli/luvit,bsn069/luvit,kaustavha/luvit,luvit/luvit,DBarney/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream
4d2dc36d6482189fad54e0776f8b6ba9a6b151cb
lexers/hypertext.lua
lexers/hypertext.lua
-- Copyright 2006-2013 Mitchell mitchell.att.foicica.com. See LICENSE. -- HTML LPeg lexer. local l, token, word_match = lexer, lexer.token, lexer.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'hypertext'} case_insensitive_tags = true -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, '<!--' * (l.any - '-->')^0 * P('-->')^-1) -- Strings. local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local string = l.last_char_includes('=') * token(l.STRING, sq_str + dq_str) local in_tag = P(function(input, index) local before = input:sub(1, index - 1) local s, e = before:find('<[^>]-$'), before:find('>[^<]-$') if s and e then return s > e and index or nil end if s then return index end return input:find('^[^<]->', index) and index or nil end) -- Numbers. local number = l.last_char_includes('=') * token(l.NUMBER, l.digit^1 * P('%')^-1) * in_tag -- Elements. local known_element = token('element', word_match({ 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'b', 'base', 'basefont', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'isindex', 'kbd', 'label', 'legend', 'li', 'link', 'map', 'menu', 'meta', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'samp', 'script', 'select', 'small', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 's', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'xml' }, nil, case_insensitive_tags)) local unknown_element = token('unknown_element', l.word) local element = l.last_char_includes('</') * (known_element + unknown_element) -- Attributes local known_attribute = token('attribute', ('data-' * l.alnum^1) + word_match({ 'abbr', 'accept-charset', 'accept', 'accesskey', 'action', 'align', 'alink', 'alt', 'archive', 'axis', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'classid', 'clear', 'codebase', 'codetype', 'color', 'cols', 'colspan', 'compact', 'content', 'coords', 'data', 'datafld', 'dataformatas', 'datapagesize', 'datasrc', 'datetime', 'declare', 'defer', 'dir', 'disabled', 'enctype', 'event', 'face', 'for', 'frame', 'frameborder', 'headers', 'height', 'href', 'hreflang', 'hspace', 'http-equiv', 'id', 'ismap', 'label', 'lang', 'language', 'leftmargin', 'link', 'longdesc', 'marginwidth', 'marginheight', 'maxlength', 'media', 'method', 'multiple', 'name', 'nohref', 'noresize', 'noshade', 'nowrap', 'object', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove', 'onmouseover', 'onmouseout', 'onmouseup', 'onreset', 'onselect', 'onsubmit', 'onunload', 'profile', 'prompt', 'readonly', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scheme', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'standby', 'start', 'style', 'summary', 'tabindex', 'target', 'text', 'title', 'topmargin', 'type', 'usemap', 'valign', 'value', 'valuetype', 'version', 'vlink', 'vspace', 'width', 'text', 'password', 'checkbox', 'radio', 'submit', 'reset', 'file', 'hidden', 'image', 'xml', 'xmlns', 'xml:lang' }, '-:', case_insensitive_tags)) local unknown_attribute = token('unknown_attribute', l.word) local attribute = (known_attribute + unknown_attribute) * #(l.space^0 * '=') -- Tags. local tag = token('tag', '<' * P('/')^-1 + P('/')^-1 * '>') -- Equals. local equals = token(l.OPERATOR, '=') * in_tag -- Entities. local entity = token('entity', '&' * (l.any - l.space - ';')^1 * ';') -- Doctype. local doctype = token('doctype', '<!' * word_match({'doctype'}, nil, case_insensitive_tags) * (l.any - '>')^1 * '>') M._rules = { {'whitespace', ws}, {'comment', comment}, {'doctype', doctype}, {'tag', tag}, {'element', element}, {'attribute', attribute}, {'equals', equals}, {'string', string}, {'number', number}, {'entity', entity}, } M._tokenstyles = { tag = l.STYLE_KEYWORD, element = l.STYLE_KEYWORD, unknown_element = l.STYLE_KEYWORD..',italics', attribute = l.STYLE_VARIABLE, unknown_attribute = l.STYLE_TYPE..',italics', entity = l.STYLE_OPERATOR, doctype = l.STYLE_COMMENT } -- Tags that start embedded languages. M.embed_start_tag = tag * element * ws^1 * attribute * ws^0 * equals * ws^0 * string * ws^0 * tag M.embed_end_tag = tag * element * tag -- Embedded CSS. local css = l.load('css') local style_element = word_match({'style'}, nil, case_insensitive_tags) local css_start_rule = #(P('<') * style_element * ('>' + P(function(input, index) if input:find('^%s+type%s*=%s*(["\'])text/css%1', index) then return index end end))) * M.embed_start_tag -- <style type="text/css"> local css_end_rule = #('</' * style_element * ws^0 * '>') * M.embed_end_tag -- </style> l.embed_lexer(M, css, css_start_rule, css_end_rule) -- Embedded Javascript. local js = l.load('javascript') local script_element = word_match({'script'}, nil, case_insensitive_tags) local js_start_rule = #(P('<') * script_element * ('>' + P(function(input, index) if input:find('^%s+type%s*=%s*(["\'])text/javascript%1', index) then return index end end))) * M.embed_start_tag -- <script type="text/javascript"> local js_end_rule = #('</' * script_element * ws^0 * '>') * M.embed_end_tag -- </script> l.embed_lexer(M, js, js_start_rule, js_end_rule) -- Embedded CoffeeScript. local cs = l.load('coffeescript') local script_element = word_match({'script'}, nil, case_insensitive_tags) local cs_start_rule = #(P('<') * script_element * P(function(input, index) if input:find('^[^>]+type%s*=%s*(["\'])text/coffeescript%1', index) then return index end end)) * M.embed_start_tag -- <script type="text/coffeescript"> local cs_end_rule = #('</' * script_element * ws^0 * '>') * M.embed_end_tag -- </script> l.embed_lexer(M, cs, cs_start_rule, cs_end_rule) M._foldsymbols = { _patterns = {'</?', '/>', '<!%-%-', '%-%->'}, tag = {['<'] = 1, ['/>'] = -1, ['</'] = -1}, [l.COMMENT] = {['<!--'] = 1, ['-->'] = -1} } return M
-- Copyright 2006-2013 Mitchell mitchell.att.foicica.com. See LICENSE. -- HTML LPeg lexer. local l, token, word_match = lexer, lexer.token, lexer.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'hypertext'} case_insensitive_tags = true -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local comment = token(l.COMMENT, '<!--' * (l.any - '-->')^0 * P('-->')^-1) -- Strings. local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local string = l.last_char_includes('=') * token(l.STRING, sq_str + dq_str) -- TODO: performance is terrible on large files. local in_tag = P(function(input, index) local before = input:sub(1, index - 1) local s, e = before:find('<[^>]-$'), before:find('>[^<]-$') if s and e then return s > e and index or nil end if s then return index end return input:find('^[^<]->', index) and index or nil end) -- Numbers. local number = l.last_char_includes('=') * token(l.NUMBER, l.digit^1 * P('%')^-1) --* in_tag -- Elements. local known_element = token('element', word_match({ 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'b', 'base', 'basefont', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'isindex', 'kbd', 'label', 'legend', 'li', 'link', 'map', 'menu', 'meta', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'samp', 'script', 'select', 'small', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 's', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'xml' }, nil, case_insensitive_tags)) local unknown_element = token('unknown_element', l.word) local element = l.last_char_includes('</') * (known_element + unknown_element) -- Attributes local known_attribute = token('attribute', ('data-' * l.alnum^1) + word_match({ 'abbr', 'accept-charset', 'accept', 'accesskey', 'action', 'align', 'alink', 'alt', 'archive', 'axis', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'classid', 'clear', 'codebase', 'codetype', 'color', 'cols', 'colspan', 'compact', 'content', 'coords', 'data', 'datafld', 'dataformatas', 'datapagesize', 'datasrc', 'datetime', 'declare', 'defer', 'dir', 'disabled', 'enctype', 'event', 'face', 'for', 'frame', 'frameborder', 'headers', 'height', 'href', 'hreflang', 'hspace', 'http-equiv', 'id', 'ismap', 'label', 'lang', 'language', 'leftmargin', 'link', 'longdesc', 'marginwidth', 'marginheight', 'maxlength', 'media', 'method', 'multiple', 'name', 'nohref', 'noresize', 'noshade', 'nowrap', 'object', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove', 'onmouseover', 'onmouseout', 'onmouseup', 'onreset', 'onselect', 'onsubmit', 'onunload', 'profile', 'prompt', 'readonly', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scheme', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'standby', 'start', 'style', 'summary', 'tabindex', 'target', 'text', 'title', 'topmargin', 'type', 'usemap', 'valign', 'value', 'valuetype', 'version', 'vlink', 'vspace', 'width', 'text', 'password', 'checkbox', 'radio', 'submit', 'reset', 'file', 'hidden', 'image', 'xml', 'xmlns', 'xml:lang' }, '-:', case_insensitive_tags)) local unknown_attribute = token('unknown_attribute', l.word) local attribute = (known_attribute + unknown_attribute) * #(l.space^0 * '=') -- Tags. local tag = token('tag', '<' * P('/')^-1 + P('/')^-1 * '>') -- Equals. local equals = token(l.OPERATOR, '=') --* in_tag -- Entities. local entity = token('entity', '&' * (l.any - l.space - ';')^1 * ';') -- Doctype. local doctype = token('doctype', '<!' * word_match({'doctype'}, nil, case_insensitive_tags) * (l.any - '>')^1 * '>') M._rules = { {'whitespace', ws}, {'comment', comment}, {'doctype', doctype}, {'tag', tag}, {'element', element}, {'attribute', attribute}, -- {'equals', equals}, {'string', string}, {'number', number}, {'entity', entity}, } M._tokenstyles = { tag = l.STYLE_KEYWORD, element = l.STYLE_KEYWORD, unknown_element = l.STYLE_KEYWORD..',italics', attribute = l.STYLE_VARIABLE, unknown_attribute = l.STYLE_TYPE..',italics', entity = l.STYLE_OPERATOR, doctype = l.STYLE_COMMENT } -- Tags that start embedded languages. M.embed_start_tag = tag * element * ws^1 * attribute * ws^0 * equals * ws^0 * string * ws^0 * tag M.embed_end_tag = tag * element * tag -- Embedded CSS. local css = l.load('css') local style_element = word_match({'style'}, nil, case_insensitive_tags) local css_start_rule = #(P('<') * style_element * ('>' + P(function(input, index) if input:find('^%s+type%s*=%s*(["\'])text/css%1', index) then return index end end))) * M.embed_start_tag -- <style type="text/css"> local css_end_rule = #('</' * style_element * ws^0 * '>') * M.embed_end_tag -- </style> l.embed_lexer(M, css, css_start_rule, css_end_rule) -- Embedded Javascript. local js = l.load('javascript') local script_element = word_match({'script'}, nil, case_insensitive_tags) local js_start_rule = #(P('<') * script_element * ('>' + P(function(input, index) if input:find('^%s+type%s*=%s*(["\'])text/javascript%1', index) then return index end end))) * M.embed_start_tag -- <script type="text/javascript"> local js_end_rule = #('</' * script_element * ws^0 * '>') * M.embed_end_tag -- </script> l.embed_lexer(M, js, js_start_rule, js_end_rule) -- Embedded CoffeeScript. local cs = l.load('coffeescript') local script_element = word_match({'script'}, nil, case_insensitive_tags) local cs_start_rule = #(P('<') * script_element * P(function(input, index) if input:find('^[^>]+type%s*=%s*(["\'])text/coffeescript%1', index) then return index end end)) * M.embed_start_tag -- <script type="text/coffeescript"> local cs_end_rule = #('</' * script_element * ws^0 * '>') * M.embed_end_tag -- </script> l.embed_lexer(M, cs, cs_start_rule, cs_end_rule) M._foldsymbols = { _patterns = {'</?', '/>', '<!%-%-', '%-%->'}, tag = {['<'] = 1, ['/>'] = -1, ['</'] = -1}, [l.COMMENT] = {['<!--'] = 1, ['-->'] = -1} } return M
Fixed slowdown with large HTML files; lexers/hypertext.lua The tradeoff is that plain text like "2 + 2 = 4" highlights improperly.
Fixed slowdown with large HTML files; lexers/hypertext.lua The tradeoff is that plain text like "2 + 2 = 4" highlights improperly.
Lua
mit
rgieseke/scintillua
15f69ce26d8bb8f1675d28dda1a89ac2dd4ae806
lua/include/utils.lua
lua/include/utils.lua
local bor, band, bnot, rshift, lshift, bswap = bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift, bit.bswap function printf(str, ...) return print(str:format(...)) end function errorf(str, ...) error(str:format(...), 2) end function mapVarArg(f, ...) local l = { ... } for i, v in ipairs(l) do l[i] = f(v) end return unpack(l) end function map(f, t) for i, v in ipairs(t) do t[i] = f(v) end return t end function tostringall(...) return mapVarArg(tostring, ...) end function tonumberall(...) return mapVarArg(tonumber, ...) end function bswap16(n) return bor(rshift(n, 8), lshift(band(n, 0xFF), 8)) end hton16 = bswap16 ntoh16 = hton16 _G.bswap = bswap -- export bit.bswap to global namespace to be consistent with bswap16 hton = bswap ntoh = hton local ffi = require "ffi" ffi.cdef [[ struct timeval { long tv_sec; long tv_usec; }; int gettimeofday(struct timeval* tv, void* tz); ]] do local tv = ffi.new("struct timeval") function time() ffi.C.gettimeofday(tv, nil) return tonumber(tv.tv_sec) + tonumber(tv.tv_usec) / 10^6 end end function checksum(data, len) data = ffi.cast("uint16_t*", data) local cs = 0 for i = 0, len / 2 - 1 do cs = cs + data[i] if cs >= 2^16 then cs = band(cs, 0xFFFF) + 1 end end return band(bnot(cs), 0xFFFF) end --- Parse a string to a MAC address -- @param mac address in string format -- @return address in mac_address format or nil if invalid address function parseMACAddress(mac) local bytes = {} bytes = {string.match(mac, '(%d+)[-:](%d+)[-:](%d+)[-:](%d+)[-:](%d+)[-:](%d+)')} if bytes == nil then return end for i = 1, 6 do if bytes[i] == nil then return end bytes[i] = tonumber(bytes[i], 16) if bytes[i] < 0 or bytes[i] > 0xFF then return end end addr = ffi.new("struct mac_address") for i = 0, 5 do addr.uint8[i] = bytes[i] end return addr end --- Parse a string to an IP address -- @return ip address in ipv4_address or ipv6_address format or nil if invalid address function parseIPAddress(ip) local address = parseIP4Address(ip) if address == nil then address = parseIP6Address(ip) end return address end --- Parse a string to an IPv4 address -- @param ip address in string format -- @return address in ipv4_address format or nil if invalid address function parseIP4Address(ip) local bytes = {} bytes = {string.match(ip, '(%d+)%.(%d+)%.(%d+)%.(%d+)')} if bytes == nil then return end for i = 1, 4 do if bytes[i] == nil then return end bytes[i] = tonumber(bytes[i]) if bytes[i] < 0 or bytes[i] > 255 then return end end -- build a uint32 ip = bytes[1] for i = 2, 4 do ip = bor(lshift(ip, 8), bytes[i]) end return ip end ffi.cdef[[ int inet_pton(int af, const char *src, void *dst); ]] --- Parse a string to an IPv6 address -- @param ip address in string format -- @return address in ipv6_address format or nil if invalid address function parseIP6Address(ip) local LINUX_AF_INET6 = 10 --preprocessor constant of Linux local tmp_addr = ffi.new("union ipv6_address") ffi.C.inet_pton(LINUX_AF_INET6, ip, tmp_addr) local addr = ffi.new("union ipv6_address") addr.uint32[0] = bswap(tmp_addr.uint32[3]) addr.uint32[1] = bswap(tmp_addr.uint32[2]) addr.uint32[2] = bswap(tmp_addr.uint32[1]) addr.uint32[3] = bswap(tmp_addr.uint32[0]) return addr end
local bor, band, bnot, rshift, lshift, bswap = bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift, bit.bswap function printf(str, ...) return print(str:format(...)) end function errorf(str, ...) error(str:format(...), 2) end function mapVarArg(f, ...) local l = { ... } for i, v in ipairs(l) do l[i] = f(v) end return unpack(l) end function map(f, t) for i, v in ipairs(t) do t[i] = f(v) end return t end function tostringall(...) return mapVarArg(tostring, ...) end function tonumberall(...) return mapVarArg(tonumber, ...) end function bswap16(n) return bor(rshift(n, 8), lshift(band(n, 0xFF), 8)) end hton16 = bswap16 ntoh16 = hton16 _G.bswap = bswap -- export bit.bswap to global namespace to be consistent with bswap16 hton = bswap ntoh = hton local ffi = require "ffi" ffi.cdef [[ struct timeval { long tv_sec; long tv_usec; }; int gettimeofday(struct timeval* tv, void* tz); ]] do local tv = ffi.new("struct timeval") function time() ffi.C.gettimeofday(tv, nil) return tonumber(tv.tv_sec) + tonumber(tv.tv_usec) / 10^6 end end function checksum(data, len) data = ffi.cast("uint16_t*", data) local cs = 0 for i = 0, len / 2 - 1 do cs = cs + data[i] if cs >= 2^16 then cs = band(cs, 0xFFFF) + 1 end end return band(bnot(cs), 0xFFFF) end --- Parse a string to a MAC address -- @param mac address in string format -- @return address in mac_address format or nil if invalid address function parseMACAddress(mac) local bytes = {string.match(mac, '(%x+)[-:](%x+)[-:](%x+)[-:](%x+)[-:](%x+)[-:](%x+)')} if bytes == nil then return end for i = 1, 6 do if bytes[i] == nil then return end bytes[i] = tonumber(bytes[i], 16) if bytes[i] < 0 or bytes[i] > 0xFF then return end end addr = ffi.new("struct mac_address") for i = 0, 5 do addr.uint8[i] = bytes[i + 1] end return addr end --- Parse a string to an IP address -- @return ip address in ipv4_address or ipv6_address format or nil if invalid address function parseIPAddress(ip) local address = parseIP4Address(ip) if address == nil then address = parseIP6Address(ip) end return address end --- Parse a string to an IPv4 address -- @param ip address in string format -- @return address in ipv4_address format or nil if invalid address function parseIP4Address(ip) local bytes = {string.match(ip, '(%d+)%.(%d+)%.(%d+)%.(%d+)')} if bytes == nil then return end for i = 1, 4 do if bytes[i] == nil then return end bytes[i] = tonumber(bytes[i]) if bytes[i] < 0 or bytes[i] > 255 then return end end -- build a uint32 ip = bytes[1] for i = 2, 4 do ip = bor(lshift(ip, 8), bytes[i]) end return ip end ffi.cdef[[ int inet_pton(int af, const char *src, void *dst); ]] --- Parse a string to an IPv6 address -- @param ip address in string format -- @return address in ipv6_address format or nil if invalid address function parseIP6Address(ip) local LINUX_AF_INET6 = 10 --preprocessor constant of Linux local tmp_addr = ffi.new("union ipv6_address") ffi.C.inet_pton(LINUX_AF_INET6, ip, tmp_addr) local addr = ffi.new("union ipv6_address") addr.uint32[0] = bswap(tmp_addr.uint32[3]) addr.uint32[1] = bswap(tmp_addr.uint32[2]) addr.uint32[2] = bswap(tmp_addr.uint32[1]) addr.uint32[3] = bswap(tmp_addr.uint32[0]) return addr end
mac parser hotfix
mac parser hotfix
Lua
mit
kidaa/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,atheurer/MoonGen,scholzd/MoonGen,bmichalo/MoonGen,werpat/MoonGen,atheurer/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,dschoeffm/MoonGen,duk3luk3/MoonGen,wenhuizhang/MoonGen,emmericp/MoonGen,scholzd/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,werpat/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,pavel-odintsov/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,werpat/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,wenhuizhang/MoonGen,emmericp/MoonGen,slyon/MoonGen,gallenmu/MoonGen,slyon/MoonGen,pavel-odintsov/MoonGen,schoenb/MoonGen,schoenb/MoonGen,dschoeffm/MoonGen,pavel-odintsov/MoonGen,NetronomeMoongen/MoonGen,NetronomeMoongen/MoonGen,slyon/MoonGen,gallenmu/MoonGen,schoenb/MoonGen
65913f05c2b0bdf3ee6a4c0b9c969332ca1d8905
lib/resty/consul.lua
lib/resty/consul.lua
local pcall = pcall local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local tbl_insert = table.insert local ngx = ngx local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do tbl_insert(params, k.."="..v) end uri = uri.."?"..tbl_concat(params, "&") end return uri end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 * 1000 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end httpc:set_timeout(timeout) else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
local pcall = pcall local tostring = tostring local cjson = require('cjson') local json_decode = cjson.decode local json_encode = cjson.encode local tbl_concat = table.concat local tbl_insert = table.insert local ngx = ngx local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local http = require('resty.http') local _M = { _VERSION = '0.01', } local API_VERSION = "v1" local DEFAULT_HOST = "127.0.0.1" local DEFAULT_PORT = 8500 local DEFAULT_TIMEOUT = 60*1000 -- 60s efault timeout local mt = { __index = _M } function _M.new(_, opts) local self = { host = opts.host or DEFAULT_HOST, port = opts.port or DEFAULT_PORT, connect_timeout = opts.connect_timeout or DEFAULT_TIMEOUT, read_timeout = opts.read_timeout or DEFAULT_TIMEOUT } return setmetatable(self, mt) end function _M.get_client_body_reader(self, ...) return http:get_client_body_reader(...) end local function safe_json_decode(json_str) local ok, json = pcall(json_decode, json_str) if ok then return json else ngx_log(ngx_ERR, json) end end local function build_uri(key, opts) local uri = "/"..API_VERSION..key if opts then local params = {} for k,v in pairs(opts) do tbl_insert(params, k.."="..tostring(v)) end uri = uri.."?"..tbl_concat(params, "&") end return uri end local function connect(self) local httpc = http.new() local connect_timeout = self.connect_timeout if connect_timeout then httpc:set_timeout(connect_timeout) end local ok, err = httpc:connect(self.host, self.port) if not ok then return nil, err end return httpc end local function _get(httpc, key, opts) local uri = build_uri(key, opts) local res, err = httpc:request({path = uri}) if not res then return nil, err end local status = res.status if not status then return nil, "No status from consul" elseif status ~= 200 then if status == 404 then return nil, "Key not found" else return nil, "Consul returned: HTTP "..status end end local body, err = res:read_body() if not body then return nil, err end local response = safe_json_decode(body) local headers = res.headers return response, headers["X-Consul-Lastcontact"], headers["X-Consul-Knownleader"] end function _M.get(self, key, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if opts and (opts.wait or opts.index) then -- Blocking request, increase timeout local timeout = 10 * 60 * 1000 -- Default timeout is 10m if opts.wait then timeout = opts.wait * 1000 end httpc:set_timeout(timeout) else httpc:set_timeout(self.read_timeout) end local res, lastcontact_or_err, knownleader = _get(httpc, key, opts) httpc:set_keepalive() if not res then return nil, lastcontact_or_err end return res, {lastcontact_or_err, knownleader} end function _M.get_decoded(self, key, opts) local res, err = self:get(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do if type(entry.Value) == "string" then local decoded = ngx.decode_base64(entry.Value) if decoded ~= nil then entry.Value = decoded end end end return res, err end function _M.get_json_decoded(self, key, opts) local res, err = self:get_decoded(key, opts) if not res then return nil, err end for _,entry in ipairs(res) do local decoded = safe_json_decode(entry.Value) if decoded ~= nil then entry.Value = decoded end end return res, err end function _M.put(self, key, value, opts) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end local uri = build_uri(key, opts) local res, err = httpc:request({ method = "PUT", path = uri, body = value }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() return (body == "true\n") end function _M.delete(self, key, recurse) local httpc, err = connect(self) if not httpc then ngx_log(ngx_ERR, err) return nil, err end if recurse then recurse = {recurse = true} end local uri = build_uri(key, recurse) local res, err = httpc:request({ method = "DELETE", path = uri, }) if not res then return nil, err end if not res.status then return nil, "No status from consul" end local body, err = res:read_body() if not body then return nil, err end httpc:set_keepalive() if res.status == 200 then return true end -- DELETE seems to return 200 regardless, but just in case return {status = res.status, body = body, headers = res.headers}, err end return _M
Fix boolean query string params
Fix boolean query string params
Lua
mit
hamishforbes/lua-resty-consul
a94cf1e757c7f6e89da550a15102bab85244db9c
genie.lua
genie.lua
solution "lip" location(_ACTION) configurations {"ReleaseLib", "DebugLib", "ReleaseDLL", "DebugDLL"} platforms {"x64"} debugdir "." flags { "StaticRuntime", "Symbols", "NoEditAndContinue", "NoNativeWChar" } defines { "_CRT_SECURE_NO_WARNINGS" } configuration "Release*" flags { "OptimizeSpeed" } configuration "*DLL" defines { "LIP_DYNAMIC=1" } configuration "ReleaseLib" targetdir "bin/ReleaseLib" configuration "ReleaseDLL" targetdir "bin/ReleaseDLL" configuration "DebugLib" targetdir "bin/DebugLib" configuration "DebugDLL" targetdir "bin/DebugDLL" configuration "vs*" buildoptions { "/wd4116", -- Anonymous struct in parentheses "/wd4200", -- Flexible array member "/wd4204", -- Non-constant aggregate initializer } configuration {} project "repl" kind "ConsoleApp" language "C" files { "src/repl/*.h", "src/repl/*.c" } includedirs { "include", "deps/linenoise-ng/include", "deps/cargo" } links { "lip", "cargo", "linenoise-ng" } project "tests" kind "ConsoleApp" language "C++" includedirs { "include", "src" } files { "src/tests/*.h", "src/tests/*.c", "src/tests/*.cpp" } links { "lip" } project "lip" configuration { "*Lib" } kind "StaticLib" configuration { "*DLL" } kind "SharedLib" configuration {} language "C" defines { "LIP_BUILDING=1" } includedirs { "include" } files { "include/lip/*.h", "src/lip/**" } project "linenoise-ng" kind "StaticLib" language "C++" flags { "MinimumWarnings" } includedirs { "deps/linenoise-ng/include", } files { "deps/linenoise-ng/include/*.h", "deps/linenoise-ng/src/*.cpp" } project "cargo" kind "StaticLib" language "C" flags { "MinimumWarnings" } files { "deps/cargo/*.h", "deps/cargo/*.c" }
solution "lip" location(_ACTION) configurations {"ReleaseLib", "DebugLib", "ReleaseDLL", "DebugDLL"} platforms {"x64"} debugdir "." flags { "StaticRuntime", "Symbols", "NoEditAndContinue", "NoNativeWChar" } defines { "_CRT_SECURE_NO_WARNINGS" } configuration "Release*" flags { "OptimizeSpeed" } configuration "*DLL" defines { "LIP_DYNAMIC=1" } configuration "ReleaseLib" targetdir "bin/ReleaseLib" configuration "ReleaseDLL" targetdir "bin/ReleaseDLL" configuration "DebugLib" targetdir "bin/DebugLib" configuration "DebugDLL" targetdir "bin/DebugDLL" configuration "vs*" buildoptions { "/wd4116", -- Anonymous struct in parentheses "/wd4200", -- Flexible array member "/wd4204", -- Non-constant aggregate initializer } configuration {} project "repl" kind "ConsoleApp" language "C" files { "src/repl/*.h", "src/repl/*.c" } includedirs { "include", "deps/linenoise", "deps/cargo" } links { "lip", "cargo", "linenoise" } project "tests" kind "ConsoleApp" language "C++" includedirs { "include", "src" } files { "src/tests/*.h", "src/tests/*.c", "src/tests/*.cpp" } links { "lip" } project "lip" configuration { "*Lib" } kind "StaticLib" configuration { "*DLL" } kind "SharedLib" configuration {} language "C" defines { "LIP_BUILDING=1" } includedirs { "include" } files { "include/lip/*.h", "src/lip/**" } project "linenoise" kind "StaticLib" language "C" flags { "MinimumWarnings" } includedirs { "deps/linenoise", } files { "deps/linenoise/*.h", "deps/linenoise/*.c" } excludes { "deps/linenoise/example.c" } project "cargo" kind "StaticLib" language "C" flags { "MinimumWarnings" } files { "deps/cargo/*.h", "deps/cargo/*.c" }
Fix Windows build
Fix Windows build
Lua
bsd-2-clause
bullno1/lip,bullno1/lip,bullno1/lip,bullno1/lip,bullno1/lip,bullno1/lip
083ce74e73bc13923fd0a92133eedd554c8e2e56
agents/monitoring/default/client/connection_messages.lua
agents/monitoring/default/client/connection_messages.lua
local bind = require('utils').bind local timer = require('timer') local Emitter = require('core').Emitter local Object = require('core').Object local misc = require('../util/misc') local logging = require('logging') local loggingUtil = require ('../util/logging') local path = require('path') local util = require('../util/misc') local consts = require('../util/constants') local certs = require('../certs') local table = require('table') local os = require('os') local https = require('https') local fs = require('fs') local async = require('async') local fmt = require('string').format local fsutil = require('../util/fs') local crypto = require('_crypto') local errors = require('../errors') local instanceof = require('core').instanceof local request = require('../protocol/request') -- Connection Messages local ConnectionMessages = Emitter:extend() function ConnectionMessages:initialize(connectionStream) self._connectionStream = connectionStream self:on('handshake_success', bind(ConnectionMessages.onHandshake, self)) self:on('client_end', bind(ConnectionMessages.onClientEnd, self)) self:on('message', bind(ConnectionMessages.onMessage, self)) self._lastFetchTime = 0 end function ConnectionMessages:getStream() return self._connectionStream end function ConnectionMessages:onClientEnd(client) client:log(logging.INFO, 'Detected client disconnect') end function ConnectionMessages:onHandshake(client, data) -- Only retrieve manifest if agent is bound to an entity if data.entity_id then self:fetchManifest(client) else client:log(logging.DEBUG, 'Not retrieving check manifest, because ' .. 'agent is not bound to an entity') end end function ConnectionMessages:fetchManifest(client) function run() if client then client:log(logging.DEBUG, 'Retrieving check manifest...') client.protocol:request('check_schedule.get', function(err, resp) if err then -- TODO Abort connection? client:log(logging.ERROR, 'Error while retrieving manifest: ' .. err.message) else client:scheduleManifest(resp.result) end end) end end if self._lastFetchTime == 0 then if self._timer then timer.clearTimer(self._timer) end self._timer = process.nextTick(run) self._lastFetchTime = os.time() end end function ConnectionMessages:verify(path, sig_path, kpub_path, callback) local parallel = { hash = function(callback) local hash = crypto.verify.new('sha256') local stream = fs.createReadStream(path) stream:on('data', function(d) hash:update(d) end) stream:on('end', function() callback(nil, hash) end) stream:on('error', callback) end, sig = function(callback) fs.readFile(sig_path, callback) end, pub_data = function(callback) fs.readFile(kpub_path, callback) end } async.parallel(parallel, function(err, res) if err then return callback(err) end local hash = res.hash[1] local sig = res.sig[1] local pub_data = res.pub_data[1] local key = crypto.pkey.from_pem(pub_data) if not key then return callback(errors.InvalidSignatureError:new('invalid key file')) end if not hash:final(sig, key) then return callback(errors.InvalidSignatureError:new('invalid sig on file: '.. path)) end callback() end) end function ConnectionMessages:getUpgrade(version, client) local channel = self._connectionStream:getChannel() local unverified_dir = path.join(consts.DEFAULT_DOWNLOAD_PATH, 'unverified') local function download_iter(item, callback) local options = { method = 'GET', host = client._host, port = client._port, tls = client._tls_options, } local filename = path.join(unverified_dir, item.payload) local filename_sig = path.join(unverified_dir, item.signature) local filename_verified = path.join(item.path, item.payload) local filename_verified_sig = path.join(item.path, item.signature) async.parallel({ payload = function(callback) local opts = misc.merge({ path = fmt('/upgrades/%s/%s', channel, item.payload), download = path.join(unverified_dir, item.payload) }, options) request.makeRequest(opts, callback) end, signature = function(callback) local opts = misc.merge({ path = fmt('/upgrades/%s/%s', channel, item.signature), download = path.join(unverified_dir, item.signature) }, options) request.makeRequest(opts, callback) end }, function(err) if err then return callback(err) end self:verify(filename, filename_sig, certs.codeCert, function(err) if err then return callback(err) end async.parallel({ function(callback) fs.rename(filename, filename_verified, callback) end, function(callback) fs.rename(filename_sig, filename_verified_sig, callback) end }, callback) end) end) end async.waterfall({ function(callback) fsutil.mkdirp(unverified_dir, "0755", function(err) if not err then return callback() end if err.code == "EEXIST" then return callback() end callback(err) end) end, function(callback) local bundle_files = { [1] = { payload = fmt('monitoring-%s.zip', version), signature = fmt('monitoring-%s.zip.sig', version), path = virgo_paths.get(virgo_paths.VIRGO_PATH_BUNDLE_DIR) } } async.forEach(bundle_files, download_iter, callback) end }, function(err) if err then client:log(logging.ERROR, fmt('Error downloading update: %s', tostring(err))) return end local msg = 'An update to the Rackspace Cloud Monitoring Agent has been downloaded' client:log(logging.INFO, msg) end) end function ConnectionMessages:onMessage(client, msg) local method = msg.method if not method then client:log(logging.WARNING, fmt('no method on message!')) return end client:log(logging.DEBUG, fmt('received %s', method)) local callback = function(err, msg) if (err) then client:log(logging.INFO, fmt('error handling %s %s', method, err)) return end if method == 'check_schedule.changed' then self._lastFetchTime = 0 client:log(logging.DEBUG, 'fetching manifest') self:fetchManifest(client) return end if method == 'binary_upgrade.available' then return self:getUpgrade('binary', client) elseif method == 'bundle_upgrade.available' then return self:getUpgrade('bundle', client) end client:log(logging.DEBUG, fmt('No handler for method: %s', method)) end client.protocol:respond(method, msg, callback) end local exports = {} exports.ConnectionMessages = ConnectionMessages return exports
local bind = require('utils').bind local timer = require('timer') local Emitter = require('core').Emitter local Object = require('core').Object local misc = require('../util/misc') local logging = require('logging') local loggingUtil = require ('../util/logging') local path = require('path') local util = require('../util/misc') local consts = require('../util/constants') local certs = require('../certs') local table = require('table') local os = require('os') local https = require('https') local fs = require('fs') local async = require('async') local fmt = require('string').format local fsutil = require('../util/fs') local crypto = require('_crypto') local errors = require('../errors') local instanceof = require('core').instanceof local request = require('../protocol/request') -- Connection Messages local ConnectionMessages = Emitter:extend() function ConnectionMessages:initialize(connectionStream) self._connectionStream = connectionStream self:on('handshake_success', bind(ConnectionMessages.onHandshake, self)) self:on('client_end', bind(ConnectionMessages.onClientEnd, self)) self:on('message', bind(ConnectionMessages.onMessage, self)) self._lastFetchTime = 0 end function ConnectionMessages:getStream() return self._connectionStream end function ConnectionMessages:onClientEnd(client) client:log(logging.INFO, 'Detected client disconnect') end function ConnectionMessages:onHandshake(client, data) -- Only retrieve manifest if agent is bound to an entity if data.entity_id then self:fetchManifest(client) else client:log(logging.DEBUG, 'Not retrieving check manifest, because ' .. 'agent is not bound to an entity') end end function ConnectionMessages:fetchManifest(client) function run() if client then client:log(logging.DEBUG, 'Retrieving check manifest...') client.protocol:request('check_schedule.get', function(err, resp) if err then -- TODO Abort connection? client:log(logging.ERROR, 'Error while retrieving manifest: ' .. err.message) else client:scheduleManifest(resp.result) end end) end end if self._lastFetchTime == 0 then if self._timer then timer.clearTimer(self._timer) end self._timer = process.nextTick(run) self._lastFetchTime = os.time() end end function ConnectionMessages:verify(path, sig_path, kpub_data, callback) local parallel = { hash = function(callback) local hash = crypto.verify.new('sha256') local stream = fs.createReadStream(path) stream:on('data', function(d) hash:update(d) end) stream:on('end', function() callback(nil, hash) end) stream:on('error', callback) end, sig = function(callback) fs.readFile(sig_path, callback) end } async.parallel(parallel, function(err, res) if err then return callback(err) end local hash = res.hash[1] local sig = res.sig[1] local pub_data = kpub_data local key = crypto.pkey.from_pem(pub_data) if not key then return callback(errors.InvalidSignatureError:new('invalid key file')) end if not hash:final(sig, key) then return callback(errors.InvalidSignatureError:new('invalid sig on file: '.. path)) end callback() end) end function ConnectionMessages:getUpgrade(version, client) local channel = self._connectionStream:getChannel() local unverified_dir = path.join(consts.DEFAULT_DOWNLOAD_PATH, 'unverified') local function download_iter(item, callback) local options = { method = 'GET', host = client._host, port = client._port, tls = client._tls_options, } local filename = path.join(unverified_dir, item.payload) local filename_sig = path.join(unverified_dir, item.signature) local filename_verified = path.join(item.path, item.payload) local filename_verified_sig = path.join(item.path, item.signature) async.parallel({ payload = function(callback) local opts = misc.merge({ path = fmt('/upgrades/%s/%s', channel, item.payload), download = path.join(unverified_dir, item.payload) }, options) request.makeRequest(opts, callback) end, signature = function(callback) local opts = misc.merge({ path = fmt('/upgrades/%s/%s', channel, item.signature), download = path.join(unverified_dir, item.signature) }, options) request.makeRequest(opts, callback) end }, function(err) if err then return callback(err) end self:verify(filename, filename_sig, certs.codeCert, function(err) if err then return callback(err) end async.parallel({ function(callback) fs.rename(filename, filename_verified, callback) end, function(callback) fs.rename(filename_sig, filename_verified_sig, callback) end }, callback) end) end) end async.waterfall({ function(callback) fsutil.mkdirp(unverified_dir, "0755", function(err) if not err then return callback() end if err.code == "EEXIST" then return callback() end callback(err) end) end, function(callback) local bundle_files = { [1] = { payload = fmt('monitoring-%s.zip', version), signature = fmt('monitoring-%s.zip.sig', version), path = virgo_paths.get(virgo_paths.VIRGO_PATH_BUNDLE_DIR) } } async.forEach(bundle_files, download_iter, callback) end }, function(err) if err then client:log(logging.ERROR, fmt('Error downloading update: %s', tostring(err))) return end local msg = 'An update to the Rackspace Cloud Monitoring Agent has been downloaded' client:log(logging.INFO, msg) end) end function ConnectionMessages:onMessage(client, msg) local method = msg.method if not method then client:log(logging.WARNING, fmt('no method on message!')) return end client:log(logging.DEBUG, fmt('received %s', method)) local callback = function(err, msg) if (err) then client:log(logging.INFO, fmt('error handling %s %s', method, err)) return end if method == 'check_schedule.changed' then self._lastFetchTime = 0 client:log(logging.DEBUG, 'fetching manifest') self:fetchManifest(client) return end if method == 'binary_upgrade.available' then return self:getUpgrade('binary', client) elseif method == 'bundle_upgrade.available' then return self:getUpgrade('bundle', client) end client:log(logging.DEBUG, fmt('No handler for method: %s', method)) end client.protocol:respond(method, msg, callback) end local exports = {} exports.ConnectionMessages = ConnectionMessages return exports
fix parallel
fix parallel
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
7354ba885b7619c2b126bf300f075897c3415276
evaluation.lua
evaluation.lua
-- -- Created by IntelliJ IDEA. -- User: bking -- Date: 1/30/17 -- Time: 2:25 AM -- To change this template use File | Settings | File Templates. -- package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path require 'torch' require 'nn' require 'nnx' require 'util' require 'torch-rnn' require 'DynamicView' require 'Sampler' cjson = require 'cjson' torch.setheaptracking(true) -- =========================================== COMMAND LINE OPTIONS ==================================================== local cmd = torch.CmdLine() -- Options cmd:option('-gpu', false) cmd:option('-calculate_losses', false) cmd:option('-generate_samples', false) -- Dataset options cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7') cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7') cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7') cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7") cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7") -- Model options cmd:option('-model', 'newcudamodel.th7') --Output Options cmd:option('-batch_loss_file', '') cmd:option('-num_samples', 10) cmd:option('-max_sample_length', 10) local opt = cmd:parse(arg) -- ================================================ EVALUATION ========================================================= if opt.gpu then require 'cutorch' require 'cunn' end function clean_dataset(dataset, batch_size) new_set = {} for i=1, #dataset do if dataset[i][1]:size(1) == batch_size then new_set[#new_set + 1] = dataset[i] end end return new_set end train_set = clean_dataset(torch.load(opt.train_set), 50) valid_set = clean_dataset(torch.load(opt.valid_set), 50) test_set = clean_dataset(torch.load(opt.test_set), 50) model = torch.load(opt.model) criterion = nn.ClassNLLCriterion() wmap = torch.load(opt.wmap_file) function table_cuda(dataset) for i=1, #dataset do dataset[i][1] = dataset[i][1]:cuda() dataset[i][2] = dataset[i][2]:cuda() end return dataset end -- CUDA everything if GPU if opt.gpu then train_set = table_cuda(train_set) valid_set = table_cuda(valid_set) test_set = table_cuda(test_set) model = model:cuda() criterion = criterion:cuda() end function loss_on_dataset(data_set, criterion) local loss = 0.0 local batch_losses = {} for i=1, #data_set do local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2]) if batch_losses[data_set[i][1]:size(2)] == nil then batch_losses[data_set[i][1]:size(2)] = {l} else local x = batch_losses[data_set[i][1]:size(2)] x[#x + 1] = l end loss = loss + l end loss = loss / #data_set return loss, batch_losses end -- We will build a report as a table which will be converted to json. output = {} -- calculate losses if opt.calculate_losses then print('Calculating Training Loss...') local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion) output['train_loss'] = tr_set_loss output['train_batch_loss'] = tr_batch_loss print('Calculating Validation Loss...') local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion) output['valid_loss'] = vd_set_loss output['valid_batch_loss'] = vd_batch_loss print('Calculating Test Loss...') local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion) output['test_loss'] = ts_set_loss output['test_batch_loss'] = ts_batch_loss end sampler = opt.gpu and nn.Sampler():cuda() or nn.Sampler() function sample(model, sequence, max_samples) if max_samples == nil then max_samples = 1 end local addition = opt.gpu and torch.zeros(sequence:size(1)):cuda() or torch.zeros(sequence:size(1)) local output = torch.cat(sequence, addition , 2) local y = model:forward(sequence:repeatTensor(50, 1)) local sampled = sampler:forward(y:reshape(50, y:size(1) / 50, y:size(2))[1]) for i=1, output:size(1) do output[i][output:size(2)] = sampled[output:size(2) - 1] end if max_samples == 1 or wmap[output[i][output:size(2)]] == '</S>' then return output else return sample(output, max_samples - 1) end end function sequence_to_string(seq) local str = '' if seq:dim() == 2 then seq = seq[1] end for i=1, seq:size()[1] do local next_word = wmap[seq[i]] == nil and '<UNK>' or wmap[seq[i]] str = str..' '..next_word end return str end function generate_samples(data_set, num_samples) local results = {} for i = 1, num_samples do local t_set_idx = (torch.random() % #data_set) + 1 local example = data_set[t_set_idx][1] local label = data_set[t_set_idx][2] local example_no = torch.random() % example:size(1) local cut_length = (torch.random() % example:size(2)) + 1 local x = opt.gpu and torch.CudaTensor(1, cut_length) or torch.IntTensor(1, cut_length) for i=1, cut_length do x[1][i] = example[example_no][i] end local result = {} result['generated'] = sequence_to_string(sample(model, x)) result['gold'] = label:reshape(example:size())[example_no] result['supplied_length'] = cut_length results[#results + 1] = result end return results end -- generate some samples if opt.generate_samples then end
-- -- Created by IntelliJ IDEA. -- User: bking -- Date: 1/30/17 -- Time: 2:25 AM -- To change this template use File | Settings | File Templates. -- package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path require 'torch' require 'nn' require 'nnx' require 'util' require 'torch-rnn' require 'DynamicView' require 'Sampler' cjson = require 'cjson' torch.setheaptracking(true) -- =========================================== COMMAND LINE OPTIONS ==================================================== local cmd = torch.CmdLine() -- Options cmd:option('-gpu', false) cmd:option('-calculate_losses', false) cmd:option('-generate_samples', false) -- Dataset options cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7') cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7') cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7') cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7") cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7") -- Model options cmd:option('-model', 'newcudamodel.th7') --Output Options cmd:option('-batch_loss_file', '') cmd:option('-num_samples', 10) cmd:option('-max_sample_length', 10) local opt = cmd:parse(arg) -- ================================================ EVALUATION ========================================================= if opt.gpu then require 'cutorch' require 'cunn' end function clean_dataset(dataset, batch_size) new_set = {} for i=1, #dataset do if dataset[i][1]:size(1) == batch_size then new_set[#new_set + 1] = dataset[i] end end return new_set end train_set = clean_dataset(torch.load(opt.train_set), 50) valid_set = clean_dataset(torch.load(opt.valid_set), 50) test_set = clean_dataset(torch.load(opt.test_set), 50) model = torch.load(opt.model) criterion = nn.ClassNLLCriterion() wmap = torch.load(opt.wmap_file) function table_cuda(dataset) for i=1, #dataset do dataset[i][1] = dataset[i][1]:cuda() dataset[i][2] = dataset[i][2]:cuda() end return dataset end -- CUDA everything if GPU if opt.gpu then train_set = table_cuda(train_set) valid_set = table_cuda(valid_set) test_set = table_cuda(test_set) model = model:cuda() criterion = criterion:cuda() end function loss_on_dataset(data_set, criterion) local loss = 0.0 local batch_losses = {} for i=1, #data_set do local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2]) if batch_losses[data_set[i][1]:size(2)] == nil then batch_losses[data_set[i][1]:size(2)] = {l} else local x = batch_losses[data_set[i][1]:size(2)] x[#x + 1] = l end loss = loss + l end loss = loss / #data_set return loss, batch_losses end -- We will build a report as a table which will be converted to json. output = {} -- calculate losses if opt.calculate_losses then print('Calculating Training Loss...') local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion) output['train_loss'] = tr_set_loss output['train_batch_loss'] = tr_batch_loss print('Calculating Validation Loss...') local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion) output['valid_loss'] = vd_set_loss output['valid_batch_loss'] = vd_batch_loss print('Calculating Test Loss...') local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion) output['test_loss'] = ts_set_loss output['test_batch_loss'] = ts_batch_loss end sampler = opt.gpu and nn.Sampler():cuda() or nn.Sampler() function sample(model, sequence, max_samples) if max_samples == nil then max_samples = 1 end local addition = opt.gpu and torch.zeros(sequence:size(1)):cuda() or torch.zeros(sequence:size(1)) local output = torch.cat(sequence, addition , 2) local y = model:forward(sequence:repeatTensor(50, 1)) local sampled = sampler:forward(y:reshape(50, y:size(1) / 50, y:size(2))[1]) for i=1, output:size(1) do output[i][output:size(2)] = sampled[output:size(2) - 1] end if max_samples == 1 or wmap[output[i][output:size(2)]] == '</S>' then return output else return sample(output, max_samples - 1) end end function sequence_to_string(seq) local str = '' if seq:dim() == 2 then seq = seq[1] end for i=1, seq:size()[1] do local next_word = wmap[seq[i]] == nil and '<UNK>' or wmap[seq[i]] str = str..' '..next_word end return str end function generate_samples(data_set, num_samples) local results = {} for i = 1, num_samples do local t_set_idx = (torch.random() % #data_set) + 1 local example = data_set[t_set_idx][1] local label = data_set[t_set_idx][2] local example_no = torch.random() % example:size(1) local cut_length = (torch.random() % example:size(2)) + 1 local x = opt.gpu and torch.CudaTensor(1, cut_length) or torch.IntTensor(1, cut_length) for i=1, cut_length do x[1][i] = example[example_no][i] end local result = {} result['generated'] = sequence_to_string(sample(model, x, opt.max_sample_length)) result['gold'] = sequence_to_string(label:reshape(example:size())[example_no]) result['supplied_length'] = cut_length results[#results + 1] = result end return results end -- generate some samples if opt.generate_samples then end
smapling fix
smapling fix
Lua
mit
kingb12/languagemodelRNN,kingb12/languagemodelRNN,kingb12/languagemodelRNN
7f3ba1d91e73b24ba4c5f497e6e51947f58d51ab
main.lua
main.lua
require 'roundrect' math.randomseed(os.time()) varfilter = '$(%w+)%$?' function printf(template, rep) return (template:gsub(varfilter, rep)) end state = {frame = 0, totaltime = 0, current = 'mainmenu'} states = {} officialnames = {a = 'Amania', b = 'Bzadoria', c = 'Cadadonia', d = 'Darzamin', ar = 'Anarchists', br = 'Fighters for the Common Good', cr = 'Eclectic Monkeys', dr = 'Alliance of Oppressed People', dem = 'Deus Ex Machines', player = 'You', sc = 'SpaceCorp'} function registerstate(name) states[name] = {} states[name].keypressed = {} end registerstate'game' registerstate'dead' require "hook" function love.load() require "map" require "graphics" require "ui" require "player" require "ai" require "ships" require "physics" require "mainmenu" require "base" require "mission" require "diplomacy" require "help" require "conv" smallfont = love.graphics.newFont('gemfontone.ttf', 16) largefont = love.graphics.newFont('gemfontone.ttf', 30) mediumfont = love.graphics.newFont('gemfontone.ttf', 22) love.graphics.setFont(largefont) restart() end function restart() map.load() graphics.load() ui.load() ships.load() player.load() ai.load() physics.load() mainmenu.load() base.load() mission.load() help.load() conv.load() diplomacy.load() end function love.update(dt) if state.current == 'game' then if not ui.cmdstring then state.frame = state.frame + 1 state.totaltime = state.totaltime + dt mission.update(dt) map.update(dt) ui.update(dt) player.update(dt) ai.update(dt) ships.update(dt) physics.update(dt) graphics.update(dt) end love.timer.sleep(10) elseif state.current == 'paused' then state.frame = state.frame + 1 love.timer.sleep(20) elseif state.current == 'dead' then love.timer.sleep(50) elseif state.current == 'mainmenu' then mainmenu.update(dt) love.timer.sleep(20) elseif state.current == 'base' then ui.base.update(dt) love.timer.sleep(20) elseif state.current == 'help' then help.update(dt) love.timer.sleep(20) elseif state.current == 'conv' then conv.update(dt) love.timer.sleep(20) elseif state.current:sub(1,7) == 'mission' then mission.updatescreen(dt) love.timer.sleep(20) elseif state.current:sub(1,4) == 'base' then base.update(dt) love.timer.sleep(20) elseif state.current:sub(1,8) == 'mainmenu' then mainmenu[state.current:sub(10)].update(dt) love.timer.sleep(20) end end function love.draw() if state.current == 'game' or state.current == 'paused' then map.draw() graphics.draw() ui.draw() player.draw() ai.draw() ships.draw() physics.draw() elseif state.current == 'help' then help.draw() elseif state.current == 'dead' then love.graphics.print('Nice steering, captain. You\'re dead now.', 100, 100) love.graphics.print('Press R to restart the game.', 100, 130) elseif state.current == 'base' then ui.drawbase() elseif state.current == 'mainmenu' then mainmenu.draw() elseif state.current == 'conv' then conv.draw() elseif state.current:sub(1,7) == 'mission' then mission.drawscreen() elseif state.current:sub(1,4) == 'base' then base.draw() elseif state.current:sub(1,8) == 'mainmenu' then mainmenu[state.current:sub(10)].draw() end end function love.keypressed(key, unicode) if key == 'return' then key = 'enter' end if states[state.current].keypressed[key] then states[state.current].keypressed[key]() elseif states[state.current].keypressed.other then states[state.current].keypressed.other(key, unicode) end end local function error_printer(msg, layer) print((debug.traceback("Error: " .. msg, 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end function love.errhand(msg) error_printer(msg, 2) -- Load. love.graphics.setScissor() love.graphics.setColor(255, 255, 255, 255) local trace = debug.traceback() love.graphics.clear() local err = {msg} for l in string.gmatch(trace, "(.-)\n") do if not string.match(l, "boot.lua") then l = string.gsub(l, "stack traceback:", "Traceback\n") table.insert(err, l) end end local p = table.concat(err, "\n") p = string.gsub(p, "\t", "") p = string.gsub(p, "%[string \"(.-)\"%]", "%1") local wi = love.graphics.getWidth() - 140 address = 'github.com/gvx/space/issues' local wa = love.graphics.getWidth() - largefont:getWidth(address) - 20 local ha = love.graphics.getHeight() - 20 local function draw() love.graphics.clear() love.graphics.setFont(largefont) love.graphics.print('Oops! Something went wrong.', 20, 35) love.graphics.print(address, wa, ha) love.graphics.setFont(mediumfont) if showtrace then love.graphics.printf(p, 70, 120, wi) else love.graphics.printf('An error occurred. It would be great if you want to file a bug report. To do that, please visit github.com/gvx/space/issues. First check if this bug has not been fixed already. If you have no terminal with the traceback of the error, press space. To quit, press escape.', 70, 120, wi) end love.graphics.present() end draw() local e, a, b, c while true do e, a, b, c = love.event.wait() if e == "q" then return end if e == "kp" then if a == "escape" then return elseif a == ' ' then showtrace = not showtrace end end draw() love.timer.sleep(25) end end
require 'roundrect' math.randomseed(os.time()) varfilter = '$(%w+)%$?' function printf(template, rep) return (template:gsub(varfilter, rep)) end state = {frame = 0, totaltime = 0, current = 'mainmenu'} states = {} officialnames = {a = 'Amania', b = 'Bzadoria', c = 'Cadadonia', d = 'Darzamin', ar = 'Anarchists', br = 'Fighters for the Common Good', cr = 'Eclectic Monkeys', dr = 'Alliance of Oppressed People', dem = 'Deus Ex Machines', player = 'You', sc = 'SpaceCorp'} function registerstate(name) states[name] = {} states[name].keypressed = {} end registerstate'game' registerstate'dead' require "hook" function love.load() smallfont = love.graphics.newFont('gemfontone.ttf', 16) largefont = love.graphics.newFont('gemfontone.ttf', 30) mediumfont = love.graphics.newFont('gemfontone.ttf', 22) love.graphics.setFont(largefont) require "map" require "graphics" require "ui" require "player" require "ai" require "ships" require "physics" require "mainmenu" require "base" require "mission" require "diplomacy" require "help" require "conv" restart() end function restart() map.load() graphics.load() ui.load() ships.load() player.load() ai.load() physics.load() mainmenu.load() base.load() mission.load() help.load() conv.load() diplomacy.load() end function love.update(dt) if state.current == 'game' then if not ui.cmdstring then state.frame = state.frame + 1 state.totaltime = state.totaltime + dt mission.update(dt) map.update(dt) ui.update(dt) player.update(dt) ai.update(dt) ships.update(dt) physics.update(dt) graphics.update(dt) end love.timer.sleep(10) elseif state.current == 'paused' then state.frame = state.frame + 1 love.timer.sleep(20) elseif state.current == 'dead' then love.timer.sleep(50) elseif state.current == 'mainmenu' then mainmenu.update(dt) love.timer.sleep(20) elseif state.current == 'base' then ui.base.update(dt) love.timer.sleep(20) elseif state.current == 'help' then help.update(dt) love.timer.sleep(20) elseif state.current == 'conv' then conv.update(dt) love.timer.sleep(20) elseif state.current:sub(1,7) == 'mission' then mission.updatescreen(dt) love.timer.sleep(20) elseif state.current:sub(1,4) == 'base' then base.update(dt) love.timer.sleep(20) elseif state.current:sub(1,8) == 'mainmenu' then mainmenu[state.current:sub(10)].update(dt) love.timer.sleep(20) end end function love.draw() if state.current == 'game' or state.current == 'paused' then map.draw() graphics.draw() ui.draw() player.draw() ai.draw() ships.draw() physics.draw() elseif state.current == 'help' then help.draw() elseif state.current == 'dead' then love.graphics.print('Nice steering, captain. You\'re dead now.', 100, 100) love.graphics.print('Press R to restart the game.', 100, 130) elseif state.current == 'base' then ui.drawbase() elseif state.current == 'mainmenu' then mainmenu.draw() elseif state.current == 'conv' then conv.draw() elseif state.current:sub(1,7) == 'mission' then mission.drawscreen() elseif state.current:sub(1,4) == 'base' then base.draw() elseif state.current:sub(1,8) == 'mainmenu' then mainmenu[state.current:sub(10)].draw() end end function love.keypressed(key, unicode) if key == 'return' then key = 'enter' end if states[state.current].keypressed[key] then states[state.current].keypressed[key]() elseif states[state.current].keypressed.other then states[state.current].keypressed.other(key, unicode) end end local function error_printer(msg, layer) print((debug.traceback("Error: " .. msg, 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end function love.errhand(msg) error_printer(msg, 2) -- Load. love.graphics.setScissor() love.graphics.setColor(255, 255, 255, 255) local trace = debug.traceback() love.graphics.clear() local err = {msg} for l in string.gmatch(trace, "(.-)\n") do if not string.match(l, "boot.lua") then l = string.gsub(l, "stack traceback:", "Traceback\n") table.insert(err, l) end end local p = table.concat(err, "\n") p = string.gsub(p, "\t", "") p = string.gsub(p, "%[string \"(.-)\"%]", "%1") local wi = love.graphics.getWidth() - 140 address = 'github.com/gvx/space/issues' local wa = love.graphics.getWidth() - largefont:getWidth(address) - 20 local ha = love.graphics.getHeight() - 20 local function draw() love.graphics.clear() love.graphics.setFont(largefont) love.graphics.print('Oops! Something went wrong.', 20, 35) love.graphics.print(address, wa, ha) love.graphics.setFont(mediumfont) if showtrace then love.graphics.printf(p, 70, 120, wi) else love.graphics.printf('An error occurred. It would be great if you want to file a bug report. To do that, please visit github.com/gvx/space/issues. First check if this bug has not been fixed already. If you have no terminal with the traceback of the error, press space. To quit, press escape.', 70, 120, wi) end love.graphics.present() end draw() local e, a, b, c while true do e, a, b, c = love.event.wait() if e == "q" then return end if e == "kp" then if a == "escape" then return elseif a == ' ' then showtrace = not showtrace end end draw() love.timer.sleep(25) end end
Fixes nasty error-loop if something goes wrong before fonts are properly initialized
Fixes nasty error-loop if something goes wrong before fonts are properly initialized
Lua
mit
gvx/space,gvx/space
e2025f51af09b3109f612269144e40ea9ee3ad3b
source/pathfinder.lua
source/pathfinder.lua
-- TODO: cleanup and add comments require "source/gridNeighbors" require "source/utilities/vector" local function posToKey(gridWidth, pos) return pos[1] + pos[2] * (gridWidth + 1) end function getPathDestination(grid, pos, path) local gridWidth = grid:getSize() local key = posToKey(gridWidth, vector{grid:locToCoord(pos[1], pos[2])}) local node = path[key] if node then local parent = path[key].parent return parent and vector{grid:getTileLoc(parent.position[1], parent.position[2], MOAIGridSpace.TILE_CENTER)} end end -- Finds the shortest path from from every node on the map to the targetPosition function findPath(grid, targetPosition) local width, height = grid:getSize() local function ValidTile(pos) return pos[1] >= 1 and pos[1] <= width and pos[2] >= 1 and pos[2] <= height and grid:getTile(pos[1], pos[2]) == 6 -- TODO: this should be a parameter to change which tile is a wall end if not ValidTile(targetPosition) then return false end local visited = {} local list = {} table.insert(list, {position = targetPosition, parent = nil}) while #list > 0 do -- Pop the front node from the queue local currentNode = list[1] table.remove(list, 1) local directions = getHexNeighbors(currentNode.position) for i, dir in ipairs(directions) do local newPos = currentNode.position + dir local key = posToKey(width, newPos) if ValidTile(newPos) and not visited[key] then table.insert(list, {position = newPos, parent = currentNode}) visited[key] = list[#list] end end end return visited end
-- TODO: cleanup and add comments require "source/gridNeighbors" require "source/utilities/vector" local function posToKey(gridWidth, pos) return pos[1] + pos[2] * (gridWidth + 1) end function getPathDestination(grid, pos, path) local gridWidth = grid:getSize() local key = posToKey(gridWidth, vector{grid:locToCoord(pos[1], pos[2])}) local node = path[key] if node then local parent = path[key].parent return parent and vector{grid:getTileLoc(parent.position[1], parent.position[2], MOAIGridSpace.TILE_CENTER)} end end -- Finds the shortest path from from every node on the map to the targetPosition function findPath(grid, targetPosition) local width, height = grid:getSize() local function ValidTile(pos) return pos[1] >= 1 and pos[1] <= width and pos[2] >= 1 and pos[2] <= height and grid:getTile(pos[1], pos[2]) == 6 -- TODO: this should be a parameter to change which tile is a wall end if not ValidTile(targetPosition) then return false end local visited = {} local list = {} table.insert(list, {position = targetPosition, parent = nil}) visited[posToKey(width, targetPosition)] = list[1] while #list > 0 do -- Pop the front node from the queue local currentNode = list[1] table.remove(list, 1) local directions = getHexNeighbors(currentNode.position) for i, dir in ipairs(directions) do local newPos = currentNode.position + dir local key = posToKey(width, newPos) if ValidTile(newPos) and not visited[key] then table.insert(list, {position = newPos, parent = currentNode}) visited[key] = list[#list] end end end return visited end
Fixed loop in pathfinder.
Fixed loop in pathfinder.
Lua
mit
BryceMehring/Hexel
5402c612a865fb83c876c5c252e5c1bc6ecd87e0
AceGUI-3.0/widgets/AceGUIWidget-ColorPicker.lua
AceGUI-3.0/widgets/AceGUIWidget-ColorPicker.lua
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- ColorPicker -- -------------------------- do local Type = "ColorPicker" local Version = 8 local function Acquire(self) self.HasAlpha = false self:SetColor(0,0,0,1) end local function SetLabel(self, text) self.text:SetText(text) end local function SetColor(self,r,g,b,a) self.r = r self.g = g self.b = b self.a = a or 1 self.colorSwatch:SetVertexColor(r,g,b,a) end local function Control_OnEnter(this) this.obj:Fire("OnEnter") end local function Control_OnLeave(this) this.obj:Fire("OnLeave") end local function SetHasAlpha(self, HasAlpha) self.HasAlpha = HasAlpha end local function ColorCallback(self,r,g,b,a,isAlpha) if not self.HasAlpha then a = 1 end self:SetColor(r,g,b,a) if ColorPickerFrame:IsVisible() then --colorpicker is still open self:Fire("OnValueChanged",r,g,b,a) else --colorpicker is closed, color callback is first, ignore it, --alpha callback is the final call after it closes so confirm now if isAlpha then self:Fire("OnValueConfirmed",r,g,b,a) end end end local function ColorSwatch_OnClick(this) HideUIPanel(ColorPickerFrame) local self = this.obj if not self.disabled then ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG") ColorPickerFrame.func = function() local r,g,b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self,r,g,b,a) end ColorPickerFrame.hasOpacity = self.HasAlpha ColorPickerFrame.opacityFunc = function() local r,g,b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self,r,g,b,a,true) end local r, g, b, a = self.r, self.g, self.b, self.a if self.HasAlpha then ColorPickerFrame.opacity = 1 - (a or 0) end ColorPickerFrame:SetColorRGB(r, g, b) ColorPickerFrame.cancelFunc = function() ColorCallback(self,r,g,b,a,true) end ShowUIPanel(ColorPickerFrame) end end local function Release(self) self.frame:ClearAllPoints() self.frame:Hide() end local function SetDisabled(self, disabled) self.disabled = disabled if self.disabled then self.text:SetTextColor(0.5,0.5,0.5) else self.text:SetTextColor(1,1,1) end end local function Constructor() local frame = CreateFrame("Button",nil,UIParent) local self = {} self.type = Type self.Release = Release self.Acquire = Acquire self.SetLabel = SetLabel self.SetColor = SetColor self.SetDisabled = SetDisabled self.SetHasAlpha = SetHasAlpha self.frame = frame frame.obj = self local text = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight") self.text = text text:SetJustifyH("LEFT") text:SetTextColor(1,1,1) frame:SetHeight(24) frame:SetWidth(200) text:SetHeight(24) frame:SetScript("OnClick", ColorSwatch_OnClick) frame:SetScript("OnEnter",Control_OnEnter) frame:SetScript("OnLeave",Control_OnLeave) local colorSwatch = frame:CreateTexture(nil, "OVERLAY") self.colorSwatch = colorSwatch colorSwatch:SetWidth(19) colorSwatch:SetHeight(19) colorSwatch:SetTexture("Interface\\ChatFrame\\ChatFrameColorSwatch") local texture = frame:CreateTexture(nil, "BACKGROUND") colorSwatch.texture = texture texture:SetTexture("Tileset\\Generic\\Checkers") texture:SetDesaturated(true) texture:SetVertexColor(1,1,1,0.75) texture:SetTexCoord(.25,0,0.5,.25) texture:SetWidth(16) texture:SetHeight(16) texture:Show() local highlight = frame:CreateTexture(nil, "BACKGROUND") self.highlight = highlight highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") highlight:SetBlendMode("ADD") highlight:SetAllPoints(frame) highlight:Hide() texture:SetPoint("CENTER", colorSwatch, "CENTER") colorSwatch:SetPoint("LEFT", frame, "LEFT", 0, 0) text:SetPoint("LEFT",colorSwatch,"RIGHT",2,0) text:SetPoint("RIGHT",frame,"RIGHT") AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- ColorPicker -- -------------------------- do local Type = "ColorPicker" local Version = 8 local function Acquire(self) self.HasAlpha = false self:SetColor(0,0,0,1) end local function SetLabel(self, text) self.text:SetText(text) end local function SetColor(self,r,g,b,a) self.r = r self.g = g self.b = b self.a = a or 1 self.colorSwatch:SetVertexColor(r,g,b,a) end local function Control_OnEnter(this) this.obj:Fire("OnEnter") end local function Control_OnLeave(this) this.obj:Fire("OnLeave") end local function SetHasAlpha(self, HasAlpha) self.HasAlpha = HasAlpha end local function ColorCallback(self,r,g,b,a,isAlpha) if not self.HasAlpha then a = 1 end self:SetColor(r,g,b,a) if ColorPickerFrame:IsVisible() then --colorpicker is still open self:Fire("OnValueChanged",r,g,b,a) else --colorpicker is closed, color callback is first, ignore it, --alpha callback is the final call after it closes so confirm now if isAlpha then self:Fire("OnValueConfirmed",r,g,b,a) end end end local function ColorSwatch_OnClick(this) HideUIPanel(ColorPickerFrame) local self = this.obj if not self.disabled then ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG") ColorPickerFrame.func = function() local r,g,b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self,r,g,b,a) end ColorPickerFrame.hasOpacity = self.HasAlpha ColorPickerFrame.opacityFunc = function() local r,g,b = ColorPickerFrame:GetColorRGB() local a = 1 - OpacitySliderFrame:GetValue() ColorCallback(self,r,g,b,a,true) end local r, g, b, a = self.r, self.g, self.b, self.a if self.HasAlpha then ColorPickerFrame.opacity = 1 - (a or 0) end ColorPickerFrame:SetColorRGB(r, g, b) ColorPickerFrame.cancelFunc = function() ColorCallback(self,r,g,b,a,true) end ShowUIPanel(ColorPickerFrame) end end local function Release(self) self.frame:ClearAllPoints() self.frame:Hide() end local function SetDisabled(self, disabled) self.disabled = disabled if self.disabled then self.text:SetTextColor(0.5,0.5,0.5) else self.text:SetTextColor(1,1,1) end end local function Constructor() local frame = CreateFrame("Button",nil,UIParent) local self = {} self.type = Type self.Release = Release self.Acquire = Acquire self.SetLabel = SetLabel self.SetColor = SetColor self.SetDisabled = SetDisabled self.SetHasAlpha = SetHasAlpha self.frame = frame frame.obj = self local text = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight") self.text = text text:SetJustifyH("LEFT") text:SetTextColor(1,1,1) frame:SetHeight(24) frame:SetWidth(200) text:SetHeight(24) frame:SetScript("OnClick", ColorSwatch_OnClick) frame:SetScript("OnEnter",Control_OnEnter) frame:SetScript("OnLeave",Control_OnLeave) local colorSwatch = frame:CreateTexture(nil, "OVERLAY") self.colorSwatch = colorSwatch colorSwatch:SetWidth(19) colorSwatch:SetHeight(19) colorSwatch:SetTexture("Interface\\ChatFrame\\ChatFrameColorSwatch") local texture = frame:CreateTexture(nil, "BACKGROUND") colorSwatch.texture = texture texture:SetWidth(16) texture:SetHeight(16) texture:SetTexture(1,1,1) texture:Show() local checkers = frame:CreateTexture(nil, "BACKGROUND") colorSwatch.checkers = checkers checkers:SetTexture("Tileset\\Generic\\Checkers") checkers:SetDesaturated(true) checkers:SetVertexColor(1,1,1,0.75) checkers:SetTexCoord(.25,0,0.5,.25) checkers:SetWidth(14) checkers:SetHeight(14) checkers:Show() local highlight = frame:CreateTexture(nil, "BACKGROUND") self.highlight = highlight highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") highlight:SetBlendMode("ADD") highlight:SetAllPoints(frame) highlight:Hide() texture:SetPoint("CENTER", colorSwatch, "CENTER") checkers:SetPoint("CENTER", colorSwatch, "CENTER") colorSwatch:SetPoint("LEFT", frame, "LEFT", 0, 0) text:SetPoint("LEFT",colorSwatch,"RIGHT",2,0) text:SetPoint("RIGHT",frame,"RIGHT") AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
Ace3 - AceGUI-3.0 - ColorPicker Widget: "fix" checker background overlapping the border
Ace3 - AceGUI-3.0 - ColorPicker Widget: "fix" checker background overlapping the border git-svn-id: 7647537e40c65c0861dc9b5b7a3f92438fa62736@599 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
0b45a4adbe1ee0841eb818db0af11aac274400eb
patt_movingspots.lua
patt_movingspots.lua
local spot_index = 0 local function run(wsbuf, p, spots_count) if not (type(spots_count) == "number" and spots_count > 0) then spots_count = 1 end local spots_distance = wsbuf:size()/spots_count wsbuf:fade(2,ws2812.FADE_OUT) local pos = 0 for nspot = 0, spots_count -1 do pos = spot_index+1+nspot*spots_distance wsbuf:set(pos, 255 ,255, 255) if pos < wsbuf:size() then wsbuf:set(pos+1, 64 ,64, 64) end end spot_index = (spot_index + 1) % spots_distance return 20 + ((200 * (255 - p.speed)) / 255) end return run
local spot_index = 0 local function run(wsbuf, p, spots_count) if not (type(spots_count) == "number" and spots_count > 0) then spots_count = 1 end local spots_distance = wsbuf:size()/spots_count spot_index = (spot_index + 1) % spots_distance wsbuf:fade(2,ws2812.FADE_OUT) local pos = 0 for nspot = 0, spots_count -1 do pos = spot_index+1+nspot*spots_distance wsbuf:set(pos, 255 ,255, 255) if pos < wsbuf:size() then wsbuf:set(pos+1, 64 ,64, 64) end end return 20 + ((200 * (255 - p.speed)) / 255) end return run
bugfix für spot anzahl änderung
bugfix für spot anzahl änderung
Lua
mit
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
2e31e96aa9f6b03a41ffabbe7b8481185f0a5d6e
ninja.lua
ninja.lua
-- -- Name: premake-ninja/ninja.lua -- Purpose: Define the ninja action. -- Author: Dmitry Ivanov -- Created: 2015/07/04 -- Copyright: (c) 2015 Dmitry Ivanov -- local p = premake local tree = p.tree local project = p.project local solution = p.solution local config = p.config local fileconfig = p.fileconfig premake.modules.ninja = {} local ninja = p.modules.ninja function ninja.esc(value) return value -- TODO end -- generate solution that will call ninja for projects function ninja.generateSolution(sln) p.w("# solution build file") p.w("# generated with premake ninja") p.w("") p.w("rule ninja") p.w(" command = ninja -f $in") p.w("") p.w("# build projects") local cfgs = {} local cfg_first = nil for prj in solution.eachproject(sln) do for cfg in project.eachconfig(prj) do if not cfgs[cfg] then cfgs[cfg] = "" end if cfg_first == nil then cfg_first = cfg.name end cfgs[cfg] = cfgs[cfg] .. ninja.outputFilename(cfg) .. " " -- well ninja does not have any way to output implicit dependencies, so let's do it by hand -- TODO add premake prj dependencies local all_files = "" tree.traverse(project.getsourcetree(prj), {onleaf = function(node, depth) all_files = all_files .. node.relpath .. " " end,}, false, 1) p.w("build " .. ninja.outputFilename(cfg) .. ": ninja " .. ninja.projectCfgFilename(cfg) .. " | " .. all_files) end end p.w("") p.w("# targets") for cfg, prjs in pairs(cfgs) do p.w("build " .. cfg.name .. ": phony " .. prjs) end p.w("") p.w("# default target") p.w("default " .. cfg_first) end function ninja.list(value) if #value > 0 then return " " .. table.concat(value, " ") else return "" end end -- generate project + config build file function ninja.generateProjectCfg(cfg) if cfg.toolset == nil then cfg.toolset = "msc" -- TODO why premake doesn't provide default name always ? end local prj = cfg.project local toolset = premake.tools[cfg.toolset] p.w("# project build file") p.w("# generated with premake ninja") p.w("") ---------------------------------------------------- figure out toolset executables local cc = "" local cxx = "" local ar = "" local link = "" if cfg.toolset == "msc" then -- TODO premake doesn't set tools names for msc, do we want to fix it ? cc = "cl" cxx = "cl" ar = "lib" link = "cl" else -- TODO end ---------------------------------------------------- figure out settings local buildopt = ninja.list(cfg.buildoptions) local cflags = ninja.list(toolset.getcflags(cfg)) local cppflags = ninja.list(toolset.getcppflags(cfg)) local cxxflags = ninja.list(toolset.getcxxflags(cfg)) local warnings = ninja.list(toolset.getwarnings(cfg)) local defines = ninja.list(table.join(toolset.getdefines(cfg.defines), toolset.getundefines(cfg.undefines))) local includes = ninja.list(premake.esc(toolset.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs))) local forceincludes = ninja.list(premake.esc(toolset.getforceincludes(cfg))) -- TODO pch local lddeps = ninja.list(premake.esc(config.getlinks(cfg, "siblings", "fullpath"))) local ldflags = ninja.list(table.join(toolset.getLibraryDirectories(cfg), toolset.getldflags(cfg), cfg.linkoptions)) local libs = ninja.list(toolset.getlinks(cfg)) local all_cflags = buildopt .. cflags .. warnings .. defines .. includes .. forceincludes local all_cxxflags = buildopt .. cflags .. cppflags .. cxxflags .. warnings .. defines .. includes .. forceincludes local all_ldflags = buildopt .. lddeps .. ldflags .. libs local obj_dir = project.getrelative(cfg.project, cfg.objdir) ---------------------------------------------------- write rules p.w("# core rules") if cfg.toolset == "msc" then -- TODO /NOLOGO is invalid, we need to use /nologo p.w("rule cc_" .. cfg.name) p.w(" command = " .. cc .. all_cflags .. " /nologo /showIncludes -c $in /Fo$out") p.w(" description = cxx $out") p.w(" deps = msvc") p.w("rule cxx_" .. cfg.name) p.w(" command = " .. cc .. all_cxxflags .. " /nologo /showIncludes -c $in /Fo$out") p.w(" description = cxx $out") p.w(" deps = msvc") p.w("rule ar_" .. cfg.name) p.w(" command = " .. ar .. " $in /nologo -OUT:$out") p.w(" description = ar $out") p.w("rule link_" .. cfg.name) p.w(" command = " .. link .. " $in" .. all_ldflags .. " /nologo /link /out:$out") p.w(" description = link $out") p.w("") else -- TODO end ---------------------------------------------------- build all files p.w("# build files") local intermediateExt = function(cfg, var) if (var == "c") or (var == "cxx") then return iif(cfg.toolset == "msc", ".obj", ".o") elseif var == "res" then -- TODO return ".res" elseif var == "link" then return cfg.targetextension end end local objfiles = {} tree.traverse(project.getsourcetree(prj), { onleaf = function(node, depth) local filecfg = fileconfig.getconfig(node, cfg) if fileconfig.hasCustomBuildRule(filecfg) then -- TODO elseif path.iscppfile(node.abspath) then objfilename = obj_dir .. "/" .. node.objname .. intermediateExt(cfg, "cxx") p.w("build " .. objfilename .. ": cxx_" .. cfg.name .. " " .. node.relpath) objfiles[#objfiles + 1] = objfilename elseif path.isresourcefile(node.abspath) then -- TODO end end, }, false, 1) p.w("") ---------------------------------------------------- build final target if cfg.kind == premake.STATICLIB then p.w("# link static lib") p.w("build " .. ninja.outputFilename(cfg) .. ": ar_" .. cfg.name .. " " .. table.concat(objfiles, " ")) elseif cfg.kind == premake.SHAREDLIB then -- TODO elseif (cfg.kind == premake.CONSOLEAPP) or (cfg.kind == premake.WINDOWEDAPP) then -- TODO windowed app p.w("# link executable") p.w("build " .. ninja.outputFilename(cfg) .. ": link_" .. cfg.name .. " " .. table.concat(objfiles, " ")) else p.error("ninja action doesn't support this kind " .. cfg.kind) end end -- return name of output binary relative to build folder function ninja.outputFilename(cfg) return project.getrelative(cfg.project, cfg.buildtarget.directory) .. "/" .. cfg.buildtarget.name end -- return name of build file for configuration function ninja.projectCfgFilename(cfg) return "build_" .. cfg.project.name .. "_" .. cfg.name .. ".ninja" end -- generate all build files for every project configuration function ninja.generateProject(prj) for cfg in project.eachconfig(prj) do p.generate(cfg, ninja.projectCfgFilename(cfg), ninja.generateProjectCfg) end end include("_preload.lua") return ninja
-- -- Name: premake-ninja/ninja.lua -- Purpose: Define the ninja action. -- Author: Dmitry Ivanov -- Created: 2015/07/04 -- Copyright: (c) 2015 Dmitry Ivanov -- local p = premake local tree = p.tree local project = p.project local solution = p.solution local config = p.config local fileconfig = p.fileconfig premake.modules.ninja = {} local ninja = p.modules.ninja function ninja.esc(value) return value -- TODO end -- generate solution that will call ninja for projects function ninja.generateSolution(sln) p.w("# solution build file") p.w("# generated with premake ninja") p.w("") p.w("# build projects") local cfgs = {} -- key is configuration name, value is string of outputs names local cfg_first = nil for prj in solution.eachproject(sln) do for cfg in project.eachconfig(prj) do -- fill list of output files if not cfgs[cfg.name] then cfgs[cfg.name] = "" end cfgs[cfg.name] = cfgs[cfg.name] .. ninja.outputFilename(cfg) .. " " -- set first configuration name if cfg_first == nil then cfg_first = cfg.name end -- include other ninja file p.w("subninja " .. ninja.projectCfgFilename(cfg)) end end p.w("") p.w("# targets") for cfg, outputs in pairs(cfgs) do p.w("build " .. cfg .. ": phony " .. outputs) end p.w("") p.w("# default target") p.w("default " .. cfg_first) end function ninja.list(value) if #value > 0 then return " " .. table.concat(value, " ") else return "" end end -- generate project + config build file function ninja.generateProjectCfg(cfg) if cfg.toolset == nil then cfg.toolset = "msc" -- TODO why premake doesn't provide default name always ? end local prj = cfg.project local toolset = premake.tools[cfg.toolset] p.w("# project build file") p.w("# generated with premake ninja") p.w("") ---------------------------------------------------- figure out toolset executables local cc = "" local cxx = "" local ar = "" local link = "" if cfg.toolset == "msc" then -- TODO premake doesn't set tools names for msc, do we want to fix it ? cc = "cl" cxx = "cl" ar = "lib" link = "cl" else -- TODO end ---------------------------------------------------- figure out settings local buildopt = ninja.list(cfg.buildoptions) local cflags = ninja.list(toolset.getcflags(cfg)) local cppflags = ninja.list(toolset.getcppflags(cfg)) local cxxflags = ninja.list(toolset.getcxxflags(cfg)) local warnings = ninja.list(toolset.getwarnings(cfg)) local defines = ninja.list(table.join(toolset.getdefines(cfg.defines), toolset.getundefines(cfg.undefines))) local includes = ninja.list(premake.esc(toolset.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs))) local forceincludes = ninja.list(premake.esc(toolset.getforceincludes(cfg))) -- TODO pch local lddeps = ninja.list(premake.esc(config.getlinks(cfg, "siblings", "fullpath"))) local ldflags = ninja.list(table.join(toolset.getLibraryDirectories(cfg), toolset.getldflags(cfg), cfg.linkoptions)) local libs = ninja.list(toolset.getlinks(cfg)) local all_cflags = buildopt .. cflags .. warnings .. defines .. includes .. forceincludes local all_cxxflags = buildopt .. cflags .. cppflags .. cxxflags .. warnings .. defines .. includes .. forceincludes local all_ldflags = buildopt .. lddeps .. ldflags .. libs local obj_dir = project.getrelative(cfg.project, cfg.objdir) ---------------------------------------------------- write rules p.w("# core rules") if cfg.toolset == "msc" then -- TODO /NOLOGO is invalid, we need to use /nologo p.w("rule cc_" .. cfg.name) p.w(" command = " .. cc .. all_cflags .. " /nologo /showIncludes -c $in /Fo$out") p.w(" description = cxx $out") p.w(" deps = msvc") p.w("rule cxx_" .. cfg.name) p.w(" command = " .. cc .. all_cxxflags .. " /nologo /showIncludes -c $in /Fo$out") p.w(" description = cxx $out") p.w(" deps = msvc") p.w("rule ar_" .. cfg.name) p.w(" command = " .. ar .. " $in /nologo -OUT:$out") p.w(" description = ar $out") p.w("rule link_" .. cfg.name) p.w(" command = " .. link .. " $in" .. all_ldflags .. " /nologo /link /out:$out") p.w(" description = link $out") p.w("") else -- TODO end ---------------------------------------------------- build all files p.w("# build files") local intermediateExt = function(cfg, var) if (var == "c") or (var == "cxx") then return iif(cfg.toolset == "msc", ".obj", ".o") elseif var == "res" then -- TODO return ".res" elseif var == "link" then return cfg.targetextension end end local objfiles = {} tree.traverse(project.getsourcetree(prj), { onleaf = function(node, depth) local filecfg = fileconfig.getconfig(node, cfg) if fileconfig.hasCustomBuildRule(filecfg) then -- TODO elseif path.iscppfile(node.abspath) then objfilename = obj_dir .. "/" .. node.objname .. intermediateExt(cfg, "cxx") p.w("build " .. objfilename .. ": cxx_" .. cfg.name .. " " .. node.relpath) objfiles[#objfiles + 1] = objfilename elseif path.isresourcefile(node.abspath) then -- TODO end end, }, false, 1) p.w("") ---------------------------------------------------- build final target if cfg.kind == premake.STATICLIB then p.w("# link static lib") p.w("build " .. ninja.outputFilename(cfg) .. ": ar_" .. cfg.name .. " " .. table.concat(objfiles, " ")) elseif cfg.kind == premake.SHAREDLIB then -- TODO elseif (cfg.kind == premake.CONSOLEAPP) or (cfg.kind == premake.WINDOWEDAPP) then -- TODO windowed app p.w("# link executable") p.w("build " .. ninja.outputFilename(cfg) .. ": link_" .. cfg.name .. " " .. table.concat(objfiles, " ")) else p.error("ninja action doesn't support this kind " .. cfg.kind) end end -- return name of output binary relative to build folder function ninja.outputFilename(cfg) return project.getrelative(cfg.project, cfg.buildtarget.directory) .. "/" .. cfg.buildtarget.name end -- return name of build file for configuration function ninja.projectCfgFilename(cfg) return "build_" .. cfg.project.name .. "_" .. cfg.name .. ".ninja" end -- generate all build files for every project configuration function ninja.generateProject(prj) for cfg in project.eachconfig(prj) do p.generate(cfg, ninja.projectCfgFilename(cfg), ninja.generateProjectCfg) end end include("_preload.lua") return ninja
root ninja file uses subninja now, fix phony rules for multiple projects
root ninja file uses subninja now, fix phony rules for multiple projects
Lua
mit
jimon/premake-ninja,jimon/premake-ninja,jimon/premake-ninja,jimon/premake-ninja
a8e470b6c6a54064287cfc0e31623db253e9f85a
src/sailor/access.lua
src/sailor/access.lua
-------------------------------------------------------------------------------- -- access.lua, v0.4: controls user login on sailor apps -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local sailor = require "sailor" local session = require "sailor.session" local bcrypt = require( "bcrypt" ) local log_rounds = 11 local access = {} session.open(sailor.r) local INVALID = "Invalid username or password." local settings = { default_login = 'admin', -- Default login details default_password = 'demo', grant_time = 604800, -- 1 week model = nil, -- Setting this field will deactivate default login details and activate below fields login_attributes = {'username'},-- Allows multiple options, for example, username or email. The one used to hash the password_attribute = 'password',-- password should come first. hashing = true } -- Changes settings function access.settings(s) for k, v in pairs(s) do settings[k] = v end end -- Simple hashing algorithm for encrypting passworsd function access.hash(username, password) return bcrypt.digest( username .. password, log_rounds ) end function access.verify_hash(username, password, model_password) if not settings.hashing then return model_password == password end return bcrypt.verify( username..password, model_password ) end function access.is_guest() if not access.data then access.data = session.data end return not access.data.login end function access.grant(data,time) session.setsessiontimeout (time or 604800) -- 1 week if not data.login then return false end access.data = data return session.save(data) end function access.find_object(login) local Model = sailor.model(settings.model) local o for _, attr in pairs(settings.login_attributes) do local a = {} a[attr] = login o = Model:find_by_attributes(a) if o ~= nil then return o end end return false end function access.login(login,password) local id if settings.model then local model = access.find_object(login) if not model then return false, INVALID end if not access.verify_hash(model[settings.login_attributes[1]], password, model[settings.password_attribute]) then return false, INVALID end id = model.id else if login ~= settings.default_login or password ~= settings.default_password then return false, INVALID end id = 1 end return access.grant({login=login,id=id}) end function access.logout() session.data = {} access.data = {} return session.destroy(sailor.r) end return access
-------------------------------------------------------------------------------- -- access.lua, v0.5: controls user login on sailor apps -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local sailor = require "sailor" local session = require "sailor.session" local bcrypt = require( "bcrypt" ) local log_rounds = 11 local access = {} session.open(sailor.r) local INVALID = "Invalid username or password." local function default_settings() return { default_login = 'admin', -- Default login details default_password = 'demo', grant_time = 604800, -- 1 week model = nil, -- Setting this field will deactivate default login details and activate below fields login_attributes = {'username'},-- Allows multiple options, for example, username or email. The one used to hash the password_attribute = 'password',-- password should come first. hashing = true } end local settings = default_settings() -- Changes settings function access.settings(s) settings = default_settings() for k, v in pairs(s) do settings[k] = v end end -- Simple hashing algorithm for encrypting passworsd function access.hash(username, password) return bcrypt.digest( username .. password, log_rounds ) end function access.verify_hash(username, password, model_password) if not settings.hashing then return model_password == password end return bcrypt.verify( username..password, model_password ) end function access.is_guest() if not access.data then access.data = session.data end return not access.data.login end function access.grant(data,time) session.setsessiontimeout (time or 604800) -- 1 week if not data.login then return false end access.data = data return session.save(data) end function access.find_object(login) local Model = sailor.model(settings.model) local o for _, attr in pairs(settings.login_attributes) do local a = {} a[attr] = login o = Model:find_by_attributes(a) if o ~= nil then return o end end return false end function access.login(login,password) local id if settings.model then local model = access.find_object(login) if not model then return false, INVALID end if not access.verify_hash(model[settings.login_attributes[1]], password, model[settings.password_attribute]) then return false, INVALID end id = model.id else if login ~= settings.default_login or password ~= settings.default_password then return false, INVALID end id = 1 end return access.grant({login=login,id=id}) end function access.logout() session.data = {} access.data = {} return session.destroy(sailor.r) end return access
fix(access): Reset settings before setting them
fix(access): Reset settings before setting them
Lua
mit
sailorproject/sailor,mpeterv/sailor,mpeterv/sailor,Etiene/sailor,Etiene/sailor
f3e9fc7cd4043adcc3fdbb95949b584626f6ceb5
modules/game_viplist/viplist.lua
modules/game_viplist/viplist.lua
VipList = {} -- private variables local vipWindow local vipButton local addVipWindow -- public functions function VipList.init() vipWindow = displayUI('viplist.otui', GameInterface.getLeftPanel()) vipButton = TopMenu.addGameToggleButton('vipListButton', 'VIP list', 'viplist.png', VipList.toggle) vipButton:setOn(true) end function VipList.terminate() vipWindow:destroy() vipWindow = nil vipButton:destroy() vipButton = nil end function VipList.toggle() local visible = not vipWindow:isExplicitlyVisible() vipWindow:setVisible(visible) vipButton:setOn(visible) end function VipList.createAddWindow() addVipWindow = displayUI('addvip.otui') end function VipList.destroyAddWindow() addVipWindow:destroy() addVipWindow = nil end function VipList.addVip() g_game.addVip(addVipWindow:getChildById('name'):getText()) VipList.destroyAddWindow() end -- hooked events function VipList.onAddVip(id, name, online) local vipList = vipWindow:getChildById('contentsPanel') local label = createWidget('VipListLabel', nil) label:setId('vip' .. id) label:setText(name) if online then label:setColor('#00ff00') else label:setColor('#ff0000') end label.vipOnline = online label:setPhantom(false) connect(label, { onDoubleClick = function () g_game.openPrivateChannel(label:getText()) return true end } ) local nameLower = name:lower() local childrenCount = vipList:getChildCount() for i=1,childrenCount do local child = vipList:getChildByIndex(i) if online and not child.vipOnline then vipList:insertChild(i, label) return end if (not online and not child.vipOnline) or (online and child.vipOnline) then local childText = child:getText():lower() local length = math.min(childText:len(), nameLower:len()) for j=1,length do if nameLower:byte(j) < childText:byte(j) then vipList:insertChild(i, label) return elseif nameLower:byte(j) > childText:byte(j) then break end end end end vipList:insertChild(childrenCount+1, label) end function VipList.onVipStateChange(id, online) local vipList = vipWindow:getChildById('vipList') local label = vipList:getChildById('vip' .. id) local text = label:getText() vipList:removeChild(label) VipList.onAddVip(id, text, online) end function VipList.onVipListMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local vipList = vipWindow:getChildById('vipList') local menu = createWidget('PopupMenu') menu:addOption('Add new VIP', function() VipList.createAddWindow() end) menu:display(mousePos) return true end function VipList.onVipListLabelMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local vipList = vipWindow:getChildById('vipList') local menu = createWidget('PopupMenu') menu:addOption('Add new VIP', function() VipList.createAddWindow() end) menu:addOption('Remove ' .. widget:getText(), function() if widget then g_game.removeVip(widget:getId():sub(4)) vipList:removeChild(widget) end end) menu:addSeparator() menu:addOption('Copy Name', function() g_window.setClipboardText(widget:getText()) end) menu:display(mousePos) return true end connect(g_game, { onGameStart = VipList.create, onGameEnd = VipList.destroy, onAddVip = VipList.onAddVip, onVipStateChange = VipList.onVipStateChange })
VipList = {} -- private variables local vipWindow local vipButton local addVipWindow -- public functions function VipList.init() connect(g_game, { onGameEnd = VipList.clear, onAddVip = VipList.onAddVip, onVipStateChange = VipList.onVipStateChange }) vipWindow = displayUI('viplist.otui', GameInterface.getLeftPanel()) vipButton = TopMenu.addGameToggleButton('vipListButton', 'VIP list', 'viplist.png', VipList.toggle) vipButton:setOn(true) end function VipList.terminate() disconnect(g_game, { onGameEnd = VipList.clear, onAddVip = VipList.onAddVip, onVipStateChange = VipList.onVipStateChange }) vipWindow:destroy() vipWindow = nil vipButton:destroy() vipButton = nil end function VipList.clear() local vipList = vipWindow:getChildById('contentsPanel') vipList:destroyChildren() end function VipList.toggle() local visible = not vipWindow:isExplicitlyVisible() vipWindow:setVisible(visible) vipButton:setOn(visible) end function VipList.createAddWindow() addVipWindow = displayUI('addvip.otui') end function VipList.destroyAddWindow() addVipWindow:destroy() addVipWindow = nil end function VipList.addVip() g_game.addVip(addVipWindow:getChildById('name'):getText()) VipList.destroyAddWindow() end -- hooked events function VipList.onAddVip(id, name, online) local vipList = vipWindow:getChildById('contentsPanel') local label = createWidget('VipListLabel', nil) label:setId('vip' .. id) label:setText(name) if online then label:setColor('#00ff00') else label:setColor('#ff0000') end label.vipOnline = online label:setPhantom(false) connect(label, { onDoubleClick = function () g_game.openPrivateChannel(label:getText()) return true end } ) local nameLower = name:lower() local childrenCount = vipList:getChildCount() for i=1,childrenCount do local child = vipList:getChildByIndex(i) if online and not child.vipOnline then vipList:insertChild(i, label) return end if (not online and not child.vipOnline) or (online and child.vipOnline) then local childText = child:getText():lower() local length = math.min(childText:len(), nameLower:len()) for j=1,length do if nameLower:byte(j) < childText:byte(j) then vipList:insertChild(i, label) return elseif nameLower:byte(j) > childText:byte(j) then break end end end end vipList:insertChild(childrenCount+1, label) end function VipList.onVipStateChange(id, online) local vipList = vipWindow:getChildById('vipList') local label = vipList:getChildById('vip' .. id) local text = label:getText() vipList:removeChild(label) VipList.onAddVip(id, text, online) end function VipList.onVipListMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local vipList = vipWindow:getChildById('contentsPanel') local menu = createWidget('PopupMenu') menu:addOption('Add new VIP', function() VipList.createAddWindow() end) menu:display(mousePos) return true end function VipList.onVipListLabelMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local vipList = vipWindow:getChildById('contentsPanel') local menu = createWidget('PopupMenu') menu:addOption('Add new VIP', function() VipList.createAddWindow() end) menu:addOption('Remove ' .. widget:getText(), function() if widget then g_game.removeVip(widget:getId():sub(4)) vipList:removeChild(widget) end end) menu:addSeparator() menu:addOption('Copy Name', function() g_window.setClipboardText(widget:getText()) end) menu:display(mousePos) return true end
fix viplist issues
fix viplist issues
Lua
mit
EvilHero90/otclient,Cavitt/otclient_mapgen,gpedro/otclient,kwketh/otclient,kwketh/otclient,gpedro/otclient,gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,dreamsxin/otclient,Radseq/otclient,EvilHero90/otclient,dreamsxin/otclient,dreamsxin/otclient
4261b8abac1ba1665f3226d91cb5b14636ffe220
entities/turret.lua
entities/turret.lua
local Turret = Class('Turret') function Turret:initialize(game, x, y, roomHash, offset, flip) self.game = game self.x = x self.y = y self.screenX = 0 self.screenY = 0 self.hitboxX = 24 self.hitboxY = 24 self.hitboxWidth = 36 self.hitboxHeight = 36 self.offset = offset or Vector(0, 0) self.flip = flip or false self.animationName = 'idle' self.image = Turret.images.idle self.animation = Turret.animations.idle:clone() self.roomHash = roomHash or 0 self.activated = false self.canShoot = true self.reloadTime = TWEAK.turretReloadTime self.timer = Timer.new() end function Turret:switchAnimation(name) self.animationName = name self.image = Turret.images[name] self.animation = Turret.animations[name]:clone() end function Turret:activate() if not self.activated then self.activated = true Signal.emit('turretActivate') end end function Turret:update(dt) local game = self.game self.alreadyDrawn = false self.animation:update(dt) self.timer:update(dt) if self.activated then local biggestEvolution = 0 local targetCandidates = {} local tiles = game:getRoomTiles(self.roomHash) for i, tile in ipairs(tiles) do local enemy = game:getEnemy(tile.x, tile.y) if enemy then if enemy.stage > biggestEvolution then targetCandidates = {enemy} biggestEvolution = enemy.stage else table.insert(targetCandidates, enemy) end end end local target = Lume.randomchoice(targetCandidates) if target and self.canShoot then -- @Hack game.mouseAction:clickEnemy(target.x, target.y) Signal.emit('turretFire', self.roomHash == game.currentRoom) self.canShoot = false self:switchAnimation('fire') self.animation.onLoop = function() self:switchAnimation('idle') end self.timer:after(self.reloadTime, function() self.canShoot = true end) end end end function Turret:draw() local game = self.game if not self.alreadyDrawn then local x, y = game:gridToScreen(self.x, self.y) local offset = Turret.animationOffsets[self.animationName] x = x + offset.x y = y - self.image:getHeight() + offset.y x = x + self.offset.x y = y + self.offset.y self.screenX = x self.screenY = y if self.flip then love.graphics.push() love.graphics.scale(-1, 1) self.animation:draw(self.image, x, y) love.graphics.pop() else self.animation:draw(self.image, x, y) end self.alreadyDrawn = true end end return Turret
local Turret = Class('Turret') function Turret:initialize(game, x, y, roomHash, offset, flip) self.game = game self.x = x self.y = y self.screenX = 0 self.screenY = 0 self.hitboxX = 24 self.hitboxY = 24 self.hitboxWidth = 36 self.hitboxHeight = 36 self.offset = offset or Vector(0, 0) self.flip = flip or false self.animationName = 'idle' self.image = Turret.images.idle self.animation = Turret.animations.idle:clone() self.roomHash = roomHash or 0 self.activated = false self.canShoot = true self.reloadTime = TWEAK.turretReloadTime self.timer = Timer.new() end function Turret:switchAnimation(name) self.animationName = name self.image = Turret.images[name] self.animation = Turret.animations[name]:clone() end function Turret:activate() if not self.activated then self.activated = true Signal.emit('turretActivate') end end function Turret:update(dt) local game = self.game self.alreadyDrawn = false self.animation:update(dt) self.timer:update(dt) if self.activated then local biggestEvolution = 0 local targetCandidates = {} local tiles = game:getRoomTiles(self.roomHash) for i, tile in ipairs(tiles) do local enemy = game:getEnemy(tile.x, tile.y) if enemy then if enemy.stage > biggestEvolution then targetCandidates = {enemy} biggestEvolution = enemy.stage else table.insert(targetCandidates, enemy) end end end local target = Lume.randomchoice(targetCandidates) if target and self.canShoot then -- @Hack game.mouseAction:clickEnemy(target.x, target.y) Signal.emit('turretFire', self.roomHash == game.currentRoom) self.canShoot = false self:switchAnimation('fire') self.animation.onLoop = function() self:switchAnimation('idle') end self.timer:after(self.reloadTime, function() self.canShoot = true end) end end end function Turret:draw() local game = self.game if not self.alreadyDrawn then local x, y = game:gridToScreen(self.x, self.y) local offset = Turret.animationOffsets[self.animationName] x = x + offset.x y = y - self.image:getHeight() + offset.y self.screenX = x self.screenY = y x = x + self.offset.x y = y + self.offset.y if self.flip then love.graphics.push() love.graphics.scale(-1, 1) self.animation:draw(self.image, x, y) love.graphics.pop() else self.animation:draw(self.image, x, y) end self.alreadyDrawn = true end end return Turret
fixed hitbox turret
fixed hitbox turret
Lua
mit
Nuthen/ludum-dare-39
45eff24a44f371fd55b79c0609390c45c97dfc83
himan-scripts/frost-sum.lua
himan-scripts/frost-sum.lua
-- Calculate frost sum from 2 meter daily mean temperature -- Positive values do not increase the value of frost sum -- -- For example: -- Daily (24h) mean t2m are: -4, -6, -1, +2, -5 -- Frost sum is: -16 (sic) -- -- Script should only be used with ECMWF data -- Calculate daily (24h) mean temperature by reading all t2m values -- found and doing simple arithmetic mean. -- Function reads past 24h from given time. function WriteMeanToFile(mean, ftime) local start = ftime:GetStep() - 24 local agg = aggregation(HPAggregationType.kAverage, HPTimeResolution.kHourResolution, 24, 999999) local par = param("T-MEAN-K") par:SetAggregation(agg) result:SetParam(par) result:SetValues(mean) luatool:WriteToFile(result) end function DailyMeanTemperature(atime, lastTime) local curTime = forecast_time(atime, lastTime) if curTime:GetStep() == 0 then return end local mean = luatool:FetchWithType(curTime, current_level, param("T-MEAN-K"), current_forecast_type) if mean then -- got lucky return mean end -- calculate 24h mean temperature local tsum = {} local stopStep = math.max(curTime:GetStep() - 24, 0) local count = 0 local step = curTime:GetStep() while true do local stepAdjustment = -1 if step >= 150 then stepAdjustment = -6 elseif step >= 93 then stepAdjustment = -3 end -- lastTime:Adjust(HPTimeResolution.kHourResolution, -configuration:GetForecastStep()) lastTime:Adjust(HPTimeResolution.kHourResolution, stepAdjustment) local time = forecast_time(atime, lastTime) if time:GetStep() < stopStep or time:GetStep() < 0 then break end local t2m = luatool:FetchWithType(time, current_level, param("T-K"), current_forecast_type) if t2m then if #tsum == 0 then for i=1, #t2m do tsum[i] = 0 end end for i=1, #t2m do tsum[i] = tsum[i] + t2m[i] end count = count + 1 end step = time:GetStep() end if #tsum == 0 then return end mean = {} for i=1,#tsum do mean[i] = tsum[i] / count end WriteMeanToFile(mean, curTime) return mean end local atime = current_time:GetOriginDateTime() local vtime = raw_time(current_time:GetValidDateTime():String("%Y-%m-%d %H:%M:%S")) local step = current_time:GetStep() local hour = tonumber(vtime:String("%H")) if step == 0 or hour ~= 0 then logger:Info(string.format("Analysis hour %d leadtime %d -- not calculating frost sum", tonumber(atime:String("%H")), hour)) return end local frostSum = {} while true do local curtime = raw_time(vtime:String("%Y-%m-%d %H:%M:%S")) logger:Info(string.format("Fetching mean temperature for day ending at %s", curtime:String("%Y%m%d%H"))) local mean = DailyMeanTemperature(atime, curtime) if mean then -- initialize frost sum array to zero if #frostSum == 0 then for i=1,#mean do frostSum[i] = 0 end end for i=1,#mean do -- positive values should not affect the value of frost sum local m = math.min(mean[i] - 273.15, 0) frostSum[i] = frostSum[i] + m end end if tonumber(curtime:String("%Y%m%d%H")) <= tonumber(atime:String("%Y%m%d%H")) then break end vtime:Adjust(HPTimeResolution.kHourResolution, -24) end local agg = aggregation(HPAggregationType.kAccumulation, HPTimeResolution.kHourResolution, current_time:GetStep(), 0) local par = param("FROSTSUM-C") par:SetAggregation(agg) result:SetParam(par) result:SetValues(frostSum) luatool:WriteToFile(result)
-- Calculate frost sum from 2 meter daily mean temperature -- Positive values do not increase the value of frost sum -- -- For example: -- Daily (24h) mean t2m are: -4, -6, -1, +2, -5 -- Frost sum is: -16 (sic) -- -- Script should only be used with ECMWF data -- Calculate daily (24h) mean temperature by reading all t2m values -- found and doing simple arithmetic mean. -- Function reads past 24h from given time. function WriteMeanToFile(mean, ftime) local start = ftime:GetStep() - 24 local agg = aggregation(HPAggregationType.kAverage, HPTimeResolution.kHourResolution, 24, 999999) local par = param("T-MEAN-K") par:SetAggregation(agg) result:SetParam(par) result:SetValues(mean) luatool:WriteToFile(result) end function DailyMeanTemperature(atime, lastTime) local curTime = forecast_time(atime, lastTime) if curTime:GetStep() == 0 then return end local mean = luatool:FetchWithType(curTime, current_level, param("T-MEAN-K"), current_forecast_type) if mean then -- got lucky return mean end -- calculate 24h mean temperature local tsum = {} local stopStep = math.max(curTime:GetStep() - 24, 0) local count = 0 local step = curTime:GetStep() while true do local stepAdjustment = -1 if step >= 150 then stepAdjustment = -6 elseif step >= 93 then stepAdjustment = -3 end -- lastTime:Adjust(HPTimeResolution.kHourResolution, -configuration:GetForecastStep()) lastTime:Adjust(HPTimeResolution.kHourResolution, stepAdjustment) local time = forecast_time(atime, lastTime) if time:GetStep() < stopStep or time:GetStep() < 0 then break end local t2m = luatool:FetchWithType(time, current_level, param("T-K"), current_forecast_type) if t2m then if #tsum == 0 then for i=1, #t2m do tsum[i] = 0 end end for i=1, #t2m do tsum[i] = tsum[i] + t2m[i] end count = count + 1 end step = time:GetStep() end if #tsum == 0 then return end mean = {} for i=1,#tsum do mean[i] = tsum[i] / count end WriteMeanToFile(mean, curTime) return mean end local atime = current_time:GetOriginDateTime() local vtime = raw_time(current_time:GetValidDateTime():String("%Y-%m-%d %H:%M:%S")) local step = current_time:GetStep() if step % 24 ~= 0 then logger:Info(string.format("Step is not a multiple of 24 (%d) -- skipping", step)) return end local frostSum = {} while true do local curtime = raw_time(vtime:String("%Y-%m-%d %H:%M:%S")) logger:Info(string.format("Fetching mean temperature for a 24h period ending at %s", curtime:String("%Y%m%d%H"))) local mean = DailyMeanTemperature(atime, curtime) if mean then -- initialize frost sum array to zero if #frostSum == 0 then for i=1,#mean do frostSum[i] = 0 end end for i=1,#mean do -- positive values should not affect the value of frost sum local m = math.min(mean[i] - 273.15, 0) frostSum[i] = frostSum[i] + m end end if tonumber(curtime:String("%Y%m%d%H")) <= tonumber(atime:String("%Y%m%d%H")) then break end vtime:Adjust(HPTimeResolution.kHourResolution, -24) end local agg = aggregation(HPAggregationType.kAccumulation, HPTimeResolution.kHourResolution, current_time:GetStep(), 0) local par = param("FROSTSUM-C") par:SetAggregation(agg) result:SetParam(par) result:SetValues(frostSum) luatool:WriteToFile(result)
Fix issue with 12z calculations.
Fix issue with 12z calculations. My misunderstanding was that frost sum should always be calculated to hour = 0 (ie. midnight). After re-reading the request ticket, I realized that it's only calculated when step % 24 == 0.
Lua
mit
fmidev/himan,fmidev/himan,fmidev/himan
47901c76d590f71151be00c33d5312a548137c0b
scripts/run_tests.lua
scripts/run_tests.lua
#!/usr/bin/env lua5.1 -- Weee local SCRIPTS_PATH = string.sub(arg[0], 1, -15) dofile(SCRIPTS_PATH .. "/common.lua") require("lfs") local prev_wd = lfs.currentdir() lfs.chdir(SCRIPTS_PATH .. "/..") local ROOT = lfs.currentdir() local group_data = {} group_data["core"] = { excluded = { ["algorithm/sort"] = true, }, args = { ["utility/args"] = '-a --b=1234 --c="goats" cmd -d a1 a2 "a3" 1 false true', }, } group_data["image"] = { excluded = { }, args = { }, } group_data["window"] = { excluded = { -- ["window/window"] = true, -- ["window/window_opengl"] = true, }, args = { }, } group_data["game"] = { excluded = { -- ["app/general"] = true, -- ["gfx/renderer_triangle"] = true, -- ["gfx/renderer_pipeline"] = true, }, args = { }, } local group_names = togo_libraries() local groups = {} for _, group_name in pairs(group_names) do local root = "lib/" .. group_name .. "/test" local group = { name = group_name, root = ROOT .. "/" .. root, data = group_data[group_name], tests = {}, } for file in iterate_dir(root, "file") do local name, ext = split_path(file) if ext == "elf" then if group.data.excluded[name] then printf("EXCLUDED: %s / %s", group_name, name) else table.insert(group.tests, file) end end end table.insert(groups, group) end function run() for _, group in pairs(groups) do printf("\nGROUP: %s", group.name) lfs.chdir(group.root) for _, path in pairs(group.tests) do local cmd = "./" .. path local args = group.data.args[path] if args then cmd = cmd .. " " .. args end printf("\nRUNNING: %s", cmd) local exit_code = os.execute(cmd) if exit_code ~= 0 then printf("ERROR: '%s' failed with exit code %d", path, exit_code) return -1 end end end return 0 end local ec = run() lfs.chdir(prev_wd) os.exit(ec)
#!/usr/bin/env lua5.1 -- Weee local SCRIPTS_PATH = string.sub(arg[0], 1, -15) dofile(SCRIPTS_PATH .. "/common.lua") require("lfs") local prev_wd = lfs.currentdir() lfs.chdir(SCRIPTS_PATH .. "/..") local ROOT = lfs.currentdir() local group_data = {} group_data["core"] = { excluded = { ["algorithm/sort"] = true, }, args = { ["utility/args"] = '-a --b=1234 --c="goats" cmd -d a1 a2 "a3" 1 false true', }, } group_data["image"] = { excluded = { }, args = { }, } group_data["window"] = { excluded = { -- ["window/window"] = true, -- ["window/window_opengl"] = true, }, args = { }, } group_data["game"] = { excluded = { -- ["app/general"] = true, -- ["gfx/renderer_triangle"] = true, -- ["gfx/renderer_pipeline"] = true, }, args = { }, } local group_names = togo_libraries() local groups = {} for _, group_name in pairs(group_names) do local root = "lib/" .. group_name .. "/test" local group = { name = group_name, root = ROOT .. "/" .. root, data = group_data[group_name], tests = {}, } for file in iterate_dir(root, "file") do local name, ext = split_path(file) if ext == "elf" then if group.data.excluded[name] then printf("EXCLUDED: %s / %s", group_name, name) else table.insert(group.tests, {name = name, path = file}) end end end table.insert(groups, group) end function run() for _, group in pairs(groups) do printf("\nGROUP: %s", group.name) lfs.chdir(group.root) for _, test in pairs(group.tests) do local cmd = "./" .. test.path local args = group.data.args[test.name] if args then cmd = cmd .. " " .. args end printf("\nRUNNING: %s", cmd) local exit_code = os.execute(cmd) if exit_code ~= 0 then printf("ERROR: '%s' failed with exit code %d", test.path, exit_code) return -1 end end end return 0 end local ec = run() lfs.chdir(prev_wd) os.exit(ec)
scripts/run_tests.lua: fixed test args lookup.
scripts/run_tests.lua: fixed test args lookup.
Lua
mit
komiga/togo,komiga/togo,komiga/togo
f606fef31c6f94a3a7568a1c1cbfa50872810c7d
test/lua/unit/url.lua
test/lua/unit/url.lua
-- URL parser tests context("URL check functions", function() local mpool = require("rspamd_mempool") local ffi = require("ffi") ffi.cdef[[ struct rspamd_url { char *string; int protocol; int ip_family; char *user; char *password; char *host; char *port; char *data; char *query; char *fragment; char *post; char *surbl; struct rspamd_url *phished_url; unsigned int protocollen; unsigned int userlen; unsigned int passwordlen; unsigned int hostlen; unsigned int portlen; unsigned int datalen; unsigned int querylen; unsigned int fragmentlen; unsigned int surbllen; /* Flags */ int ipv6; /* URI contains IPv6 host */ int form; /* URI originated from form */ int is_phished; /* URI maybe phishing */ }; struct rspamd_config; struct rspamd_url* rspamd_url_get_next (void *pool, const char *start, char const **pos); void * rspamd_mempool_new (unsigned long size); void rspamd_url_init (const char *tld_file); ]] test("Extract urls from text", function() local pool = ffi.C.rspamd_mempool_new(4096) local cases = { {"test.com text", {"test.com", nil}}, {"mailto:A.User@example.com text", {"example.com", "A.User"}}, {"http://Тест.Рф:18 text", {"тест.рф", nil}}, {"http://user:password@тест2.РФ:18 text", {"тест2.рф", "user"}}, } ffi.C.rspamd_url_init(nil) for _,c in ipairs(cases) do local res = ffi.C.rspamd_url_get_next(pool, c[1], nil) assert_not_nil(res, "cannot parse " .. c[1]) assert_equal(c[2][1], ffi.string(res.host, res.hostlen)) if c[2][2] then assert_equal(c[2][2], ffi.string(res.user, res.userlen)) end end end) end)
-- URL parser tests context("URL check functions", function() local mpool = require("rspamd_mempool") local ffi = require("ffi") ffi.cdef[[ struct rspamd_url { char *string; int protocol; int ip_family; char *user; char *password; char *host; char *port; char *data; char *query; char *fragment; char *post; char *surbl; struct rspamd_url *phished_url; unsigned int protocollen; unsigned int userlen; unsigned int passwordlen; unsigned int hostlen; unsigned int portlen; unsigned int datalen; unsigned int querylen; unsigned int fragmentlen; unsigned int surbllen; /* Flags */ int ipv6; /* URI contains IPv6 host */ int form; /* URI originated from form */ int is_phished; /* URI maybe phishing */ }; struct rspamd_config; struct rspamd_url* rspamd_url_get_next (void *pool, const char *start, char const **pos, int *statep); void * rspamd_mempool_new (unsigned long size); void rspamd_url_init (const char *tld_file); ]] test("Extract urls from text", function() local pool = ffi.C.rspamd_mempool_new(4096) local cases = { {"test.com text", {"test.com", nil}}, {"mailto:A.User@example.com text", {"example.com", "A.User"}}, {"http://Тест.Рф:18 text", {"тест.рф", nil}}, {"http://user:password@тест2.РФ:18 text", {"тест2.рф", "user"}}, } local test_dir = string.gsub(debug.getinfo(1).source, "^@(.+/)[^/]+$", "%1") ffi.C.rspamd_url_init(string.format('%s/%s', test_dir, "test_tld.dat")) for _,c in ipairs(cases) do local res = ffi.C.rspamd_url_get_next(pool, c[1], nil, nil) assert_not_nil(res, "cannot parse " .. c[1]) assert_equal(c[2][1], ffi.string(res.host, res.hostlen)) if c[2][2] then assert_equal(c[2][2], ffi.string(res.user, res.userlen)) end end end) end)
Fix urls unit test.
Fix urls unit test.
Lua
bsd-2-clause
dark-al/rspamd,dark-al/rspamd,dark-al/rspamd,amohanta/rspamd,awhitesong/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,awhitesong/rspamd,awhitesong/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,dark-al/rspamd,AlexeySa/rspamd,awhitesong/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,minaevmike/rspamd,amohanta/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd
88b2c05a91b7bcad1494e7b8e9917cf999596d08
Plan.lua
Plan.lua
--- LUA wrapper for moveit planning environment -- dependency to tourch.ros -- @classmod Plan local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros' local moveit = require 'moveit.env' local utils = require 'moveit.utils' local gnuplot = require 'gnuplot' local Plan = torch.class('moveit.Plan', moveit) local f function init() local Plan_method_names = { "new", "delete", "release", "getStartStateMsg", "setStartStateMsg", "getTrajectoryMsg", "setTrajectoryMsg", "getPlanningTime", "plot", "convertTrajectoyMsgToTable", "convertStartStateMsgToTensor" } f = utils.create_method_table("moveit_Plan_", Plan_method_names) end init() function Plan:__init() self.o = f.new() self.moveit_msgs_RobotStateSpec = ros.get_msgspec('moveit_msgs/RobotState') self.moveit_msgs_RobotTrajectory = ros.get_msgspec('moveit_msgs/RobotTrajectory') end function Plan:cdata() return self.o end function Plan:release() f.release(self.o) end ---Create a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getStartStateMsg(result) local msg_bytes = torch.ByteStorage() f.getStartStateMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotStateSpec, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result function Plan:setStartStateMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() local newOffset = f.setStartStateMsg(self.o, msg_bytes.storage:cdata()) end end ---Create a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getTrajectoryMsg(result) local msg_bytes = torch.ByteStorage() f.getTrajectoryMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotTrajectory, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message input function Plan:setTrajectoryMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() local newOffset = f.setTrajectoryMsg(self.o, msg_bytes.storage:cdata()) end end ---Get the number of seconds --@treturn number function Plan:getPlanningTime() return f.getPlannigTime(self.o) end ---Convert a ros message: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message trajectory_msg --@return Positions, Velocities and Labels (name of each joint) function Plan:convertTrajectoyMsgToTable(trajectory_msg) -- expect a Utils object local positions = {} local velocities = {} local accelerations = {} local efforts = {} local points = trajectory_msg.joint_trajectory.points for i=1,#points do positions[i] = points[i].positions velocities[i] = points[i].velocities accelerations[i] = points[i].accelerations efforts[i] = points[i].effort end return positions,velocities,accelerations,efforts end ---Convert a ros message: moveit_msgs/RobotState --@tparam[opt] ros.Message start_state --@return current position, velocity and labels (name of each joint) function Plan:convertStartStateMsgToTensor(start_state) -- expect a Utils object local position = start_state.joint_state.position local velocity = start_state.joint_state.velocity local labels = start_state.joint_state.names return position, velocity, labels end local function plot6DTrajectory(trajectory) if trajectory[1]:nDimension()==0 then return false end local history_size = #trajectory local q1={} local q2={} local q3={} local q4={} local q5={} local q6={} for i=1,history_size do q1[#q1+1] = trajectory[i][1] q2[#q2+1] = trajectory[i][2] q3[#q3+1] = trajectory[i][3] q4[#q4+1] = trajectory[i][4] q5[#q5+1] = trajectory[i][5] q6[#q6+1] = trajectory[i][6] end local q1_tensor = torch.Tensor(q1) local q2_tensor = torch.Tensor(q2) local q3_tensor = torch.Tensor(q3) local q4_tensor = torch.Tensor(q4) local q5_tensor = torch.Tensor(q5) local q6_tensor = torch.Tensor(q6) gnuplot.plot({'q1',q1_tensor}, {'q2',q2_tensor}, {'q3',q3_tensor},{'q4',q4_tensor},{'q5',q5_tensor},{'q6',q6_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) return true end ---Creates gnu plot for either position, velocity, acceleration and speed depending input --@tparam int type if 1: Positions are plotted, 2: velocities are plotted,3: accelarations are plotted,4: speed is plotted --@treturn boolean is true if the requested type of the plot is know. function Plan:plot(type) local msg msg= self:getTrajectoryMsg()--Position local positions,velocities,accelerations,efforts= self:convertTrajectoyMsgToTable(msg) gnuplot.figure(type) if type == 1 then if plot6DTrajectory(positions)then gnuplot.title('Trajectory position Data') else return false end elseif type == 2 then if plot6DTrajectory(velocities) then gnuplot.title('Trajectory velocity Data') else return false end elseif type == 3 then if plot6DTrajectory(accelerations) then gnuplot.title('Trajectory accelaration Data') else return false end elseif type ==4 then if velocities[1]:nDimension()==0 then return false end history_size = #velocities local q = {} for i=1,#velocities do q[#q+1] = torch.norm(velocities[i]) end local q_tensor = torch.Tensor(q) gnuplot.plot({'speed',q_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) gnuplot.title('Trajectory speed Data') else print("plot type not yet implemented") return false end return true end
--- LUA wrapper for moveit planning environment -- dependency to tourch.ros -- @classmod Plan local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros' local moveit = require 'moveit.env' local utils = require 'moveit.utils' local gnuplot = require 'gnuplot' local Plan = torch.class('moveit.Plan', moveit) local f function init() local Plan_method_names = { "new", "delete", "release", "getStartStateMsg", "setStartStateMsg", "getTrajectoryMsg", "setTrajectoryMsg", "getPlanningTime", "plot", "convertTrajectoyMsgToTable", "convertStartStateMsgToTensor" } f = utils.create_method_table("moveit_Plan_", Plan_method_names) end init() function Plan:__init() self.o = f.new() self.moveit_msgs_RobotStateSpec = ros.get_msgspec('moveit_msgs/RobotState') self.moveit_msgs_RobotTrajectory = ros.get_msgspec('moveit_msgs/RobotTrajectory') end function Plan:cdata() return self.o end function Plan:release() f.release(self.o) end ---Create a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getStartStateMsg(result) local msg_bytes = torch.ByteStorage() f.getStartStateMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotStateSpec, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result function Plan:setStartStateMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() f.setStartStateMsg(self.o, msg_bytes.storage:cdata()) end end ---Create a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getTrajectoryMsg(result) local msg_bytes = torch.ByteStorage() f.getTrajectoryMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotTrajectory, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message input function Plan:setTrajectoryMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() f.setTrajectoryMsg(self.o, msg_bytes.storage:cdata()) end end ---Get the number of seconds --@treturn number function Plan:getPlanningTime() return f.getPlannigTime(self.o) end ---Convert a ros message: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message trajectory_msg --@return Positions, Velocities and Labels (name of each joint) function Plan:convertTrajectoyMsgToTable(trajectory_msg) -- expect a Utils object local positions = {} local velocities = {} local accelerations = {} local efforts = {} local points = trajectory_msg.joint_trajectory.points for i=1,#points do positions[i] = points[i].positions velocities[i] = points[i].velocities accelerations[i] = points[i].accelerations efforts[i] = points[i].effort end return positions,velocities,accelerations,efforts end ---Convert a ros message: moveit_msgs/RobotState --@tparam[opt] ros.Message start_state --@return current position, velocity and labels (name of each joint) function Plan:convertStartStateMsgToTensor(start_state) -- expect a Utils object local position = start_state.joint_state.position local velocity = start_state.joint_state.velocity local labels = start_state.joint_state.names return position, velocity, labels end local function plot6DTrajectory(trajectory) if trajectory[1]:nDimension()==0 then return false end local history_size = #trajectory local q1={} local q2={} local q3={} local q4={} local q5={} local q6={} for i=1,history_size do q1[#q1+1] = trajectory[i][1] q2[#q2+1] = trajectory[i][2] q3[#q3+1] = trajectory[i][3] q4[#q4+1] = trajectory[i][4] q5[#q5+1] = trajectory[i][5] q6[#q6+1] = trajectory[i][6] end local q1_tensor = torch.Tensor(q1) local q2_tensor = torch.Tensor(q2) local q3_tensor = torch.Tensor(q3) local q4_tensor = torch.Tensor(q4) local q5_tensor = torch.Tensor(q5) local q6_tensor = torch.Tensor(q6) gnuplot.plot({'q1',q1_tensor}, {'q2',q2_tensor}, {'q3',q3_tensor},{'q4',q4_tensor},{'q5',q5_tensor},{'q6',q6_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) return true end ---Creates gnu plot for either position, velocity, acceleration and speed depending input --@tparam int type if 1: Positions are plotted, 2: velocities are plotted,3: accelarations are plotted,4: speed is plotted --@treturn boolean is true if the requested type of the plot is know. function Plan:plot(type) local msg msg= self:getTrajectoryMsg()--Position local positions,velocities,accelerations,efforts= self:convertTrajectoyMsgToTable(msg) gnuplot.figure(type) if type == 1 then if plot6DTrajectory(positions)then gnuplot.title('Trajectory position Data') else return false end elseif type == 2 then if plot6DTrajectory(velocities) then gnuplot.title('Trajectory velocity Data') else return false end elseif type == 3 then if plot6DTrajectory(accelerations) then gnuplot.title('Trajectory accelaration Data') else return false end elseif type ==4 then if velocities[1]:nDimension()==0 then return false end history_size = #velocities local q = {} for i=1,#velocities do q[#q+1] = torch.norm(velocities[i]) end local q_tensor = torch.Tensor(q) gnuplot.plot({'speed',q_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) gnuplot.title('Trajectory speed Data') else print("plot type not yet implemented") return false end return true end
bugfix
bugfix
Lua
bsd-3-clause
Xamla/torch-moveit
d2fdb3916206b7c00a8ba8a82aec80e319b9f10d
map/lua/table.lua
map/lua/table.lua
--如果不是数字,则移除指定值 local oldremove = table.remove function table.remove(t, p) if p and type(p) ~= 'number' then for i = 1, #t do local v = t[i] if v == p then oldremove(t, i) return end end else oldremove(t, p) end end --将数组转化为哈希表 function table.key(t, v) if v == nil then v = true end local nt = {} for i = 1, #t do nt[t[i]] = v end return nt end --挑选出数组中的某个值 ---table.pick(表, 规则, 项目) function table.pick(t, f1, f2) local count = #t if count == 0 then return elseif count == 1 then return t[1], 1 end local y = f2 and f2(t[1]) or t[1] local r = 1 for i = 2, count do local x = f2 and f2(t[i]) or t[i] if f1(x, y) then y = x r = i end end return t[r], r end --批量删除表中指定的索引 function table.removes(a, b) for j = 1, #b do local x, y = b[j], b[j + 1] or #a for i = x - j + 1, y - j + 1 do a[i] = a[i + j] end end end --建立带有默认值的表 function table.new(n) local mt = {} function mt.__index() return n end function mt.__call(t, nt) mt.__call = nil return setmetatable(nt, mt) end return setmetatable({}, mt) end --创建反向表(不要吐槽我英文) function table.back(t) local tt = {} for name, value in pairs(t) do if not tt[name] and not tt[value] then tt[name] = true tt[value] = true t[value] = name end end return t end --meta表 table.meta = { math = { __index = function() return 0 end, __add = function(t1, t2) local t = setmetatable({}, table.meta.math) for name in pairs(t1) do t[name] = t1[name] + t2[name] end return t end, __sub = function(t1, t2) local t = setmetatable({}, table.meta.math) for name in pairs(t1) do t[name] = t1[name] - t2[name] end return t end, }, }
--如果不是数字,则移除指定值 local oldremove = table.remove function table.remove(t, p) if p and type(p) ~= 'number' then for i = 1, #t do local v = t[i] if v == p then oldremove(t, i) return end end else oldremove(t, p) end end --将数组转化为哈希表 function table.key(t, v) if v == nil then v = true end local nt = {} for i = 1, #t do nt[t[i]] = v end return nt end --挑选出数组中的某个值 ---table.pick(表, 规则, 项目) function table.pick(t, f1, f2) local count = #t if count == 0 then return elseif count == 1 then return t[1], 1 end local y = f2 and f2(t[1]) or t[1] local r = 1 for i = 2, count do local x = f2 and f2(t[i]) or t[i] if f1(x, y) then y = x r = i end end return t[r], r end --批量删除表中指定的索引 function table.removes(a, b) local n = #a - #b + 1 for j = 1, #b do local x, y = b[j], b[j + 1] or #a for i = x - j + 1, y - j + 1 do a[i] = a[i + j] end end for i = n, #a do a[i] = nil end end --建立带有默认值的表 function table.new(n) local mt = {} function mt.__index() return n end function mt.__call(t, nt) mt.__call = nil return setmetatable(nt, mt) end return setmetatable({}, mt) end --创建反向表(不要吐槽我英文) function table.back(t) local tt = {} for name, value in pairs(t) do if not tt[name] and not tt[value] then tt[name] = true tt[value] = true t[value] = name end end return t end --meta表 table.meta = { math = { __index = function() return 0 end, __add = function(t1, t2) local t = setmetatable({}, table.meta.math) for name in pairs(t1) do t[name] = t1[name] + t2[name] end return t end, __sub = function(t1, t2) local t = setmetatable({}, table.meta.math) for name in pairs(t1) do t[name] = t1[name] - t2[name] end return t end, }, }
修正一个基础函数的BUG
修正一个基础函数的BUG
Lua
apache-2.0
syj2010syj/All-star-Battle
00b252238f2b20e9edcd7dbcdd63fc504e53edaa
src/facil/core.lua
src/facil/core.lua
--[[---------------------------------------------------------------------------- --- @file core.lua --- @brief Core component of fácil. ----------------------------------------------------------------------------]]-- local FileSystem = require "lfs" local Uuid = require "uuid" local Template = {} Template.Md = require "facil.template.md" Template.Config = require "facil.template.default_config" local _M = {} --- Generates full path inside .fl for card or meta files. -- @param root Root folder of file inside .fl ("cards", "meta", "boards") as string. -- @param prefix Name of subfolder inside the root as string. -- @return string with full path with trailing / on success, nil otherwise local function generatePath(root, prefix) local pwd = FileSystem.currentdir() if not pwd then return nil end local path = { pwd, ".fl" } if root and "" ~= root then path[#path + 1] = root end if prefix and "" ~= prefix then path[#path + 1] = prefix end return table.concat(path, "/") end --- Creates directory if doesn't exist. -- @param path Path to create directory -- @return true on success, false otherwise. local function createDir(path) return ("directory" == FileSystem.attributes(path, "mode")) or FileSystem.mkdir(path) end --- Creates directories, files for card or metadata. -- @param root Root directory of created file ("crads" | "meta" | "boards"). -- @param prefix Name prefix, used to create directory. -- @param infix Name infix, used to create file name. -- @param suffix Name suffix, used to create file extension. (optional) -- @param content Content of created file. -- @return {path, name} - description of created file on success, -- nil, string - description of error otherwise. local function createCardFile(root, prefix, infix, suffix, content) local data = {} data.path = generatePath(root, prefix) if not data.path then return nil, "Can't generate file name for card." end local fullName = { data.path } if infix and "" ~= infix then fullName[#fullName + 1] = infix end data.name = table.concat(fullName, "/") if suffix and "" ~= suffix then data.name = data.name .. suffix end if not createDir(data.path) then return nil, "Can't create dir: " .. data.path end local file = io.open(data.name, "w") if not file then return nil, "Can't create file: " .. tostring(data.name) end file:write(content) file:close() return data end --- Serializes lua card table to meta file format. -- @param card Card description {name, dat, id} -- @todo Use either proper serialization lib or json lib. -- @return serialized card as string on success, nil otherwise. local function serializeMeta(card) if not card or "table" ~= type(card) then return nil end local meta = {} meta[#meta + 1] = "return {" meta[#meta + 1] = " id = " .. card.id .. "," meta[#meta + 1] = " name = " .. card.name .. "," meta[#meta + 1] = " created = " .. tostring(card.time) .. "" meta[#meta + 1] = "}" return table.concat(meta, "\n") end --- Creates new card -- @param name Short descriptive name of card. -- @retval true, string - on success, where string is the uuid of new card. -- @retval nil, string - on error, where string contains detailed description. function _M.create(name) if not name or "string" ~= type(name) then return nil, "Invalid argument." end local card = {} card.name = name card.id = uuid.new() if not card.id then return nil, "Can't generate uuid for card." end card.time = os.time() local prefix = card.id:sub(1, 2) local body = card.id:sub(3) local markdown, markdownErr = createCardFile("cards", prefix, body, ".md", Template.Md.value) if not markdown then return nil, markdownErr end --- @warning Platform (linux specific) dependent code. --- @todo Either replace with something more cross platform --- or check OS before. os.execute("$EDITOR " .. markdown.name) local meta, metaErr = createCardFile("meta", prefix, body, nil, serializeMeta(card)) if not meta then return nil, metaErr end local marker, markerErr = createCardFile("boards", "backlog", card.id, nil, tostring(card.time)) if not marker then return nil, markerErr end return true, card.id end --- Initialized fácil's file system layout inside selected directory. -- @param root Path to the root directory, where to initialize fl. -- @retval true - on success -- @retval nil, string - on error, where string contains detailed description. function _M.init(root) if not root or "string" ~= type(root) then return nil, "Invalid argument." end local directories = {} directories[#directories + 1] = root .. "/.fl" directories[#directories + 1] = root .. "/.fl/boards" directories[#directories + 1] = root .. "/.fl/boards/backlog" directories[#directories + 1] = root .. "/.fl/boards/progress" directories[#directories + 1] = root .. "/.fl/boards/done" directories[#directories + 1] = root .. "/.fl/cards" directories[#directories + 1] = root .. "/.fl/meta" for _, path in pairs(directories) do if not createDir(path) then return nil, "Can't create directory: " .. path end end local configSuccess, configError = createCardFile("", nil, "config", nil, Template.Config.value) if not configSuccess then return nil, configError end return true end return _M
--[[---------------------------------------------------------------------------- --- @file core.lua --- @brief Core component of fácil. ----------------------------------------------------------------------------]]-- local FileSystem = require "lfs" local Uuid = require "uuid" local Template = {} Template.Md = require "facil.template.md" Template.Config = require "facil.template.default_config" local _M = {} --- Generates full path inside .fl for card or meta files. -- @param root Root folder of file inside .fl ("cards", "meta", "boards") as string. -- @param prefix Name of subfolder inside the root as string. -- @return string with full path with trailing / on success, nil otherwise local function generatePath(root, prefix) local pwd = FileSystem.currentdir() if not pwd then return nil end local path = { pwd, ".fl" } if root and "" ~= root then path[#path + 1] = root end if prefix and "" ~= prefix then path[#path + 1] = prefix end return table.concat(path, "/") end --- Creates directory if doesn't exist. -- @param path Path to create directory -- @return true on success, false otherwise. local function createDir(path) return ("directory" == FileSystem.attributes(path, "mode")) or FileSystem.mkdir(path) end --- Creates directories, files for card or metadata. -- @param root Root directory of created file ("crads" | "meta" | "boards"). -- @param prefix Name prefix, used to create directory. -- @param infix Name infix, used to create file name. -- @param suffix Name suffix, used to create file extension. (optional) -- @param content Content of created file. -- @return {path, name} - description of created file on success, -- nil, string - description of error otherwise. local function createCardFile(root, prefix, infix, suffix, content) local data = {} data.path = generatePath(root, prefix) if not data.path then return nil, "Can't generate file name for card." end local fullName = { data.path } if infix and "" ~= infix then fullName[#fullName + 1] = infix end data.name = table.concat(fullName, "/") if suffix and "" ~= suffix then data.name = data.name .. suffix end if not createDir(data.path) then return nil, "Can't create dir: " .. data.path end local file = io.open(data.name, "w") if not file then return nil, "Can't create file: " .. tostring(data.name) end file:write(content) file:close() return data end --- Serializes lua card table to meta file format. -- @param card Card description {name, dat, id} -- @todo Use either proper serialization lib or json lib. -- @return serialized card as string on success, nil otherwise. local function serializeMeta(card) if not card or "table" ~= type(card) then return nil end local meta = { "return {", " id = " .. card.id .. ",", " name = " .. card.name .. ",", " created = " .. tostring(card.time) .. "", "}" } return table.concat(meta, "\n") end --- Creates new card -- @param name Short descriptive name of card. -- @retval true, string - on success, where string is the uuid of new card. -- @retval nil, string - on error, where string contains detailed description. function _M.create(name) if not name or "string" ~= type(name) then return nil, "Invalid argument." end local card = {} card.name = name card.id = uuid.new() if not card.id then return nil, "Can't generate uuid for card." end card.time = os.time() local prefix = card.id:sub(1, 2) local body = card.id:sub(3) local markdown, markdownErr = createCardFile("cards", prefix, body, ".md", Template.Md.value) if not markdown then return nil, markdownErr end --- @warning Platform (linux specific) dependent code. --- @todo Either replace with something more cross platform --- or check OS before. os.execute("$EDITOR " .. markdown.name) local meta, metaErr = createCardFile("meta", prefix, body, nil, serializeMeta(card)) if not meta then return nil, metaErr end local marker, markerErr = createCardFile("boards", "backlog", card.id, nil, tostring(card.time)) if not marker then return nil, markerErr end return true, card.id end --- Initialized fácil's file system layout inside selected directory. -- @param root Path to the root directory, where to initialize fl. -- @retval true - on success -- @retval nil, string - on error, where string contains detailed description. function _M.init(root) if not root or "string" ~= type(root) then return nil, "Invalid argument." end local directories = { root .. "/.fl", root .. "/.fl/boards", root .. "/.fl/boards/backlog", root .. "/.fl/boards/progress", root .. "/.fl/boards/done", root .. "/.fl/cards", root .. "/.fl/meta" } for _, path in pairs(directories) do if not createDir(path) then return nil, "Can't create directory: " .. path end end local configSuccess, configError = createCardFile("", nil, "config", nil, Template.Config.value) if not configSuccess then return nil, configError end return true end return _M
Fix: small performance fix.
Fix: small performance fix.
Lua
mit
norefle/facil
f5d4bcade271e60bc31b0455b275991d0ed64dd3
models/upload.lua
models/upload.lua
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(dest_dir, oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') if not ext then main = oldname ext = '' end -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( dest_dir + main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end local function absoluteDirPrefix() local monserver_dir = bamboo.config.monserver_dir local project_name = bamboo.config.project_name assert(monserver_dir) assert(project_name) return string.trailingPath(monserver_dir + '/sites/' + project_name + '/uploads/') end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req -- @field t.file_obj -- @field t.dest_dir -- @field t.prefix -- @field t.postfix -- local function savefile(t) local req, file_obj = t.req, t.file_obj local dest_dir = t.dest_dir and absoluteDirPrefix() + t.dest_dir dest_dir = string.trailingPath(dest_dir) -- print(dest_dir) local url_prefix = 'media/uploads/' + t.dest_dir + '/' url_prefix = string.trailingPath(url_prefix) local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') body = file_obj.body end if isFalse(filename) or isFalse(body) then return nil, nil end if not posix.stat(dest_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + dest_dir) end local newbasename, ext = calcNewFilename(dest_dir, filename) local newname = prefix + newbasename + postfix + ext local absolute_path = dest_dir + newname local url_path = url_prefix + newname -- write file to disk local fd = io.open(absolute_path, "wb") fd:write(body) fd:close() return absolute_path, newname, url_path end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = "User's upload files."; __fields = { ['name'] = {}, ['path'] = {}, ['absolute_path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.url_path self.absolute_path = t.absolute_path self.size = posix.stat(t.absolute_path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local absolute_path, name, url_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not absolute_path or not name then return nil end -- create file instance local file_instance = self { name = name, absolute_path = absolute_path, url_path = url_path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(req, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if upload in html5 way if req.headers['x-requested-with'] then -- stored to disk local absolute_path, name, url_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not absolute_path or not name then return nil, '[ERROR] empty file.' end local file_instance = self { name = name, absolute_path = absolute_path, url_path = url_path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading in html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if not files then return nil, '[ERROR] empty file.' end if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, dest_dir, oldname) return calcNewFilename(dest_dir, oldname) end; absoluteDirPrefix = function (self) return absoluteDirPrefix() end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('rm ' + self.absolute_path) return self end; } return Upload
--- A basic lower upload API -- module(..., package.seeall) require 'posix' local Model = require 'bamboo.model' local Form = require 'bamboo.form' local function calcNewFilename(absolute_dir, oldname) -- separate the base name and extense name of a filename local main, ext = oldname:match('^(.+)(%.%w+)$') if not ext then main = oldname ext = '' end -- check if exists the same name file local tstr = '' local i = 0 while posix.stat( absolute_dir + main + tstr + ext ) do i = i + 1 tstr = '_' + tostring(i) end -- concat to new filename local newbasename = main + tstr return newbasename, ext end local function absoluteDirPrefix() local monserver_dir = bamboo.config.monserver_dir local project_name = bamboo.config.project_name assert(monserver_dir) assert(project_name) return string.trailingPath(monserver_dir + '/sites/' + project_name + '/uploads/') end --- here, we temprorily only consider the file data is passed wholly by zeromq -- and save by bamboo -- @field t.req -- @field t.file_obj -- @field t.dest_dir -- @field t.prefix -- @field t.postfix -- local function savefile(t) local req, file_obj = t.req, t.file_obj t.dest_dir = string.trailingPath(t.dest_dir and (t.dest_dir + '/') or '') local absolute_dir = absoluteDirPrefix() + t.dest_dir absolute_dir = string.trailingPath(absolute_dir) local url_prefix = 'media/uploads/' local prefix = t.prefix or '' local postfix = t.postfix or '' local filename = '' local body = '' -- if upload in html5 way if req.headers['x-requested-with'] then -- when html5 upload, we think of the name of that file was stored in header x-file-name -- if this info missing, we may consider the filename was put in the query string filename = req.headers['x-file-name'] -- TODO: -- req.body contains all file binary data body = req.body else checkType(file_obj, 'table') -- Notice: the filename in the form string are quoted by "" -- this pattern rule can deal with the windows style directory delimiter -- file_obj['content-disposition'] contains many file associated info filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$') body = file_obj.body end if isFalse(filename) or isFalse(body) then return nil, nil end if not posix.stat(absolute_dir) then -- why posix have no command like " mkdir -p " os.execute('mkdir -p ' + absolute_dir) end local newbasename, ext = calcNewFilename(absolute_dir, filename) local newname = prefix + newbasename + postfix + ext -- xxxx local path = t.dest_dir + newname local url_path = url_prefix + path local absolute_path = absolute_dir + newname -- write file to disk local fd = io.open(absolute_path, "wb") fd:write(body) fd:close() return newname, path, url_path, absolute_path end local Upload = Model:extend { __tag = 'Bamboo.Model.Upload'; __name = 'Upload'; __desc = "User's upload files."; __fields = { ['name'] = {}, ['path'] = {}, ['url_path'] = {}, ['absolute_path'] = {}, ['size'] = {}, ['timestamp'] = {}, ['desc'] = {}, }; init = function (self, t) if not t then return self end self.name = t.name or self.name self.path = t.path self.url_path = 'media/uploads/' + t.path self.absolute_path = absoluteDirPrefix() + t.path self.size = posix.stat(self.absolute_path).size self.timestamp = os.time() -- according the current design, desc field is nil self.desc = t.desc or '' return self end; --- For traditional Html4 form upload -- batch = function (self, req, params, dest_dir, prefix, postfix) I_AM_CLASS(self) local file_objs = List() -- file data are stored as arraies in params for i, v in ipairs(params) do local name, path, url_path, absolute_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not absolute_path or not name then return nil end -- create file instance local file_instance = self { name = name, path = path } if file_instance then -- store to db file_instance:save() file_objs:append(file_instance) end end -- a file object list return file_objs end; process = function (self, web, req, dest_dir, prefix, postfix) I_AM_CLASS(self) assert(web, '[ERROR] Upload input parameter: "web" must be not nil.') assert(req, '[ERROR] Upload input parameter: "req" must be not nil.') -- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately if req.headers['x-mongrel2-upload-start'] then print('return blank to abort upload.') web.conn:reply(req, '') return nil, 'Uploading file is too large.' end -- if upload in html5 way if req.headers['x-requested-with'] then -- stored to disk local name, path, url_path, absolute_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix } if not absolute_path or not name then return nil, '[ERROR] empty file.' end local file_instance = self { name = name, path = path } if file_instance then file_instance:save() return file_instance, 'single' end else -- for uploading in html4 way local params = Form:parse(req) local files = self:batch ( req, params, dest_dir, prefix, postfix ) if not files then return nil, '[ERROR] empty file.' end if #files == 1 then -- even only one file upload, batch function will return a list return files[1], 'single' else return files, 'multiple' end end end; calcNewFilename = function (self, dest_dir, oldname) return calcNewFilename(dest_dir, oldname) end; absoluteDirPrefix = function (self) return absoluteDirPrefix() end; -- this function, encorage override by child model, to execute their own delete action specDelete = function (self) I_AM_INSTANCE() -- remove file from disk os.execute('rm ' + self.absolute_path) return self end; } return Upload
Fix Upload interal errors. ;(
Fix Upload interal errors. ;( Now, you can use: Upload { name = 'xxx', path = 'xxx', ... = ... } to create a file object. Signed-off-by: Daogang Tang <6435653d2db08e7863743a16df53ecbb301fb4b0@gmail.com>
Lua
bsd-3-clause
daogangtang/bamboo,daogangtang/bamboo
f1a508a6c61d64623f40d5274eee3bdbb6353d28
inputters/base.lua
inputters/base.lua
local _deprecated = [[ You appear to be using a document class '%s' programmed for SILE <= v0.12.5. This system was refactored in v0.13.0 and the shims trying to make it work temporarily without refactoring your classes have been removed in v0.14.0. Please see v0.13.0 release notes for help. ]] local inputter = pl.class() inputter.type = "inputter" inputter._name = "base" inputter._docclass = nil function inputter:_init (options) if options then self.options = options end end function inputter:classInit (options) options = pl.tablex.merge(options, SILE.input.options, true) local constructor, class if SILE.scratch.class_from_uses then constructor = SILE.scratch.class_from_uses class = constructor._name end class = SILE.input.class or class or options.class or "plain" options.class = nil -- don't pass already consumed class option to contstructor constructor = self._docclass or constructor or SILE.require(class, "classes", true) if constructor.id then SU.deprecated("std.object", "pl.class", "0.13.0", "0.14.0", string.format(_deprecated, constructor.id)) end SILE.documentState.documentClass = constructor(options) end function inputter:requireClass (tree) local root = SILE.documentState.documentClass == nil if root then if #tree ~= 1 or (tree[1].command ~= "sile" and tree[1].command ~= "document") then SU.error("This isn't a SILE document!") end self:classInit(tree[1].options or {}) self:preamble() end end function inputter:process (doc) local tree = self:parse(doc) self:requireClass(tree) return SILE.process(tree) end -- Just a simple one-level find. We're not reimplementing XPath here. function inputter.findInTree (_, tree, command) for i=1, #tree do if type(tree[i]) == "table" and tree[i].command == command then return tree[i] end end end local function process_ambles (ambles) for _, amble in ipairs(ambles) do if type(amble) == "string" then SILE.processFile(amble) elseif type(amble) == "function" then SU.warn("Passing functions as pre/postambles is not officially sactioned and may go away without being marked as a breaking change.") amble() elseif type(amble) == "table" then local options = {} if amble.pack then amble, options = amble.pack, amble.options end if amble.type == "package" then amble(options) else SILE.documentState.documentClass:initPackage(amble, options) end end end end function inputter.preamble (_) process_ambles(SILE.input.preambles) end function inputter.postamble (_) process_ambles(SILE.input.postambles) end return inputter
local _deprecated = [[ You appear to be using a document class '%s' programmed for SILE <= v0.12.5. This system was refactored in v0.13.0 and the shims trying to make it work temporarily without refactoring your classes have been removed in v0.14.0. Please see v0.13.0 release notes for help. ]] local inputter = pl.class() inputter.type = "inputter" inputter._name = "base" inputter._docclass = nil function inputter:_init (options) if options then self.options = options end end function inputter:classInit (options) options = pl.tablex.merge(options, SILE.input.options, true) local constructor, class if SILE.scratch.class_from_uses then constructor = SILE.scratch.class_from_uses class = constructor._name end class = SILE.input.class or class or options.class or "plain" options.class = nil -- don't pass already consumed class option to contstructor constructor = self._docclass or constructor or SILE.require(class, "classes", true) if constructor.id then SU.deprecated("std.object", "pl.class", "0.13.0", "0.14.0", string.format(_deprecated, constructor.id)) end SILE.documentState.documentClass = constructor(options) end function inputter:requireClass (tree) local root = SILE.documentState.documentClass == nil local document if root then for _, leaf in ipairs(tree) do if leaf.lno then if document then SU.error("Document has more than one parent node!") end if leaf.command == "sile" or leaf.command == "document" then document = leaf end end end if not document then SU.error("This isn't a SILE document!") end self:classInit(document.options or {}) self:preamble() end end function inputter:process (doc) local tree = self:parse(doc) self:requireClass(tree) return SILE.process(tree) end -- Just a simple one-level find. We're not reimplementing XPath here. function inputter.findInTree (_, tree, command) for i=1, #tree do if type(tree[i]) == "table" and tree[i].command == command then return tree[i] end end end local function process_ambles (ambles) for _, amble in ipairs(ambles) do if type(amble) == "string" then SILE.processFile(amble) elseif type(amble) == "function" then SU.warn("Passing functions as pre/postambles is not officially sactioned and may go away without being marked as a breaking change.") amble() elseif type(amble) == "table" then local options = {} if amble.pack then amble, options = amble.pack, amble.options end if amble.type == "package" then amble(options) else SILE.documentState.documentClass:initPackage(amble, options) end end end end function inputter.preamble (_) process_ambles(SILE.input.preambles) end function inputter.postamble (_) process_ambles(SILE.input.postambles) end return inputter
fix(inputters): Permit content outside of the document note, e.g. comments or blanks (#1596)
fix(inputters): Permit content outside of the document note, e.g. comments or blanks (#1596)
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
027e451b25dd984a2c7f67d6b7da5608e9e83881
hammerspoon/.hammerspoon/jumpcutselect.lua
hammerspoon/.hammerspoon/jumpcutselect.lua
-- Selector for jumpcut thingy local settings = require("hs.settings") local utils = require("utils") local mod = {} -- jumpcutselect function mod.jumpcutselect() function formatChoices(choices) choices = utils.reverse(choices) formattedChoices = hs.fnutils.imap(choices, function(result) return { ["text"] = utils.trim(result), } end) return formattedChoices end local copy = nil local current = hs.application.frontmostApplication() local copies = settings.get("so.meain.hs.jumpcut") or {} local choices = formatChoices(copies) local chooser = hs.chooser.new(function(choosen) if copy then copy:delete() end current:activate() hs.eventtap.keyStrokes(choosen) end) chooser:choices(formatChoices(copies)) copy = hs.hotkey.bind('', 'return', function() local id = chooser:selectedRow() local item = choices[id] if item then chooser:hide() hs.pasteboard.setContents(item) trimmed = utils.trim(item.text) settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed) hs.alert.show(trimmed, 1) else hs.alert.show("Nothing to copy", 1) end end) function updateChooser() local query = chooser:query() local filteredChoices = hs.fnutils.filter(copies, function(result) return string.match(result, query) end) chooser:choices(formatChoices(filteredChoices)) end chooser:queryChangedCallback(updateChooser) chooser:searchSubText(false) chooser:show() end function mod.registerDefaultBindings(mods, key) mods = mods or {"cmd", "alt", "ctrl"} key = key or "P" hs.hotkey.bind(mods, key, mod.jumpcutselect) end return mod
-- Selector for jumpcut thingy local settings = require("hs.settings") local utils = require("utils") local mod = {} -- jumpcutselect function mod.jumpcutselect() function formatChoices(choices) choices = utils.reverse(choices) formattedChoices = hs.fnutils.imap(choices, function(result) return { ["text"] = utils.trim(result), } end) return formattedChoices end local copy = nil local current = hs.application.frontmostApplication() local copies = settings.get("so.meain.hs.jumpcut") or {} local choices = formatChoices(copies) local chooser = hs.chooser.new(function(choosen) if copy then copy:delete() end current:activate() hs.eventtap.keyStrokes(choosen) end) chooser:choices(formatChoices(copies)) copy = hs.hotkey.bind('', 'return', function() local id = chooser:selectedRow() local item = choices[id] if item then chooser:hide() trimmed = utils.trim(item.text) hs.pasteboard.setContents(trimmed) settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed) hs.alert.show(trimmed, 1) -- hs.notify.show("Jumpcut","Text copied", trimmed) else hs.alert.show("Nothing to copy", 1) end end) function updateChooser() local query = chooser:query() local filteredChoices = hs.fnutils.filter(copies, function(result) return string.match(result, query) end) chooser:choices(formatChoices(filteredChoices)) end chooser:queryChangedCallback(updateChooser) chooser:searchSubText(false) chooser:show() end function mod.registerDefaultBindings(mods, key) mods = mods or {"cmd", "alt", "ctrl"} key = key or "P" hs.hotkey.bind(mods, key, mod.jumpcutselect) end return mod
[hammerspoon] bugfix in jumpcutselect
[hammerspoon] bugfix in jumpcutselect
Lua
mit
meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles
486ffc69b66b5b45b0178fd4a0ffddc7bca2f26c
scripts/game_flow.lua
scripts/game_flow.lua
local kernel = require 'dokidoki.kernel' local v2 = require 'dokidoki.v2' local blueprints = require 'blueprints' local the_game = require 'the_game' local LEFT = game.constants.screen_left local RIGHT = game.constants.screen_right local BOTTOM = game.constants.screen_bottom local TOP = game.constants.screen_top local CENTER = v2((LEFT + RIGHT) / 2, (TOP + BOTTOM) / 2) local RADIUS = 200 local POSITIONS = { false, {CENTER + v2.unit(math.pi) * RADIUS, CENTER + v2.unit(0) * RADIUS}, {CENTER + v2.unit(math.pi*5/6) * RADIUS, CENTER + v2.unit(math.pi*1/6) * RADIUS, CENTER + v2.unit(math.pi*9/6) * RADIUS}, {CENTER + v2.unit(math.pi*3/4) * RADIUS, CENTER + v2.unit(math.pi*1/4) * RADIUS, CENTER + v2.unit(math.pi*5/4) * RADIUS, CENTER + v2.unit(math.pi*7/4) * RADIUS} } local state = 'init' local selectors local function generate_positions(n) local positions = {} for i = 1, n do positions[#positions+1] = v2(math.cos(i/n), math.sin(i/n)) * 200 end return positions end function update() if state == 'init' then selectors = { game.actors.new(blueprints.selection_factory, {'transform', pos=v2(LEFT + 200, TOP - 200)}, {'selector', player=1}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(RIGHT - 200, TOP - 200), facing=v2(-1, 0)}, {'selector', player=2}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(LEFT + 200, BOTTOM + 200)}, {'selector', player=3}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(RIGHT - 200, BOTTOM + 200), facing=v2(-1, 0)}, {'selector', player=4}) } state = 'player_select' elseif state == 'player_select' then if game.keyboard.key_pressed(string.byte('S')) then local players = {} for i, selector in ipairs(selectors) do selector.dead = true if selector.selector.picked then players[#players+1] = i end end local positions = generate_positions(#players) for i, p in ipairs(players) do local pos = POSITIONS[#players][i] local facing = v2.rotate90(pos - CENTER) game.actors.new(blueprints.easy_enemy_factory, {'transform', pos=pos, facing=facing}, {'ship', player=p}) end state = 'in_game' end elseif state == 'in_game' then if #game.actors.get('factory') < 2 then kernel.switch_scene(the_game.make()) end else error 'invalid state' end end
local kernel = require 'dokidoki.kernel' local v2 = require 'dokidoki.v2' local blueprints = require 'blueprints' local the_game = require 'the_game' local LEFT = game.constants.screen_left local RIGHT = game.constants.screen_right local BOTTOM = game.constants.screen_bottom local TOP = game.constants.screen_top local CENTER = v2((LEFT + RIGHT) / 2, (TOP + BOTTOM) / 2) local RADIUS = 200 local POSITIONS = { false, {CENTER + v2.unit(math.pi) * RADIUS, CENTER + v2.unit(0) * RADIUS}, {CENTER + v2.unit(math.pi*5/6) * RADIUS, CENTER + v2.unit(math.pi*1/6) * RADIUS, CENTER + v2.unit(math.pi*9/6) * RADIUS}, {CENTER + v2.unit(math.pi*3/4) * RADIUS, CENTER + v2.unit(math.pi*1/4) * RADIUS, CENTER + v2.unit(math.pi*5/4) * RADIUS, CENTER + v2.unit(math.pi*7/4) * RADIUS} } local state = 'init' local selectors local function generate_positions(n) local positions = {} for i = 1, n do positions[#positions+1] = v2(math.cos(i/n), math.sin(i/n)) * 200 end return positions end function update() if state == 'init' then selectors = { game.actors.new(blueprints.selection_factory, {'transform', pos=v2(LEFT + 200, TOP - 200)}, {'selector', player=1}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(RIGHT - 200, TOP - 200), facing=v2(-1, 0)}, {'selector', player=2}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(LEFT + 200, BOTTOM + 200)}, {'selector', player=3}), game.actors.new(blueprints.selection_factory, {'transform', pos=v2(RIGHT - 200, BOTTOM + 200), facing=v2(-1, 0)}, {'selector', player=4}) } state = 'player_select' elseif state == 'player_select' then if game.keyboard.key_pressed(string.byte('S')) then local players = {} for i, selector in ipairs(selectors) do if selector.selector.picked then players[#players+1] = i end end if #players > 0 then for i, selector in ipairs(selectors) do selector.dead = true end local cpu_player if #players == 1 then cpu_player = players[1] == 1 and 2 or 1 players[#players+1] = cpu_player end local positions = generate_positions(#players) for i, p in ipairs(players) do local pos = POSITIONS[#players][i] local facing = v2.norm(v2.rotate90(pos - CENTER)) if p == cpu_player then game.actors.new(blueprints.easy_enemy_factory, {'transform', pos=pos, facing=facing}, {'ship', player=p}) else game.actors.new(blueprints.player_factory, {'transform', pos=pos, facing=facing}, {'ship', player=p}) end end state = 'in_game' end end elseif state == 'in_game' then if #game.actors.get('factory') < 2 then kernel.switch_scene(the_game.make()) end else error 'invalid state' end end
added computer player, fixed facing bug
added computer player, fixed facing bug
Lua
mit
henkboom/pax-britannica
1b81716cad28eb02ed1c0b82f8403be20d64d7ae
src/ragdoll/src/Server/Classes/UnragdollAutomatically.lua
src/ragdoll/src/Server/Classes/UnragdollAutomatically.lua
--[=[ When a humanoid is tagged with this, it will unragdoll automatically. @server @class UnragdollAutomatically ]=] local require = require(script.Parent.loader).load(script) local RunService = game:GetService("RunService") local BaseObject = require("BaseObject") local RagdollBindersServer = require("RagdollBindersServer") local CharacterUtils = require("CharacterUtils") local AttributeValue = require("AttributeValue") local Maid = require("Maid") local UnragdollAutomaticallyConstants = require("UnragdollAutomaticallyConstants") local cancellableDelay = require("cancellableDelay") local Observable = require("Observable") local Rx = require("Rx") local RxInstanceUtils = require("RxInstanceUtils") local UnragdollAutomatically = setmetatable({}, BaseObject) UnragdollAutomatically.ClassName = "UnragdollAutomatically" UnragdollAutomatically.__index = UnragdollAutomatically --[=[ Constructs a new UnragdollAutomatically. Should be done via [Binder]. See [RagdollBindersServer]. @param humanoid Humanoid @param serviceBag ServiceBag @return UnragdollAutomatically ]=] function UnragdollAutomatically.new(humanoid, serviceBag) local self = setmetatable(BaseObject.new(humanoid), UnragdollAutomatically) self._ragdollBindersServer = serviceBag:GetService(RagdollBindersServer) self._player = CharacterUtils.getPlayerFromCharacter(self._obj) self._unragdollAutomatically = AttributeValue.new(self._obj, UnragdollAutomaticallyConstants.UNRAGDOLL_AUTOMATICALLY_ATTRIBUTE, true) self._unragdollAutomaticTime = AttributeValue.new(self._obj, UnragdollAutomaticallyConstants.UNRAGDOLL_AUTOMATIC_TIME_ATTRIBUTE, 5) self._maid:GiveTask(self._ragdollBindersServer.Ragdoll:ObserveInstance(self._obj, function() self:_handleRagdollChanged(self._maid) end)) self:_handleRagdollChanged(self._maid) return self end function UnragdollAutomatically:_handleRagdollChanged(maid) if self._ragdollBindersServer.Ragdoll:Get(self._obj) then maid._unragdoll = self:_observeCanUnragdollTimer():Pipe({ Rx.switchMap(function(state) if state then return self:_observeAlive() else return Rx.of(false); end end); Rx.distinct(); }):Subscribe(function(canUnragdoll) if canUnragdoll then self._ragdollBindersServer.Ragdoll:Unbind(self._obj) end end) else maid._unragdoll = nil end end function UnragdollAutomatically:_observeAlive() return RxInstanceUtils.observeProperty(self._obj, "Health"):Pipe({ Rx.map(function(health) return health > 0 end); Rx.distinct(); }) end function UnragdollAutomatically:_observeCanUnragdollTimer() return Observable.new(function(sub) local maid = Maid.new() local startTime = os.clock() local isReady = Instance.new("BoolValue") isReady.Value = false maid:GiveTask(isReady) maid:GiveTask(Rx.combineLatest({ enabled = self._unragdollAutomatically:Observe(); time = self._unragdollAutomaticTime:Observe(); }):Subscribe(function(state) if state.enabled then maid._deferred = nil local timeElapsed = os.clock() - startTime local remainingTime = state.time - timeElapsed if remainingTime <= 0 then isReady.Value = true else isReady.Value = false maid._deferred = cancellableDelay(remainingTime, function() isReady.Value = true end) end else isReady.Value = false maid._deferred = nil end end)) maid:GiveTask(isReady.Changed:Connect(function() sub:Fire(isReady.Value) end)) sub:Fire(isReady.Value) return maid end) end return UnragdollAutomatically
--[=[ When a humanoid is tagged with this, it will unragdoll automatically. @server @class UnragdollAutomatically ]=] local require = require(script.Parent.loader).load(script) local BaseObject = require("BaseObject") local RagdollBindersServer = require("RagdollBindersServer") local CharacterUtils = require("CharacterUtils") local AttributeValue = require("AttributeValue") local Maid = require("Maid") local UnragdollAutomaticallyConstants = require("UnragdollAutomaticallyConstants") local cancellableDelay = require("cancellableDelay") local Observable = require("Observable") local Rx = require("Rx") local RxInstanceUtils = require("RxInstanceUtils") local UnragdollAutomatically = setmetatable({}, BaseObject) UnragdollAutomatically.ClassName = "UnragdollAutomatically" UnragdollAutomatically.__index = UnragdollAutomatically --[=[ Constructs a new UnragdollAutomatically. Should be done via [Binder]. See [RagdollBindersServer]. @param humanoid Humanoid @param serviceBag ServiceBag @return UnragdollAutomatically ]=] function UnragdollAutomatically.new(humanoid, serviceBag) local self = setmetatable(BaseObject.new(humanoid), UnragdollAutomatically) self._ragdollBindersServer = serviceBag:GetService(RagdollBindersServer) self._player = CharacterUtils.getPlayerFromCharacter(self._obj) self._unragdollAutomatically = AttributeValue.new(self._obj, UnragdollAutomaticallyConstants.UNRAGDOLL_AUTOMATICALLY_ATTRIBUTE, true) self._unragdollAutomaticTime = AttributeValue.new(self._obj, UnragdollAutomaticallyConstants.UNRAGDOLL_AUTOMATIC_TIME_ATTRIBUTE, 5) self._maid:GiveTask(self._ragdollBindersServer.Ragdoll:ObserveInstance(self._obj, function() self:_handleRagdollChanged(self._maid) end)) self:_handleRagdollChanged(self._maid) return self end function UnragdollAutomatically:_handleRagdollChanged(maid) if self._ragdollBindersServer.Ragdoll:Get(self._obj) then maid._unragdoll = self:_observeCanUnragdollTimer():Pipe({ Rx.switchMap(function(state) if state then return self:_observeAlive() else return Rx.of(false); end end); Rx.distinct(); }):Subscribe(function(canUnragdoll) if canUnragdoll then self._ragdollBindersServer.Ragdoll:Unbind(self._obj) end end) else maid._unragdoll = nil end end function UnragdollAutomatically:_observeAlive() return RxInstanceUtils.observeProperty(self._obj, "Health"):Pipe({ Rx.map(function(health) return health > 0 end); Rx.distinct(); }) end function UnragdollAutomatically:_observeCanUnragdollTimer() return Observable.new(function(sub) local maid = Maid.new() local startTime = os.clock() local isReady = Instance.new("BoolValue") isReady.Value = false maid:GiveTask(isReady) maid:GiveTask(Rx.combineLatest({ enabled = self._unragdollAutomatically:Observe(); time = self._unragdollAutomaticTime:Observe(); }):Subscribe(function(state) if state.enabled then maid._deferred = nil local timeElapsed = os.clock() - startTime local remainingTime = state.time - timeElapsed if remainingTime <= 0 then isReady.Value = true else isReady.Value = false maid._deferred = cancellableDelay(remainingTime, function() isReady.Value = true end) end else isReady.Value = false maid._deferred = nil end end)) maid:GiveTask(isReady.Changed:Connect(function() sub:Fire(isReady.Value) end)) sub:Fire(isReady.Value) return maid end) end return UnragdollAutomatically
fix: Remove unneeded RunService call
fix: Remove unneeded RunService call
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
23c4f5600a38c7ff8f3053d11dcf2766cdd92d2f
kong/cmd/start.lua
kong/cmd/start.lua
local dnsmasq_signals = require "kong.cmd.utils.dnsmasq_signals" local prefix_handler = require "kong.cmd.utils.prefix_handler" local nginx_signals = require "kong.cmd.utils.nginx_signals" local serf_signals = require "kong.cmd.utils.serf_signals" local conf_loader = require "kong.conf_loader" local DAOFactory = require "kong.dao.factory" local log = require "kong.cmd.utils.log" local function execute(args) local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) local dao = DAOFactory(conf) local err xpcall(function() assert(dao:run_migrations()) assert(prefix_handler.prepare_prefix(conf, args.nginx_conf)) if conf.dnsmasq then assert(dnsmasq_signals.start(conf)) end assert(serf_signals.start(conf, dao)) assert(nginx_signals.start(conf)) log("Kong started") end, function(e) log.verbose("could not start Kong, stopping services") nginx_signals.stop(conf) serf_signals.stop(conf, dao) if conf.dnsmasq then dnsmasq_signals.stop(conf) end err = e -- cannot throw from this function log.verbose("stopped services") end) if err then error(err) -- report to main error handler end end local lapp = [[ Usage: kong start [OPTIONS] Start Kong (Nginx and other configured services) in the configured prefix directory. Options: -c,--conf (optional string) configuration file -p,--prefix (optional string) override prefix directory --nginx-conf (optional string) custom Nginx configuration template ]] return { lapp = lapp, execute = execute }
local dnsmasq_signals = require "kong.cmd.utils.dnsmasq_signals" local prefix_handler = require "kong.cmd.utils.prefix_handler" local nginx_signals = require "kong.cmd.utils.nginx_signals" local serf_signals = require "kong.cmd.utils.serf_signals" local conf_loader = require "kong.conf_loader" local DAOFactory = require "kong.dao.factory" local log = require "kong.cmd.utils.log" local function execute(args) local conf = assert(conf_loader(args.conf, { prefix = args.prefix })) local dao = DAOFactory(conf) local err xpcall(function() assert(prefix_handler.prepare_prefix(conf, args.nginx_conf)) assert(dao:run_migrations()) if conf.dnsmasq then assert(dnsmasq_signals.start(conf)) end assert(serf_signals.start(conf, dao)) assert(nginx_signals.start(conf)) log("Kong started") end, function(e) log.verbose("could not start Kong, stopping services") pcall(nginx_signals.stop(conf)) pcall(serf_signals.stop(conf, dao)) if conf.dnsmasq then pcall(dnsmasq_signals.stop(conf)) end err = e -- cannot throw from this function log.verbose("stopped services") end) if err then error(err) -- report to main error handler end end local lapp = [[ Usage: kong start [OPTIONS] Start Kong (Nginx and other configured services) in the configured prefix directory. Options: -c,--conf (optional string) configuration file -p,--prefix (optional string) override prefix directory --nginx-conf (optional string) custom Nginx configuration template ]] return { lapp = lapp, execute = execute }
fix(cli) prevent xpcall handler to crash
fix(cli) prevent xpcall handler to crash serf_signals.stop() would eventually crash and prevent execution of the following code, thus we would not report the actual crashing reason to the user (silent kong start failure)
Lua
apache-2.0
Vermeille/kong,jebenexer/kong,beauli/kong,akh00/kong,Mashape/kong,Kong/kong,Kong/kong,li-wl/kong,salazar/kong,shiprabehera/kong,jerizm/kong,icyxp/kong,ccyphers/kong,Kong/kong
08b9e4f82f0109e5d1019cd32b57be134739e596
src/core/counter.lua
src/core/counter.lua
-- counter.lua - Count discrete events for diagnostic purposes -- -- This module provides a thin layer for representing 64-bit counters -- as shared memory objects. -- -- Counters let you efficiently count discrete events (packet drops, -- etc) and are accessible as shared memory from other processes such -- as monitoring tools. Counters hold 64-bit unsigned integers. -- -- Use counters to make troubleshooting easier. For example, if there -- are several reasons that an app could drop a packet then you can -- use counters to keep track of why this is actually happening. -- -- You can access the counters using this module, or the raw core.shm -- module, or even directly on disk. Each counter is an 8-byte ramdisk -- file that contains the 64-bit value in native host endian. -- -- For example, you can read a counter on the command line with od(1): -- -- # od -A none -t u8 /var/run/snabb/15347/counter/a -- 43 module(..., package.seeall) local shm = require("core.shm") local ffi = require("ffi") require("core.counter_h") local counter_t = ffi.typeof("struct counter") -- Double buffering: -- For each counter we have a private copy to update directly and then -- a public copy in shared memory that we periodically commit to. -- -- This is important for a subtle performance reason: the shared -- memory counters all have page-aligned addresses (thanks to mmap) -- and accessing many of them can lead to expensive cache misses (due -- to set-associative CPU cache). See SnabbCo/snabbswitch#558. local public = {} local private = {} local numbers = {} -- name -> number function open (name, readonly) if numbers[name] then error("counter already opened: " .. name) end local n = #public+1 numbers[name] = n public[n] = shm.map(name, counter_t, readonly) if readonly then private[n] = public[#public] -- use counter directly else private[n] = ffi.new(counter_t) end return private[n] end function delete (name) local ptr = public[numbers[name]] if not ptr then error("counter not found for deletion: " .. name) end -- Free shm object shm.unmap(ptr) shm.unlink(name) -- Free local state numbers[name] = false public[ptr] = false private[ptr] = false end -- Copy counter private counter values to public shared memory. function commit () for i = 1, #public do if public[i] ~= private[i] then public[i].c = private[i].c end end end function set (counter, value) counter.c = value end function add (counter, value) counter.c = counter.c + (value or 1) end function read (counter) return counter.c end function selftest () print("selftest: core.counter") local a = open("core.counter/counter/a") local b = open("core.counter/counter/b") local a2 = shm.map("core.counter/counter/a", counter_t, true) set(a, 42) set(b, 43) assert(read(a) == 42) assert(read(b) == 43) commit() assert(read(a) == a2.c) add(a, 1) assert(read(a) == 43) commit() assert(read(a) == a2.c) shm.unlink("core.counter") print("selftest ok") end
-- counter.lua - Count discrete events for diagnostic purposes -- -- This module provides a thin layer for representing 64-bit counters -- as shared memory objects. -- -- Counters let you efficiently count discrete events (packet drops, -- etc) and are accessible as shared memory from other processes such -- as monitoring tools. Counters hold 64-bit unsigned integers. -- -- Use counters to make troubleshooting easier. For example, if there -- are several reasons that an app could drop a packet then you can -- use counters to keep track of why this is actually happening. -- -- You can access the counters using this module, or the raw core.shm -- module, or even directly on disk. Each counter is an 8-byte ramdisk -- file that contains the 64-bit value in native host endian. -- -- For example, you can read a counter on the command line with od(1): -- -- # od -A none -t u8 /var/run/snabb/15347/counter/a -- 43 module(..., package.seeall) local shm = require("core.shm") local ffi = require("ffi") require("core.counter_h") local counter_t = ffi.typeof("struct counter") -- Double buffering: -- For each counter we have a private copy to update directly and then -- a public copy in shared memory that we periodically commit to. -- -- This is important for a subtle performance reason: the shared -- memory counters all have page-aligned addresses (thanks to mmap) -- and accessing many of them can lead to expensive cache misses (due -- to set-associative CPU cache). See SnabbCo/snabbswitch#558. local public = {} local private = {} local numbers = {} -- name -> number function open (name, readonly) if numbers[name] then error("counter already opened: " .. name) end local n = #public+1 numbers[name] = n public[n] = shm.map(name, counter_t, readonly) if readonly then private[n] = public[#public] -- use counter directly else private[n] = ffi.new(counter_t) end return private[n] end function delete (name) local number = numbers[name] if not number then error("counter not found for deletion: " .. name) end -- Free shm object shm.unmap(public[number]) shm.unlink(name) -- Free local state numbers[name] = false public[number] = false private[number] = false end -- Copy counter private counter values to public shared memory. function commit () for i = 1, #public do if public[i] ~= private[i] then public[i].c = private[i].c end end end function set (counter, value) counter.c = value end function add (counter, value) counter.c = counter.c + (value or 1) end function read (counter) return counter.c end function selftest () print("selftest: core.counter") local a = open("core.counter/counter/a") local b = open("core.counter/counter/b") local a2 = shm.map("core.counter/counter/a", counter_t, true) set(a, 42) set(b, 43) assert(read(a) == 42) assert(read(b) == 43) commit() assert(read(a) == a2.c) add(a, 1) assert(read(a) == 43) commit() assert(read(a) == a2.c) shm.unlink("core.counter") print("selftest ok") end
[core.counter] Fix bug in counter.delete where it failed to mark public/private record as deleted.
[core.counter] Fix bug in counter.delete where it failed to mark public/private record as deleted.
Lua
apache-2.0
eugeneia/snabb,Igalia/snabb,Igalia/snabb,pirate/snabbswitch,kbara/snabb,heryii/snabb,snabbco/snabb,dpino/snabb,aperezdc/snabbswitch,pavel-odintsov/snabbswitch,wingo/snabbswitch,eugeneia/snabb,Igalia/snabb,fhanik/snabbswitch,wingo/snabbswitch,snabbco/snabb,plajjan/snabbswitch,kbara/snabb,alexandergall/snabbswitch,kbara/snabb,andywingo/snabbswitch,snabbco/snabb,wingo/snabb,justincormack/snabbswitch,wingo/snabb,eugeneia/snabb,lukego/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,snabbnfv-goodies/snabbswitch,eugeneia/snabb,wingo/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,mixflowtech/logsensor,dpino/snabb,heryii/snabb,Igalia/snabb,justincormack/snabbswitch,dpino/snabb,hb9cwp/snabbswitch,pavel-odintsov/snabbswitch,andywingo/snabbswitch,wingo/snabb,heryii/snabb,alexandergall/snabbswitch,dpino/snabb,kbara/snabb,lukego/snabbswitch,dpino/snabbswitch,fhanik/snabbswitch,aperezdc/snabbswitch,mixflowtech/logsensor,plajjan/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dwdm/snabbswitch,hb9cwp/snabbswitch,lukego/snabb,Igalia/snabb,fhanik/snabbswitch,Igalia/snabb,lukego/snabbswitch,lukego/snabbswitch,kbara/snabb,snabbco/snabb,lukego/snabb,alexandergall/snabbswitch,kellabyte/snabbswitch,Igalia/snabbswitch,kellabyte/snabbswitch,wingo/snabb,dpino/snabb,mixflowtech/logsensor,dpino/snabb,dpino/snabb,pirate/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,pirate/snabbswitch,mixflowtech/logsensor,justincormack/snabbswitch,plajjan/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,hb9cwp/snabbswitch,andywingo/snabbswitch,Igalia/snabbswitch,wingo/snabb,hb9cwp/snabbswitch,wingo/snabbswitch,lukego/snabb,eugeneia/snabbswitch,Igalia/snabb,xdel/snabbswitch,lukego/snabbswitch,snabbco/snabb,xdel/snabbswitch,snabbco/snabb,eugeneia/snabb,kbara/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,kellabyte/snabbswitch,wingo/snabbswitch,snabbnfv-goodies/snabbswitch,plajjan/snabbswitch,dpino/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,mixflowtech/logsensor,xdel/snabbswitch,eugeneia/snabb,aperezdc/snabbswitch,justincormack/snabbswitch,heryii/snabb,heryii/snabb,dwdm/snabbswitch,pavel-odintsov/snabbswitch,andywingo/snabbswitch
63e023e56adfa13255ff792c0df52b3623eed7a7
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 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("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-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", translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"), translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " .. "members can automatically receive their network settings (<abbr title=" .. "\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " .. "System\">DNS</abbr>-server, ...).")) 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", translate("Leasetime")).rmempty = true local dd = s:option(Flag, "dynamicdhcp", translate("dynamic")) 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", translate("Ignore interface"), translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " .. "this interface")) ignore.optional = true s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true s:option(Flag, "force", translate("Force")).optional = true s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true for i, n in ipairs(s.children) do if n ~= iface and n ~= ignore then n:depends("ignore", "") end end return m
modules/admin-full: fix dhcp page
modules/admin-full: fix dhcp page
Lua
apache-2.0
thesabbir/luci,kuoruan/luci,LuttyYang/luci,teslamint/luci,wongsyrone/luci-1,MinFu/luci,Noltari/luci,schidler/ionic-luci,fkooman/luci,openwrt-es/openwrt-luci,ff94315/luci-1,981213/luci-1,chris5560/openwrt-luci,slayerrensky/luci,fkooman/luci,thesabbir/luci,nwf/openwrt-luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,obsy/luci,aa65535/luci,taiha/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,cshore/luci,openwrt-es/openwrt-luci,thesabbir/luci,Hostle/luci,zhaoxx063/luci,nwf/openwrt-luci,kuoruan/luci,maxrio/luci981213,teslamint/luci,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,bittorf/luci,lcf258/openwrtcn,palmettos/cnLuCI,schidler/ionic-luci,teslamint/luci,Wedmer/luci,marcel-sch/luci,thess/OpenWrt-luci,palmettos/test,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,sujeet14108/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,obsy/luci,RuiChen1113/luci,kuoruan/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,jlopenwrtluci/luci,david-xiao/luci,lcf258/openwrtcn,opentechinstitute/luci,NeoRaider/luci,sujeet14108/luci,mumuqz/luci,sujeet14108/luci,david-xiao/luci,thesabbir/luci,RuiChen1113/luci,ollie27/openwrt_luci,palmettos/test,cshore/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,male-puppies/luci,jorgifumi/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,dwmw2/luci,wongsyrone/luci-1,Kyklas/luci-proto-hso,RuiChen1113/luci,jorgifumi/luci,nmav/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,aa65535/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,schidler/ionic-luci,thess/OpenWrt-luci,LuttyYang/luci,nwf/openwrt-luci,Wedmer/luci,Hostle/luci,keyidadi/luci,cappiewu/luci,keyidadi/luci,maxrio/luci981213,kuoruan/luci,florian-shellfire/luci,cappiewu/luci,thess/OpenWrt-luci,florian-shellfire/luci,palmettos/cnLuCI,thesabbir/luci,dismantl/luci-0.12,slayerrensky/luci,nmav/luci,rogerpueyo/luci,hnyman/luci,schidler/ionic-luci,david-xiao/luci,kuoruan/luci,tcatm/luci,keyidadi/luci,NeoRaider/luci,palmettos/test,dwmw2/luci,bright-things/ionic-luci,maxrio/luci981213,cshore/luci,bittorf/luci,hnyman/luci,deepak78/new-luci,thess/OpenWrt-luci,slayerrensky/luci,joaofvieira/luci,bright-things/ionic-luci,lcf258/openwrtcn,aa65535/luci,cshore-firmware/openwrt-luci,Hostle/luci,kuoruan/luci,keyidadi/luci,david-xiao/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,fkooman/luci,fkooman/luci,deepak78/new-luci,taiha/luci,nmav/luci,lbthomsen/openwrt-luci,urueedi/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,rogerpueyo/luci,cshore/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,chris5560/openwrt-luci,artynet/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,fkooman/luci,openwrt/luci,harveyhu2012/luci,dismantl/luci-0.12,thesabbir/luci,thess/OpenWrt-luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,RedSnake64/openwrt-luci-packages,urueedi/luci,tcatm/luci,981213/luci-1,palmettos/test,openwrt/luci,harveyhu2012/luci,obsy/luci,tcatm/luci,opentechinstitute/luci,ff94315/luci-1,tobiaswaldvogel/luci,MinFu/luci,openwrt-es/openwrt-luci,harveyhu2012/luci,urueedi/luci,marcel-sch/luci,bright-things/ionic-luci,nmav/luci,jchuang1977/luci-1,joaofvieira/luci,palmettos/test,taiha/luci,cappiewu/luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,slayerrensky/luci,palmettos/test,Kyklas/luci-proto-hso,oyido/luci,hnyman/luci,artynet/luci,cshore-firmware/openwrt-luci,oyido/luci,Wedmer/luci,florian-shellfire/luci,chris5560/openwrt-luci,sujeet14108/luci,keyidadi/luci,Wedmer/luci,teslamint/luci,daofeng2015/luci,david-xiao/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,bright-things/ionic-luci,wongsyrone/luci-1,LuttyYang/luci,artynet/luci,male-puppies/luci,lcf258/openwrtcn,wongsyrone/luci-1,bittorf/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,nmav/luci,bright-things/ionic-luci,urueedi/luci,nwf/openwrt-luci,keyidadi/luci,shangjiyu/luci-with-extra,artynet/luci,obsy/luci,daofeng2015/luci,981213/luci-1,palmettos/cnLuCI,dwmw2/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,joaofvieira/luci,ollie27/openwrt_luci,oyido/luci,joaofvieira/luci,LuttyYang/luci,marcel-sch/luci,obsy/luci,openwrt/luci,aa65535/luci,harveyhu2012/luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,bittorf/luci,dismantl/luci-0.12,daofeng2015/luci,aircross/OpenWrt-Firefly-LuCI,taiha/luci,slayerrensky/luci,palmettos/cnLuCI,lcf258/openwrtcn,urueedi/luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,LuttyYang/luci,lcf258/openwrtcn,david-xiao/luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,jchuang1977/luci-1,zhaoxx063/luci,ff94315/luci-1,bittorf/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,fkooman/luci,shangjiyu/luci-with-extra,cshore/luci,schidler/ionic-luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,dwmw2/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,tcatm/luci,ff94315/luci-1,dwmw2/luci,oyido/luci,MinFu/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,palmettos/cnLuCI,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/luci,jchuang1977/luci-1,wongsyrone/luci-1,teslamint/luci,palmettos/test,opentechinstitute/luci,aa65535/luci,dismantl/luci-0.12,NeoRaider/luci,jorgifumi/luci,daofeng2015/luci,rogerpueyo/luci,MinFu/luci,dwmw2/luci,oyido/luci,forward619/luci,lcf258/openwrtcn,ollie27/openwrt_luci,tobiaswaldvogel/luci,deepak78/new-luci,ff94315/luci-1,981213/luci-1,openwrt-es/openwrt-luci,florian-shellfire/luci,chris5560/openwrt-luci,RuiChen1113/luci,remakeelectric/luci,artynet/luci,Hostle/luci,openwrt-es/openwrt-luci,Noltari/luci,jchuang1977/luci-1,jchuang1977/luci-1,forward619/luci,hnyman/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,hnyman/luci,oneru/luci,981213/luci-1,deepak78/new-luci,taiha/luci,marcel-sch/luci,981213/luci-1,RuiChen1113/luci,cshore/luci,kuoruan/luci,opentechinstitute/luci,cappiewu/luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,male-puppies/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,LuttyYang/luci,ff94315/luci-1,david-xiao/luci,obsy/luci,tcatm/luci,male-puppies/luci,harveyhu2012/luci,daofeng2015/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,schidler/ionic-luci,forward619/luci,nwf/openwrt-luci,jlopenwrtluci/luci,marcel-sch/luci,bittorf/luci,jlopenwrtluci/luci,zhaoxx063/luci,keyidadi/luci,artynet/luci,oneru/luci,remakeelectric/luci,cappiewu/luci,rogerpueyo/luci,dwmw2/luci,joaofvieira/luci,zhaoxx063/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,oneru/luci,shangjiyu/luci-with-extra,forward619/luci,Kyklas/luci-proto-hso,Hostle/luci,kuoruan/lede-luci,joaofvieira/luci,bittorf/luci,mumuqz/luci,mumuqz/luci,slayerrensky/luci,rogerpueyo/luci,mumuqz/luci,jlopenwrtluci/luci,kuoruan/lede-luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,wongsyrone/luci-1,jchuang1977/luci-1,harveyhu2012/luci,lbthomsen/openwrt-luci,Hostle/luci,marcel-sch/luci,jorgifumi/luci,sujeet14108/luci,hnyman/luci,Hostle/luci,marcel-sch/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,florian-shellfire/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,urueedi/luci,jlopenwrtluci/luci,openwrt/luci,openwrt-es/openwrt-luci,david-xiao/luci,Kyklas/luci-proto-hso,Wedmer/luci,Noltari/luci,Hostle/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,jorgifumi/luci,kuoruan/lede-luci,fkooman/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,MinFu/luci,obsy/luci,daofeng2015/luci,forward619/luci,oyido/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,remakeelectric/luci,cappiewu/luci,lcf258/openwrtcn,mumuqz/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,Sakura-Winkey/LuCI,rogerpueyo/luci,maxrio/luci981213,daofeng2015/luci,daofeng2015/luci,nmav/luci,oneru/luci,Noltari/luci,kuoruan/lede-luci,oneru/luci,slayerrensky/luci,jorgifumi/luci,NeoRaider/luci,bittorf/luci,thess/OpenWrt-luci,artynet/luci,urueedi/luci,maxrio/luci981213,jchuang1977/luci-1,male-puppies/luci,cshore-firmware/openwrt-luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,Noltari/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,jlopenwrtluci/luci,palmettos/test,openwrt/luci,MinFu/luci,keyidadi/luci,Wedmer/luci,mumuqz/luci,thess/OpenWrt-luci,maxrio/luci981213,cappiewu/luci,nmav/luci,remakeelectric/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,florian-shellfire/luci,forward619/luci,remakeelectric/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,sujeet14108/luci,Noltari/luci,florian-shellfire/luci,lcf258/openwrtcn,chris5560/openwrt-luci,Kyklas/luci-proto-hso,opentechinstitute/luci,openwrt/luci,openwrt/luci,Wedmer/luci,kuoruan/lede-luci,hnyman/luci,aa65535/luci,nmav/luci,chris5560/openwrt-luci,zhaoxx063/luci,aa65535/luci,Sakura-Winkey/LuCI,Noltari/luci,deepak78/new-luci,oneru/luci,teslamint/luci,nwf/openwrt-luci,tobiaswaldvogel/luci,NeoRaider/luci,maxrio/luci981213,deepak78/new-luci,chris5560/openwrt-luci,male-puppies/luci,jorgifumi/luci,taiha/luci,taiha/luci,deepak78/new-luci,RuiChen1113/luci,jlopenwrtluci/luci,taiha/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,male-puppies/luci,dwmw2/luci,tcatm/luci,zhaoxx063/luci,nwf/openwrt-luci,tcatm/luci,lbthomsen/openwrt-luci,remakeelectric/luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,dismantl/luci-0.12,MinFu/luci,remakeelectric/luci,bright-things/ionic-luci,openwrt/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,marcel-sch/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,thesabbir/luci,lbthomsen/openwrt-luci,oyido/luci,sujeet14108/luci,oyido/luci,kuoruan/lede-luci,NeoRaider/luci
e948324422824a0431d3058c7cd255b70f993c87
Assets/ToLua/Lua/event.lua
Assets/ToLua/Lua/event.lua
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) topameng@gmail.com -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local setmetatable = setmetatable local xpcall = xpcall local pcall = pcall local assert = assert local rawget = rawget local error = error local print = print local traceback = tolua.traceback local ilist = ilist local _xpcall = {} _xpcall.__call = function(self, ...) if jit then if nil == self.obj then return xpcall(self.func, traceback, ...) else return xpcall(self.func, traceback, self.obj, ...) end else local args = {...} if nil == self.obj then local func = function() self.func(unpack(args)) end return xpcall(func, traceback) else local func = function() self.func(self.obj, unpack(args)) end return xpcall(func, traceback) end end end _xpcall.__eq = function(lhs, rhs) return lhs.func == rhs.func and lhs.obj == rhs.obj end local function xfunctor(func, obj) return setmetatable({func = func, obj = obj}, _xpcall) end local _pcall = {} _pcall.__call = function(self, ...) if nil == self.obj then return pcall(self.func, ...) else return pcall(self.func, self.obj, ...) end end _pcall.__eq = function(lhs, rhs) return lhs.func == rhs.func and lhs.obj == rhs.obj end local function functor(func, obj) return setmetatable({func = func, obj = obj}, _pcall) end local _event = {} _event.__index = _event --废弃 function _event:Add(func, obj) assert(func) if self.keepSafe then func = xfunctor(func, obj) else func = functor(func, obj) end if self.lock then local node = {value = func, _prev = 0, _next = 0} table.insert(self.opList, node) node.op = list.pushnode return node else return self.list:push(func) end end --废弃 function _event:Remove(func, obj) for i, v in ilist(self.list) do if v.func == func and v.obj == obj then if self.lock and self.current ~= i then table.insert(self.opList, i) node.op = list.remove else self.list:remove(i) end break end end end function _event:CreateListener(func, obj) if self.keepSafe then func = xfunctor(func, obj) else func = functor(func, obj) end return {value = func, _prev = 0, _next = 0, removed = true} end function _event:AddListener(handle) if not handle.removed then return false end if self.lock then table.insert(self.opList, handle) handle.op = list.pushnode else self.list:pushnode(handle) end return true end function _event:RemoveListener(handle) if handle.removed then return false end if self.lock and self.current ~= handle then table.insert(self.opList, handle) handle.op = list.remove else self.list:remove(handle) end return true end function _event:Count() return self.list.length end function _event:Clear() self.list:clear() self.opList = {} self.lock = false self.keepSafe = false self.current = nil end function _event:Dump() local count = 0 for _, v in ilist(self.list) do if v.obj then print("update function:", v.func, "object name:", v.obj.name) else print("update function: ", v.func) end count = count + 1 end print("all function is:", count) end _event.__call = function(self, ...) local _list = self.list self.lock = true local ilist = ilist for i, f in ilist(_list) do self.current = i local flag, msg = f(...) if not flag then if self.keepSafe then _list:remove(i) end self.lock = false error(msg) end end for _, i in ipairs(self.opList) do i.op(_list, i) end self.lock = false self.opList = {} end function event(name, safe) safe = safe or false return setmetatable({name = name, keepSafe = safe, lock = false, opList = {}, list = list:new()}, _event) end UpdateBeat = event("Update", true) LateUpdateBeat = event("LateUpdate", true) FixedUpdateBeat = event("FixedUpdate", true) CoUpdateBeat = event("CoUpdate") --只在协同使用 local Time = Time local UpdateBeat = UpdateBeat local LateUpdateBeat = LateUpdateBeat local FixedUpdateBeat = FixedUpdateBeat local CoUpdateBeat = CoUpdateBeat --逻辑update function Update(deltaTime, unscaledDeltaTime) Time:SetDeltaTime(deltaTime, unscaledDeltaTime) UpdateBeat() end function LateUpdate() LateUpdateBeat() CoUpdateBeat() Time:SetFrameCount() end --物理update function FixedUpdate(fixedDeltaTime) Time:SetFixedDelta(fixedDeltaTime) FixedUpdateBeat() end function PrintEvents() UpdateBeat:Dump() FixedUpdateBeat:Dump() end
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) topameng@gmail.com -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local setmetatable = setmetatable local xpcall = xpcall local pcall = pcall local assert = assert local rawget = rawget local error = error local print = print local traceback = tolua.traceback local ilist = ilist local _xpcall = {} _xpcall.__call = function(self, ...) if jit then if nil == self.obj then return xpcall(self.func, traceback, ...) else return xpcall(self.func, traceback, self.obj, ...) end else local args = {...} if nil == self.obj then local func = function() self.func(unpack(args)) end return xpcall(func, traceback) else local func = function() self.func(self.obj, unpack(args)) end return xpcall(func, traceback) end end end _xpcall.__eq = function(lhs, rhs) return lhs.func == rhs.func and lhs.obj == rhs.obj end local function xfunctor(func, obj) return setmetatable({func = func, obj = obj}, _xpcall) end local _pcall = {} _pcall.__call = function(self, ...) if nil == self.obj then return pcall(self.func, ...) else return pcall(self.func, self.obj, ...) end end _pcall.__eq = function(lhs, rhs) return lhs.func == rhs.func and lhs.obj == rhs.obj end local function functor(func, obj) return setmetatable({func = func, obj = obj}, _pcall) end local _event = {} _event.__index = _event --废弃 function _event:Add(func, obj) assert(func) if self.keepSafe then func = xfunctor(func, obj) else func = functor(func, obj) end if self.lock then local node = {value = func, _prev = 0, _next = 0} table.insert(self.opList, node) node.op = list.pushnode return node else return self.list:push(func) end end --废弃 function _event:Remove(func, obj) for i, v in ilist(self.list) do if v.func == func and v.obj == obj then if self.lock and self.current ~= i then table.insert(self.opList, i) node.op = list.remove else self.list:remove(i) end break end end end function _event:CreateListener(func, obj) if self.keepSafe then func = xfunctor(func, obj) else func = functor(func, obj) end return {value = func, _prev = 0, _next = 0, removed = true} end function _event:AddListener(handle) if self.lock then table.insert(self.opList, handle) handle.op = list.pushnode else self.list:pushnode(handle) end end function _event:RemoveListener(handle) if self.lock and self.current ~= handle then table.insert(self.opList, handle) handle.op = list.remove else self.list:remove(handle) end end function _event:Count() return self.list.length end function _event:Clear() self.list:clear() self.opList = {} self.lock = false self.keepSafe = false self.current = nil end function _event:Dump() local count = 0 for _, v in ilist(self.list) do if v.obj then print("update function:", v.func, "object name:", v.obj.name) else print("update function: ", v.func) end count = count + 1 end print("all function is:", count) end _event.__call = function(self, ...) local _list = self.list self.lock = true local ilist = ilist for i, f in ilist(_list) do self.current = i local flag, msg = f(...) if not flag then if self.keepSafe then _list:remove(i) end self.lock = false error(msg) end end for _, i in ipairs(self.opList) do i.op(_list, i) end self.lock = false self.opList = {} end function event(name, safe) safe = safe or false return setmetatable({name = name, keepSafe = safe, lock = false, opList = {}, list = list:new()}, _event) end UpdateBeat = event("Update", true) LateUpdateBeat = event("LateUpdate", true) FixedUpdateBeat = event("FixedUpdate", true) CoUpdateBeat = event("CoUpdate") --只在协同使用 local Time = Time local UpdateBeat = UpdateBeat local LateUpdateBeat = LateUpdateBeat local FixedUpdateBeat = FixedUpdateBeat local CoUpdateBeat = CoUpdateBeat --逻辑update function Update(deltaTime, unscaledDeltaTime) Time:SetDeltaTime(deltaTime, unscaledDeltaTime) UpdateBeat() end function LateUpdate() LateUpdateBeat() CoUpdateBeat() Time:SetFrameCount() end --物理update function FixedUpdate(fixedDeltaTime) Time:SetFixedDelta(fixedDeltaTime) FixedUpdateBeat() end function PrintEvents() UpdateBeat:Dump() FixedUpdateBeat:Dump() end
1.0.7.365 fixed event.lua add remove时序问题
1.0.7.365 fixed event.lua add remove时序问题
Lua
mit
topameng/tolua
4d54beea19d78d65d5597397676d76d6ef3e75d6
modules/alarm.lua
modules/alarm.lua
local ev = require'ev' if(not ivar2.timers) then ivar2.timers = {} end local alarm = function(self, source, destination, time, message) local weeks = time:match'(%d+)[w]' local days = time:match'(%d+)[d]' local hour = time:match'(%d+)[ht]' local min = time:match'(%d+)m' local sec = time:match'(%d+)s' local duration = 0 if(weeks) then duration = duration + (weeks * 60 * 60 * 24 * 7) end if(days) then duration = duration + (days * 60 * 60 * 24) end if(hour) then duration = duration + (hour * 60 * 60) end if(min) then duration = duration + (min * 60) end if(sec) then duration = duration + sec end -- 60 days or more? local nick = source.nick if(duration >= (60 * 60 * 24 * 60) or duration == 0) then return self:Msg(dest, src, "%s: :'(", nick) end local id = 'Alarm: ' .. nick if(self.timers[id]) then -- message is probably changed. self.timers[id]:stop(ivar2.Loop) end local timer = ev.Timer.new( function(loop, timer, revents) if(#message == 0) then message = 'Timer finished.' end self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.') end, duration ) self:Notice(source.nick, "I'll poke you at %s.", os.date('%Y-%m-%d %X %Z', os.time() + duration)) self.timers[id] = timer timer:start(ivar2.Loop) end return { PRIVMSG = { ['^!alarm (%S+)%s?(.*)'] = alarm, ['^!timer (%S+)%s?(.*)'] = alarm, }, }
local ev = require'ev' if(not ivar2.timers) then ivar2.timers = {} end local dateFormat = '%Y-%m-%d %X %Z' local alarm = function(self, source, destination, time, message) local weeks = time:match'(%d+)[w]' local days = time:match'(%d+)[d]' local hour = time:match'(%d+)[ht]' local min = time:match'(%d+)m' local sec = time:match'(%d+)s' local duration = 0 if(weeks) then duration = duration + (weeks * 60 * 60 * 24 * 7) end if(days) then duration = duration + (days * 60 * 60 * 24) end if(hour) then duration = duration + (hour * 60 * 60) end if(min) then duration = duration + (min * 60) end if(sec) then duration = duration + sec end -- 60 days or more? local nick = source.nick if(duration >= (60 * 60 * 24 * 60) or duration == 0) then return self:Msg(dest, src, "%s: :'(", nick) end local id = 'Alarm: ' .. nick local runningTimer = self.timers[id] if(runningTimer) then -- Send a notification if we are overriding an old timer. if(runningTimer.utimestamp < os.time()) then if(runningTimer.message) then self:Notice( nick, 'Previously active timer set to trigger at %s with message "%s" has been removed.', os.date(dateFormat, runningTimer.utimestamp), runningTimer.message ) else self:Notice( nick, 'Previously active timer set to trigger at %s has been removed.', os.date(dateFormat, runningTimer.utimestamp) ) end end -- message is probably changed. runningTimer:stop(ivar2.Loop) end local timer = ev.Timer.new( function(loop, timer, revents) if(#message == 0) then message = 'Timer finished.' end self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.') end, duration ) timer.message = message timer.utimestamp = os.time() + duration self:Notice(nick, "I'll poke you at %s.", os.date(dateFormat, timer.utimestamp)) self.timers[id] = timer timer:start(ivar2.Loop) end return { PRIVMSG = { ['^!alarm (%S+)%s?(.*)'] = alarm, ['^!timer (%S+)%s?(.*)'] = alarm, }, }
alarm: Send a notification if we override a running timer.
alarm: Send a notification if we override a running timer. Fixes #28.
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
f3dc774c0982305dfbe70bf2459f9a7ddaa94b9e
modules/title.lua
modules/title.lua
local iconv = require"iconv" local parse = require"socket.url".parse local patterns = { -- X://Y url "^(%a[%w%.+-]+://%S+)", "%f[%S](%a[%w%.+-]+://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", -- XXX.YYY.ZZZ.WWW:VVVV/UUUUU IPv4 address with port and path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", -- XXX.YYY.ZZZ.WWW/VVVVV IPv4 address with path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", -- XXX.YYY.ZZZ.WWW IPv4 address "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", -- X.Y.Z:WWWW/VVVVV url with port and path "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", -- X.Y.Z:WWWW url with port (ts server for example) "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", -- X.Y.Z/WWWWW url with path -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", -- X.Y.Z url -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+))", -- "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", } local danbooru = function(path) local path = path['path'] if(path and path:match'/data/([^%.]+)') then local md5 = path:match'/data/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) elseif(s == 503) then return string.format('http://danbooru.donmai.us/post?tags=md5:%s', md5) else return string.format('Server returned: %d', s) end end end local iiHost = { -- do nothing ['eu.wowarmory.com'] = function() end, ['danbooru.donmai.us'] = danbooru, ['miezaru.donmai.us'] = danbooru, ['open.spotify.com'] = function(path, url) local path = path['path'] if(path and path:match'/(%w+)/(.+)') then local type, id = path:match'/(%w+)/(.+)' local old = socket.http.USERAGENT socket.http.USERAGENT = 'Otravi/1.0' local content = utils.http(url) socket.http.USERAGENT = old local title = content:match"<title>(.-)</title>" return string.format('%s: spotify:%s:%s', title, type, id) end end, ['s3.amazonaws.com'] = function(path) local path = path['path'] if(path and path:match'/danbooru/([^%.]+)') then local md5 = path:match'/danbooru/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end, } local kiraiTitle = { ['sexy%-lena%.com'] = true, -- fap fap fap fap ['unsere%-nackte%-pyjamaparty%.net'] = true, ['johnsrevenge%.com'] = true, ['tapuz%.me2you%.co%.il'] = true, ['.-%mybrute.com'] = true, ['marie%-gets%-deflowered.com'] = true, ['whycindywhy%.com'] = true, ['.-%.labrute%.fr'] = true, ['.-%.PetiteMarion%.com'] = true, ['.-%.claravenger%.com'] = true, ['ihatestacy%.com'] = true, ['.-%.nimp.org'] = true, ['.-screwyouemily%.com'] = true, } local renameCharset = { ['x-sjis'] = 'sjis', } local validProtocols = { ['http'] = true, ['https'] = true, } local getTitle = function(url, offset) local path = parse(url) local host = path['host']:gsub('^www%.', '') for k, v in next, kiraiTitle do if(host:lower():match(k)) then return 'Blacklisted domain.' end end if(iiHost[host]) then return iiHost[host](path, url) end local body, status, headers = utils.http(url) if(body) then local charset = body:lower():match'<meta.-content=["\'].-(charset=.-)["\'].->' if(charset) then charset = charset:match"charset=(.+)$?;?" end if(not charset) then charset = body:match'<%?xml.-encoding=[\'"](.-)[\'"].-%?>' end if(not charset) then local tmp = utils.split(headers['content-type'], ' ') for _, v in pairs(tmp) do if(v:lower():match"charset") then charset = v:lower():match"charset=(.+)$?;?" break end end end local title = body:match"<[tT][iI][tT][lL][eE]>(.-)</[tT][iI][tT][lL][eE]>" if(title) then for _, pattern in ipairs(patterns) do title = title:gsub(pattern, '<snip />') end end if(charset and title and charset:lower() ~= "utf-8") then charset = charset:gsub("\n", ""):gsub("\r", "") charset = renameCharset[charset] or charset local cd, err = iconv.new("utf-8", charset) if(cd) then title = cd:iconv(title) end end if(title and title ~= "" and title ~= '<snip />') then title = utils.decodeHTML(title) title = title:gsub("[%s%s]+", " ") if(#url >= 105) then local short = utils.x0(url) if(short ~= url) then title = "Downgraded URL: " ..short.." - "..title end end return title end end end local found = 0 local urls local gsubit = function(url) found = found + 1 local total = 1 for k in pairs(urls) do total = total + 1 end if(not url:match"://") then url = "http://"..url elseif(not validProtocols[url:match'^[^:]+']) then return end if(not urls[url]) then urls[url] = { n = found, m = total, title = getTitle(url), } else urls[url].n = string.format("%s+%d", urls[url].n, found) end end return { ["^:(%S+) PRIVMSG (%S+) :(.+)$"] = function(self, src, dest, msg) if(self:srctonick(src) == self.config.nick or msg:sub(1,1) == '!' or self:srctonick(src):match"^CIA") then return end urls, found = {}, 0 for key, msg in pairs(utils.split(msg, " ")) do for _, pattern in ipairs(patterns) do msg:gsub(pattern, gsubit) end end if(next(urls)) then local out = {} for url, data in pairs(urls) do if(data.title) then table.insert(out, data.m, string.format("\002[%s]\002 %s", data.n, data.title)) end end if(#out > 0) then self:msg(dest, src, table.concat(out, " ")) end end end, }
local iconv = require"iconv" local parse = require"socket.url".parse local patterns = { -- X://Y url "^(%a[%w%.+-]+://%S+)", "%f[%S](%a[%w%.+-]+://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", -- XXX.YYY.ZZZ.WWW:VVVV/UUUUU IPv4 address with port and path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", -- XXX.YYY.ZZZ.WWW/VVVVV IPv4 address with path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", -- XXX.YYY.ZZZ.WWW IPv4 address "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", -- X.Y.Z:WWWW/VVVVV url with port and path "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", -- X.Y.Z:WWWW url with port (ts server for example) "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", -- X.Y.Z/WWWWW url with path -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", -- X.Y.Z url -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+))", -- "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", } local danbooru = function(path) local path = path['path'] if(path and path:match'/data/([^%.]+)') then local md5 = path:match'/data/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) elseif(s == 503) then return string.format('http://danbooru.donmai.us/post?tags=md5:%s', md5) else return string.format('Server returned: %d', s) end end end local iiHost = { -- do nothing ['eu.wowarmory.com'] = function() end, ['danbooru.donmai.us'] = danbooru, ['miezaru.donmai.us'] = danbooru, ['open.spotify.com'] = function(path, url) local path = path['path'] if(path and path:match'/(%w+)/(.+)') then local type, id = path:match'/(%w+)/(.+)' local old = socket.http.USERAGENT socket.http.USERAGENT = 'Otravi/1.0' local content = utils.http(url) socket.http.USERAGENT = old local title = content:match"<title>(.-)</title>" return string.format('%s: spotify:%s:%s', title, type, id) end end, ['s3.amazonaws.com'] = function(path) local path = path['path'] if(path and path:match'/danbooru/([^%.]+)') then local md5 = path:match'/danbooru/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end, } local kiraiTitle = { ['sexy%-lena%.com'] = true, -- fap fap fap fap ['unsere%-nackte%-pyjamaparty%.net'] = true, ['johnsrevenge%.com'] = true, ['tapuz%.me2you%.co%.il'] = true, ['.-%mybrute.com'] = true, ['marie%-gets%-deflowered.com'] = true, ['whycindywhy%.com'] = true, ['.-%.labrute%.fr'] = true, ['.-%.PetiteMarion%.com'] = true, ['.-%.claravenger%.com'] = true, ['ihatestacy%.com'] = true, ['.-%.nimp.org'] = true, ['.-screwyouemily%.com'] = true, } local renameCharset = { ['x-sjis'] = 'sjis', } local validProtocols = { ['http'] = true, ['https'] = true, } local getTitle = function(url, offset) local path = parse(url) local host = path['host']:gsub('^www%.', '') for k, v in next, kiraiTitle do if(host:lower():match(k)) then return 'Blacklisted domain.' end end if(iiHost[host]) then local title = iiHost[host](path, url) if(title) then return title end end local body, status, headers = utils.http(url) if(body) then local charset = body:lower():match'<meta.-content=["\'].-(charset=.-)["\'].->' if(charset) then charset = charset:match"charset=(.+)$?;?" end if(not charset) then charset = body:match'<%?xml.-encoding=[\'"](.-)[\'"].-%?>' end if(not charset) then local tmp = utils.split(headers['content-type'], ' ') for _, v in pairs(tmp) do if(v:lower():match"charset") then charset = v:lower():match"charset=(.+)$?;?" break end end end local title = body:match"<[tT][iI][tT][lL][eE]>(.-)</[tT][iI][tT][lL][eE]>" if(title) then for _, pattern in ipairs(patterns) do title = title:gsub(pattern, '<snip />') end end if(charset and title and charset:lower() ~= "utf-8") then charset = charset:gsub("\n", ""):gsub("\r", "") charset = renameCharset[charset] or charset local cd, err = iconv.new("utf-8", charset) if(cd) then title = cd:iconv(title) end end if(title and title ~= "" and title ~= '<snip />') then title = utils.decodeHTML(title) title = title:gsub("[%s%s]+", " ") if(#url >= 105) then local short = utils.x0(url) if(short ~= url) then title = "Downgraded URL: " ..short.." - "..title end end return title end end end local found = 0 local urls local gsubit = function(url) found = found + 1 local total = 1 for k in pairs(urls) do total = total + 1 end if(not url:match"://") then url = "http://"..url elseif(not validProtocols[url:match'^[^:]+']) then return end if(not urls[url]) then urls[url] = { n = found, m = total, title = getTitle(url), } else urls[url].n = string.format("%s+%d", urls[url].n, found) end end return { ["^:(%S+) PRIVMSG (%S+) :(.+)$"] = function(self, src, dest, msg) if(self:srctonick(src) == self.config.nick or msg:sub(1,1) == '!' or self:srctonick(src):match"^CIA") then return end urls, found = {}, 0 for key, msg in pairs(utils.split(msg, " ")) do for _, pattern in ipairs(patterns) do msg:gsub(pattern, gsubit) end end if(next(urls)) then local out = {} for url, data in pairs(urls) do if(data.title) then table.insert(out, data.m, string.format("\002[%s]\002 %s", data.n, data.title)) end end if(#out > 0) then self:msg(dest, src, table.concat(out, " ")) end end end, }
Fix iiHost making a bunch of shit fail.
Fix iiHost making a bunch of shit fail.
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
ffa9857ff18daa3e456ec4e3b171dbe0295ba603
frontend/apps/cloudstorage/ftp.lua
frontend/apps/cloudstorage/ftp.lua
local BD = require("ui/bidi") local ConfirmBox = require("ui/widget/confirmbox") local DocumentRegistry = require("document/documentregistry") local FtpApi = require("apps/cloudstorage/ftpapi") local InfoMessage = require("ui/widget/infomessage") local MultiInputDialog = require("ui/widget/multiinputdialog") local ReaderUI = require("apps/reader/readerui") local Screen = require("device").screen local UIManager = require("ui/uimanager") local logger = require("logger") local util = require("util") local _ = require("gettext") local T = require("ffi/util").template local Ftp = {} function Ftp:run(address, user, pass, path) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. path return FtpApi:listFolder(url, path) end function Ftp:downloadFile(item, address, user, pass, path, close) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. item.url logger.dbg("downloadFile url", url) local response = FtpApi:ftpGet(url, "retr") if response ~= nil then path = util.fixUtf8(path, "_") local file = io.open(path, "w") file:write(response) file:close() local __, filename = util.splitFilePathName(path) if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then UIManager:show(InfoMessage:new{ text = T(_("File saved to:\n%1"), BD.filepath(path)), }) else UIManager:show(ConfirmBox:new{ text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"), BD.filepath(path)), ok_callback = function() close() ReaderUI:showReader(path) end }) end else UIManager:show(InfoMessage:new{ text = T(_("Could not save file to:\n%1"), BD.filepath(path)), timeout = 3, }) end end function Ftp:config(item, callback) local text_info = _([[ The FTP address must be in the following format: ftp://example.domain.com An IP address is also supported, for example: ftp://10.10.10.1 Username and password are optional.]]) local hint_name = _("Your FTP name") local text_name = "" local hint_address = _("FTP address eg ftp://example.com") local text_address = "" local hint_username = _("FTP username") local text_username = "" local hint_password = _("FTP password") local text_password = "" local hint_folder = _("FTP folder") local text_folder = "/" local title local text_button_right = _("Add") if item then title = _("Edit FTP account") text_button_right = _("Apply") text_name = item.text text_address = item.address text_username = item.username text_password = item.password text_folder = item.url else title = _("Add FTP account") end self.settings_dialog = MultiInputDialog:new { title = title, fields = { { text = text_name, input_type = "string", hint = hint_name , }, { text = text_address, input_type = "string", hint = hint_address , }, { text = text_username, input_type = "string", hint = hint_username, }, { text = text_password, input_type = "string", text_type = "password", hint = hint_password, }, { text = text_folder, input_type = "string", hint = hint_folder, }, }, buttons = { { { text = _("Cancel"), callback = function() self.settings_dialog:onClose() UIManager:close(self.settings_dialog) end }, { text = _("Info"), callback = function() UIManager:show(InfoMessage:new{ text = text_info }) end }, { text = text_button_right, callback = function() local fields = MultiInputDialog:getFields() if fields[1] ~= "" and fields[2] ~= "" then if item then -- edit callback(item, fields) else -- add new callback(fields) end self.settings_dialog:onClose() UIManager:close(self.settings_dialog) else UIManager:show(InfoMessage:new{ text = _("Please fill in all fields.") }) end end }, }, }, width = math.floor(Screen:getWidth() * 0.95), height = math.floor(Screen:getHeight() * 0.2), input_type = "text", } UIManager:show(self.settings_dialog) self.settings_dialog:onShowKeyboard() end function Ftp:info(item) local info_text = T(_"Type: %1\nName: %2\nAddress: %3", "FTP", item.text, item.address) UIManager:show(InfoMessage:new{text = info_text}) end return Ftp
local BD = require("ui/bidi") local ConfirmBox = require("ui/widget/confirmbox") local DocumentRegistry = require("document/documentregistry") local FtpApi = require("apps/cloudstorage/ftpapi") local InfoMessage = require("ui/widget/infomessage") local MultiInputDialog = require("ui/widget/multiinputdialog") local ReaderUI = require("apps/reader/readerui") local Screen = require("device").screen local UIManager = require("ui/uimanager") local logger = require("logger") local util = require("util") local _ = require("gettext") local T = require("ffi/util").template local Ftp = {} function Ftp:run(address, user, pass, path) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. path return FtpApi:listFolder(url, path) end function Ftp:downloadFile(item, address, user, pass, path, close) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. item.url logger.dbg("downloadFile url", url) local response = FtpApi:ftpGet(url, "retr") if response ~= nil then path = util.fixUtf8(path, "_") local file, err = io.open(path, "w") if not file then UIManager:show(InfoMessage:new{ text = T(_("Could not save file to %1:\n%2"), BD.filepath(path), err), }) return end file:write(response) file:close() local __, filename = util.splitFilePathName(path) if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then UIManager:show(InfoMessage:new{ text = T(_("File saved to:\n%1"), BD.filepath(path)), }) else UIManager:show(ConfirmBox:new{ text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"), BD.filepath(path)), ok_callback = function() close() ReaderUI:showReader(path) end }) end else UIManager:show(InfoMessage:new{ text = T(_("Could not save file to:\n%1"), BD.filepath(path)), timeout = 3, }) end end function Ftp:config(item, callback) local text_info = _([[ The FTP address must be in the following format: ftp://example.domain.com An IP address is also supported, for example: ftp://10.10.10.1 Username and password are optional.]]) local hint_name = _("Your FTP name") local text_name = "" local hint_address = _("FTP address eg ftp://example.com") local text_address = "" local hint_username = _("FTP username") local text_username = "" local hint_password = _("FTP password") local text_password = "" local hint_folder = _("FTP folder") local text_folder = "/" local title local text_button_right = _("Add") if item then title = _("Edit FTP account") text_button_right = _("Apply") text_name = item.text text_address = item.address text_username = item.username text_password = item.password text_folder = item.url else title = _("Add FTP account") end self.settings_dialog = MultiInputDialog:new { title = title, fields = { { text = text_name, input_type = "string", hint = hint_name , }, { text = text_address, input_type = "string", hint = hint_address , }, { text = text_username, input_type = "string", hint = hint_username, }, { text = text_password, input_type = "string", text_type = "password", hint = hint_password, }, { text = text_folder, input_type = "string", hint = hint_folder, }, }, buttons = { { { text = _("Cancel"), callback = function() self.settings_dialog:onClose() UIManager:close(self.settings_dialog) end }, { text = _("Info"), callback = function() UIManager:show(InfoMessage:new{ text = text_info }) end }, { text = text_button_right, callback = function() local fields = MultiInputDialog:getFields() if fields[1] ~= "" and fields[2] ~= "" then if item then -- edit callback(item, fields) else -- add new callback(fields) end self.settings_dialog:onClose() UIManager:close(self.settings_dialog) else UIManager:show(InfoMessage:new{ text = _("Please fill in all fields.") }) end end }, }, }, width = math.floor(Screen:getWidth() * 0.95), height = math.floor(Screen:getHeight() * 0.2), input_type = "text", } UIManager:show(self.settings_dialog) self.settings_dialog:onShowKeyboard() end function Ftp:info(item) local info_text = T(_"Type: %1\nName: %2\nAddress: %3", "FTP", item.text, item.address) UIManager:show(InfoMessage:new{text = info_text}) end return Ftp
ftp: guard against nil file (#6640)
ftp: guard against nil file (#6640) Fixes #6636
Lua
agpl-3.0
Frenzie/koreader,mwoz123/koreader,poire-z/koreader,pazos/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,Hzj-jie/koreader,Markismus/koreader,koreader/koreader,NiLuJe/koreader
cd9c6550e9fc172b740ee3f4bdd2c03f47ee43cf
src/characterstrip.lua
src/characterstrip.lua
---------------------------------------------------------------------- -- characterstrip.lua -- A single colored strip, on which a character appears for selection. -- Created by tjvezina ---------------------------------------------------------------------- local CharacterStrip = {} CharacterStrip.__index = CharacterStrip local window = require 'window' local stripSize = 35 -- Thickness of the strip local moveSize = 300 -- Pixels travelled from ratio 0 to 1 local moveSpeed = 5.0 -- Slide speed multiplier -- The different colored bars on the strip appear at these intervals local colorSpacing = { 140, 160, 180, 200, 260 } -- Hawkthorne Colors (As arranged on-screen): -- NOTE: Each strips 2nd color is calculated by (220-r, 220-g, 220-b) -- ( 81, 73, 149) | (149, 214, 200) -- (150, 221, 149) | (134, 60, 133) -- (200, 209, 149) | (171, 98, 109) -- (173, 135, 158) | ( 80, 80, 80) function CharacterStrip.new(r, g, b) local new = {} setmetatable(new, CharacterStrip) new.x = 0 new.y = 0 new.flip = false new.ratio = 0 new.slideOut = false new.color1 = { r = r, g = g, b = b } new.color2 = { r = 220-r, g = 220-g, b = 220-b } return new end function CharacterStrip:getCharacterPos() local x = self.x + (self.flip and 44 or -44) - self:getOffset() / 1.5 local y = self.y if not self.flip then local limit = self.x + 10 if x > limit then y = y + (x - limit) x = limit end else local limit = self.x - 10 if x < limit then y = y + (limit - x) x = limit end end return x, y end function CharacterStrip:draw() w = window.width * 0.5 h = window.height * 0.75 local stencilFunc = nil if self.flip then stencilFunc = function() love.graphics.rectangle('fill', self.x, self.y, w, stripSize) love.graphics.rectangle('fill', self.x, self.y + stripSize, stripSize, math.max(moveSize * self.ratio - stripSize, 0)) end else stencilFunc = function() love.graphics.rectangle('fill', self.x - w, self.y, w, stripSize) love.graphics.rectangle('fill', self.x - stripSize, self.y + stripSize, stripSize, math.max(moveSize * self.ratio - stripSize, 0)) end end love.graphics.setStencil( stencilFunc ) for i, offset in ipairs(colorSpacing) do color = self:getColor((i-1) / (#colorSpacing-1)) love.graphics.setColor(color.r, color.g, color.b, 255) love.graphics.polygon('fill', self:getPolyVerts(i)) end love.graphics.setStencil() if self.selected and self.ratio == 0 then -- Father forgive me for I have sinned local flipped = self.flip and 1 or -1 local x1 = -self:getOffset() + self.x local y1 = self.y local x2 = -self:getOffset() + self.x + colorSpacing[5] * flipped local y2 = self.y local x3 = x2 + stripSize * flipped local y3 = y2 + stripSize local x4 = x1 + stripSize * flipped local y4 = y1 + stripSize love.graphics.setColor(255, 255, 255, 255) love.graphics.polygon('line', x1, y1, x2, y2, x3, y3, x4, y4) -- I know not what I do end end local time = 0 function CharacterStrip:update(dt,ready) self.ratio = self.ratio + dt * moveSpeed if not self.slideOut then self.ratio = math.min(self.ratio, 0) end end function CharacterStrip:getPolyVerts(segment) local offset = -self:getOffset() local verts = {} if self.flip then verts[1] = offset + self.x + (colorSpacing[segment-1] or 0) verts[2] = self.y verts[3] = offset + self.x + colorSpacing[segment] verts[4] = self.y verts[5] = verts[3] + moveSize verts[6] = verts[4] + moveSize verts[7] = verts[1] + moveSize verts[8] = verts[2] + moveSize else verts[1] = offset + self.x - (colorSpacing[segment-1] or 0) verts[2] = self.y verts[7] = offset + self.x - colorSpacing[segment] verts[8] = self.y verts[5] = verts[7] - moveSize verts[6] = verts[8] + moveSize verts[3] = verts[1] - moveSize verts[4] = verts[2] + moveSize end return verts end function CharacterStrip:getColor(ratio) assert(ratio >= 0 and ratio <= 1, "Color ratio must be between 0 and 1.") if ratio == 0 then return self.color1 end if ratio == 1 then return self.color2 end colorDif = { r = self.color2.r - self.color1.r, g = self.color2.g - self.color1.g, b = self.color2.b - self.color1.b } return { r = self.color1.r + ( colorDif.r * ratio ), g = self.color1.g + ( colorDif.g * ratio ), b = self.color1.b + ( colorDif.b * ratio ) } end function CharacterStrip:getOffset() return ( (self.flip and -moveSize or moveSize) * -self.ratio ) + (self.flip and -1 or 1) end return CharacterStrip
---------------------------------------------------------------------- -- characterstrip.lua -- A single colored strip, on which a character appears for selection. -- Created by tjvezina ---------------------------------------------------------------------- local CharacterStrip = {} CharacterStrip.__index = CharacterStrip local window = require 'window' local stripSize = 35 -- Thickness of the strip local moveSize = 300 -- Pixels travelled from ratio 0 to 1 local moveSpeed = 5.0 -- Slide speed multiplier -- The different colored bars on the strip appear at these intervals local colorSpacing = { 140, 160, 180, 200, 260 } -- Hawkthorne Colors (As arranged on-screen): -- NOTE: Each strips 2nd color is calculated by (220-r, 220-g, 220-b) -- ( 81, 73, 149) | (149, 214, 200) -- (150, 221, 149) | (134, 60, 133) -- (200, 209, 149) | (171, 98, 109) -- (173, 135, 158) | ( 80, 80, 80) function CharacterStrip.new(r, g, b) local new = {} setmetatable(new, CharacterStrip) new.x = 0 new.y = 0 new.flip = false new.ratio = 0 new.slideOut = false new.color1 = { r = r, g = g, b = b } new.color2 = { r = 220-r, g = 220-g, b = 220-b } new.stencilFunc = function( this ) love.graphics.rectangle('fill', this.x - ( this.flip and 0 or (window.width * 0.5) ), this.y, (window.width * 0.5), stripSize) love.graphics.rectangle('fill', this.x - ( this.flip and 0 or stripSize ), this.y + stripSize, stripSize, math.max(moveSize * this.ratio - stripSize, 0)) end return new end function CharacterStrip:getCharacterPos() local x = self.x + (self.flip and 44 or -44) - self:getOffset() / 1.5 local y = self.y if not self.flip then local limit = self.x + 10 if x > limit then y = y + (x - limit) x = limit end else local limit = self.x - 10 if x < limit then y = y + (limit - x) x = limit end end return x, y end function CharacterStrip:draw() love.graphics.setStencil( self.stencilFunc, self ) for i, offset in ipairs(colorSpacing) do love.graphics.setColor( self:getColor((i-1) / (#colorSpacing-1)) ) love.graphics.polygon('fill', self:getPolyVerts(i)) end love.graphics.setStencil() if self.selected and self.ratio == 0 then -- Father forgive me for I have sinned local flipped = self.flip and 1 or -1 local x1 = -self:getOffset() + self.x local y1 = self.y local x2 = -self:getOffset() + self.x + colorSpacing[5] * flipped local y2 = self.y local x3 = x2 + stripSize * flipped local y3 = y2 + stripSize local x4 = x1 + stripSize * flipped local y4 = y1 + stripSize love.graphics.setColor(255, 255, 255, 255) love.graphics.polygon('line', x1, y1, x2, y2, x3, y3, x4, y4) -- I know not what I do end end local time = 0 function CharacterStrip:update(dt,ready) self.ratio = self.ratio + dt * moveSpeed if not self.slideOut then self.ratio = math.min(self.ratio, 0) end end function CharacterStrip:getPolyVerts(segment) local offset = -self:getOffset() if self.flip then return offset + self.x + (colorSpacing[segment-1] or 0), self.y, offset + self.x + colorSpacing[segment], self.y, offset + self.x + colorSpacing[segment] + moveSize, self.y + moveSize, offset + self.x + (colorSpacing[segment-1] or 0) + moveSize, self.y + moveSize else return offset + self.x - (colorSpacing[segment-1] or 0), self.y, offset + self.x - (colorSpacing[segment-1] or 0) - moveSize, self.y + moveSize, offset + self.x - colorSpacing[segment] - moveSize, self.y + moveSize, offset + self.x - colorSpacing[segment], self.y end end function CharacterStrip:getColor(ratio) assert(ratio >= 0 and ratio <= 1, "Color ratio must be between 0 and 1.") if ratio == 0 then return self.color1.r, self.color1.g, self.color1.b,255 end if ratio == 1 then return self.color2.r, self.color2.g, self.color2.b,255 end return self.color1.r + ( ( self.color2.r - self.color1.r ) * ratio ), self.color1.g + ( ( self.color2.g - self.color1.g ) * ratio ), self.color1.b + ( ( self.color2.b - self.color1.b ) * ratio ), 255 end function CharacterStrip:getOffset() return ( (self.flip and -moveSize or moveSize) * -self.ratio ) + (self.flip and -1 or 1) end return CharacterStrip
Fixes memory leaks in character strip
Fixes memory leaks in character strip
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
0c438a161f0ebded6cd8699b930849b8f4b09067
vstreamers.lua
vstreamers.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 == "video" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if (string.match(url, "/"..item_value) and not string.match(url, "/"..item_value.."[0-9]+")) 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 if item_type == "video" then if string.match(url, "vstreamers%.com/v/[0-9]+") then local newurl = "http://vstreamers.com/js/load_comms.php" if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then table.insert(urls, { url=newurl, post_data="page=1&u_id="..item_value.."&ch_cm_left=false&type=v" }) addedtolist[newurl] = true end end if string.match(url, "vstreamers%.com/e/[0-9]+") then html = read_file(file) for url in string.gmatch(html, 'src="%.%./get_vid/'..item_value..'_[^"]+" type="video/mp4"') do if downloaded[url] ~= true and addedtolist[url] ~= true then table.insert(urls, { url=url }) addedtolist[url] = true 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) or status_code == 403 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 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") 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(75, 1000) / 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 == "video" and (downloaded[url] ~= true and addedtolist[url] ~= true) then if (string.match(url, "/"..item_value) and not string.match(url, "/"..item_value.."[0-9]+")) 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 if item_type == "video" then if string.match(url, "vstreamers%.com/v/[0-9]+") then local newurl = "http://vstreamers.com/js/load_comms.php" if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then table.insert(urls, { url=newurl, post_data="page=1&u_id="..item_value.."&ch_cm_left=false&type=v" }) addedtolist[newurl] = true end end if string.match(url, "vstreamers%.com/e/[0-9]+") then html = read_file(file) if string.match(html, 'src="%.%./get_vid/'..item_value..'_[^"]+" type="video/mp4"') then local uurl = string.match(html, 'src="%.%.(/get_vid/[^"]+)" type="video/mp4"') local url = "http://vstreamers.com"..uurl if downloaded[url] ~= true and addedtolist[url] ~= true then table.insert(urls, { url=url }) addedtolist[url] = true 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) or status_code == 403 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 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") 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(75, 1000) / 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
vstreamers.lua: fix
vstreamers.lua: fix
Lua
unlicense
ArchiveTeam/vstreamers-grab,ArchiveTeam/vstreamers-grab
8d7c423f707623fad896662af2ffcedcc3e80d86
src/websocket/client_ev.lua
src/websocket/client_ev.lua
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local debug = require'debug' local tconcat = table.concat local tinsert = table.insert local ev = function(ws) ws = ws or {} local ev = require'ev' local sock local loop = ws.loop or ev.Loop.default local fd local message_io local handshake_io local send_io_stop local async_send local self = {} self.state = 'CLOSED' local close_timer local user_on_message local user_on_close local user_on_open local user_on_error local cleanup = function() if close_timer then close_timer:stop(loop) close_timer = nil end if handshake_io then handshake_io:stop(loop) handshake_io:clear_pending(loop) handshake_io = nil end if send_io_stop then send_io_stop() send_io_stop = nil end if message_io then message_io:stop(loop) message_io:clear_pending(loop) message_io = nil end if sock then sock:shutdown() sock:close() sock = nil end end local on_close = function(was_clean,code,reason) cleanup() self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end end local on_error = function(err,dont_cleanup) if not dont_cleanup then cleanup() end if user_on_error then user_on_error(self,err) else print('Error',err) end end local on_open = function() self.state = 'OPEN' if user_on_open then user_on_open(self) end end local handle_socket_err = function(err,io,sock) if self.state == 'OPEN' then on_close(false,1006,err) elseif self.state ~= 'CLOSED' then on_error(err) end end local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE,true) async_send(encoded, function() on_close(true,code or 1005,reason) end,handle_socket_err) else on_close(true,1005,'') end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT,true) async_send(encoded, nil, handle_socket_err) end self.connect = function(_,url,ws_protocol) if self.state ~= 'CLOSED' then on_error('wrong state',true) return end local protocol,host,port,uri = tools.parse_url(url) if protocol ~= 'ws' then on_error('bad protocol') return end self.state = 'CONNECTING' assert(not sock) sock = socket.tcp() fd = sock:getfd() assert(fd > -1) -- set non blocking sock:settimeout(0) sock:setoption('tcp-nodelay',true) async_send,send_io_stop = require'websocket.ev_common'.async_send(sock,loop) handshake_io = ev.IO.new( function(loop,connect_io) connect_io:stop(loop) local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {ws_protocol or ''}, origin = ws.origin, uri = uri } async_send( req, function() local resp = {} local response = '' local read_upgrade = function(loop,read_io) -- this seems to be possible, i don't understand why though :( if not sock then read_io:stop(loop) handshake_io = nil return end repeat local byte,err,pp = sock:receive(1) if byte then response = response..byte elseif err then if err == 'timeout' then return else read_io:stop(loop) on_error('accept failed') return end end until response:sub(#response-3) == '\r\n\r\n' read_io:stop(loop) handshake_io = nil local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then self.state = 'CLOSED' on_error('accept failed') return end message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_socket_err) on_open(self) end handshake_io = ev.IO.new(read_upgrade,fd,ev.READ) handshake_io:start(loop)-- handshake end, handle_socket_err) end,fd,ev.WRITE) local connected,err = sock:connect(host,port) if connected then handshake_io:callback()(loop,handshake_io) elseif err == 'timeout' then handshake_io:start(loop)-- connect else self.state = 'CLOSED' on_error(err) end end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_open = function(_,on_open_arg) user_on_open = on_open_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.close = function(_,code,reason,timeout) if handshake_io then handshake_io:stop(loop) handshake_io:clear_pending(loop) end if self.state == 'CONNECTING' then self.state = 'CLOSING' on_close(false,1006,'') return elseif self.state == 'OPEN' then self.state = 'CLOSING' timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason) encoded = frame.encode(encoded,frame.CLOSE,true) -- this should let the other peer confirm the CLOSE message -- by 'echoing' the message. async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end return self end return ev
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local debug = require'debug' local tconcat = table.concat local tinsert = table.insert local ev = function(ws) ws = ws or {} local ev = require'ev' local sock local loop = ws.loop or ev.Loop.default local fd local message_io local handshake_io local send_io_stop local async_send local self = {} self.state = 'CLOSED' local close_timer local user_on_message local user_on_close local user_on_open local user_on_error local cleanup = function() if close_timer then close_timer:stop(loop) close_timer = nil end if handshake_io then handshake_io:stop(loop) handshake_io:clear_pending(loop) handshake_io = nil end if send_io_stop then send_io_stop() send_io_stop = nil end if message_io then message_io:stop(loop) message_io:clear_pending(loop) message_io = nil end if sock then sock:shutdown() sock:close() sock = nil end end local on_close = function(was_clean,code,reason) cleanup() self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end end local on_error = function(err,dont_cleanup) if not dont_cleanup then cleanup() end if user_on_error then user_on_error(self,err) else print('Error',err) end end local on_open = function() self.state = 'OPEN' if user_on_open then user_on_open(self) end end local handle_socket_err = function(err,io,sock) if self.state == 'OPEN' then on_close(false,1006,err) elseif self.state ~= 'CLOSED' then on_error(err) end end local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE,true) async_send(encoded, function() on_close(true,code or 1005,reason) end,handle_socket_err) else on_close(true,1005,'') end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT,true) async_send(encoded, nil, handle_socket_err) end self.connect = function(_,url,ws_protocol) if self.state ~= 'CLOSED' then on_error('wrong state',true) return end local protocol,host,port,uri = tools.parse_url(url) if protocol ~= 'ws' then on_error('bad protocol') return end self.state = 'CONNECTING' assert(not sock) sock = socket.tcp() fd = sock:getfd() assert(fd > -1) -- set non blocking sock:settimeout(0) sock:setoption('tcp-nodelay',true) async_send,send_io_stop = require'websocket.ev_common'.async_send(sock,loop) handshake_io = ev.IO.new( function(loop,connect_io) connect_io:stop(loop) local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {ws_protocol or ''}, origin = ws.origin, uri = uri } async_send( req, function() local resp = {} local response = '' local read_upgrade = function(loop,read_io) -- this seems to be possible, i don't understand why though :( if not sock then read_io:stop(loop) handshake_io = nil return end repeat local byte,err,pp = sock:receive(1) if byte then response = response..byte elseif err then if err == 'timeout' then return else read_io:stop(loop) on_error('accept failed') return end end until response:sub(#response-3) == '\r\n\r\n' read_io:stop(loop) handshake_io = nil local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then self.state = 'CLOSED' on_error('accept failed') return end message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_socket_err) on_open(self) end handshake_io = ev.IO.new(read_upgrade,fd,ev.READ) handshake_io:start(loop)-- handshake end, handle_socket_err) end,fd,ev.WRITE) local connected,err = sock:connect(host,port) if connected then handshake_io:callback()(loop,handshake_io) elseif err == 'timeout' or err == 'Operation already in progress' then handshake_io:start(loop)-- connect else self.state = 'CLOSED' on_error(err) end end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_open = function(_,on_open_arg) user_on_open = on_open_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.close = function(_,code,reason,timeout) if handshake_io then handshake_io:stop(loop) handshake_io:clear_pending(loop) end if self.state == 'CONNECTING' then self.state = 'CLOSING' on_close(false,1006,'') return elseif self.state == 'OPEN' then self.state = 'CLOSING' timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason) encoded = frame.encode(encoded,frame.CLOSE,true) -- this should let the other peer confirm the CLOSE message -- by 'echoing' the message. async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end return self end return ev
fix async open
fix async open
Lua
mit
lipp/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets
deb477a62a1792b232666ff0f1ddf7f85431832f
src/lua/sancus/log.lua
src/lua/sancus/log.lua
-- This file is part of sancus-core-lua <http://github.com/amery/sancus-core-lua> -- -- Copyright (c) 2011, Alejandro Mery <amery@geeks.cl> -- core = require(... .. ".core") local setmetatable = setmetatable local assert, select, type = assert, select, type module(...) local _mt = {} function _mt:log(str, ...) if select('#', ...) > 0 then str = str:format(...) end core.write(9, self.name, str) end _mt.__call = _mt.log _mt.__index = _mt function logger(name) assert(name == nil or type(name) == 'string') return setmetatable({ name = name }, _mt) end
-- This file is part of sancus-core-lua <http://github.com/amery/sancus-core-lua> -- -- Copyright (c) 2011, Alejandro Mery <amery@geeks.cl> -- core = require(... .. ".core") local setmetatable = setmetatable local assert, select, type = assert, select, type module(...) local _mt = {} function _mt:log(str, ...) if select('#', ...) > 0 then str = str:format(...) end core.write(9, self.name, str) end function _mt:__call(...) return _mt.log(self, ...) end _mt.__index = _mt function logger(name) assert(name == nil or type(name) == 'string') return setmetatable({ name = name }, _mt) end
sancus.log: fixed logger.__call()
sancus.log: fixed logger.__call()
Lua
bsd-3-clause
sancus-project/sancus-core-lua-old,sancus-project/sancus-core-lua-old
e6e68bb630fd64b15a04a626d7ff8faef52a916e
packages/lime-proto-wan/src/wan.lua
packages/lime-proto-wan/src/wan.lua
#!/usr/bin/lua local libuci = require("uci") wan = {} wan.configured = false function wan.configure(args) if wan.configured then return end wan.configured = true local uci = libuci:cursor() uci:set("network", "wan", "interface") uci:set("network", "wan", "proto", "dhcp") uci:save("network") end function wan.setup_interface(ifname, args) local uci = libuci:cursor() uci:set("network", "wan", "ifname", ifname) uci:save("network") if opkg.installed("firewall") then fs.remove("/etc/firewall.lime.d/20-wan-out-masquerade") else fs.mkdir("/etc/firewall.lime.d") fs.writefile( "/etc/firewall.lime.d/20-wan-out-masquerade", "iptables -t nat -D POSTROUTING -o " .. ifname .. " -j MASQUERADE\n" .. "iptables -t nat -A POSTROUTING -o " .. ifname .. " -j MASQUERADE\n" ) end end return wan
#!/usr/bin/lua local libuci = require("uci") local fs = require("nixio.fs") local opkg = require("luci.model.ipkg") wan = {} wan.configured = false function wan.configure(args) if wan.configured then return end wan.configured = true local uci = libuci:cursor() uci:set("network", "wan", "interface") uci:set("network", "wan", "proto", "dhcp") uci:save("network") end function wan.setup_interface(ifname, args) local uci = libuci:cursor() uci:set("network", "wan", "ifname", ifname) uci:save("network") if opkg.installed("firewall") then fs.remove("/etc/firewall.lime.d/20-wan-out-masquerade") else fs.mkdir("/etc/firewall.lime.d") fs.writefile( "/etc/firewall.lime.d/20-wan-out-masquerade", "iptables -t nat -D POSTROUTING -o " .. ifname .. " -j MASQUERADE\n" .. "iptables -t nat -A POSTROUTING -o " .. ifname .. " -j MASQUERADE\n" ) end end return wan
lime-proto-wan: fix require fs and opkg (introduced in 1b23a3ce95)
lime-proto-wan: fix require fs and opkg (introduced in 1b23a3ce95)
Lua
agpl-3.0
libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages
2380e249dc858b0326a3bf99d7e541fdd0bd514b
kong/cmd/utils/env.lua
kong/cmd/utils/env.lua
local pl_utils = require "pl.utils" local log = require "kong.cmd.utils.log" local fmt = string.format local cmd = [[ printenv ]] local function read_all() log.debug("reading environment variables: %s", cmd) local vars = {} local success, ret_code, stdout, stderr = pl_utils.executeex(cmd) if not success or ret_code ~= 0 then return nil, fmt("could not read environment variables (exit code: %d): %s", ret_code, stderr) end for line in stdout:gmatch("[^\r\n]+") do local i = string.find(line, "=") -- match first = if i then local k = string.sub(line, 1, i - 1) local v = string.sub(line, i + 1) if k and v then vars[k] = v end end end return vars end return { read_all = read_all, }
-- Parts of this file are adapted from the ljsyscall project -- The ljsyscall project is licensed under the MIT License, -- and copyrighted as: -- Copyright (C) 2011-2016 Justin Cormack. All rights reserved. local ffi = require "ffi" local log = require "kong.cmd.utils.log" ffi.cdef [[ extern char **environ; ]] local environ = ffi.C.environ local function read_all() log.debug("reading environment variables") local env = {} if not environ then log.warn("could not access **environ") return env end local i = 0 while environ[i] ~= nil do local l = ffi.string(environ[i]) local eq = string.find(l, "=", nil, true) if eq then local name = string.sub(l, 1, eq - 1) local val = string.sub(l, eq + 1) env[name] = val end i = i + 1 end return env end return { read_all = read_all, }
hotfix(cli) read environment from **environ instead of printenv
hotfix(cli) read environment from **environ instead of printenv Follow up fix of ac0f3f6fe3048210a68f93ee00d88f10eb77274c From #3538
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
db86cbf5425dcf85f125c301b01dd2ed11d0903c
source/game/map.lua
source/game/map.lua
require "source/pathfinder" require "source/utilities/vector" local Towers = require "assets/towers" Map = flower.class() function Map:init(t) -- Copy all data members of the table as member variables for k, d in pairs(t) do self[k] = d end -- Try to load the map if not self:Load() then print("Cannot Load Map: " .. self.file) end end function Map:Load(file) self.file = self.file or file if not (self.file and io.fileExists(self.file)) then return false end self.map = dofile(self.file) self.width = self.map.width or self.width self.height = self.map.height or self.height self.grid = flower.MapImage(self.texture, self.width, self.height, self.tileWidth, self.tileHeight, self.radius) self.grid:setShape(MOAIGridSpace.HEX_SHAPE) self.grid:setLayer(self.layer) self.grid:setRepeat(false, false) self.grid:setPos(0,0) if type(self.map.tiles) == "table" then for i = 1,self.width do for j = 1,self.height do self.grid.grid:setTile(i, j, self.map.default_tile) end end for i, data in ipairs(self.map.tiles) do for j, pos in ipairs(data) do self.grid.grid:setTile(pos[1], pos[2], i) end end elseif type(self.map.tiles) == "string" then -- Load file from stream local fileStream = MOAIFileStream.new() local success = fileStream:open(self.map.tiles, MOAIFileStream.READ) if success then self.grid.grid:streamTilesIn(fileStream) fileStream:close() end -- TODO: turn the tower types into global variables instead of hardcoding them -- Check which tiles are enemy tiles self.spawnTiles = {} self.targetPosition = {} for i = 1,self.width do for j = 1,self.height do local tile = self.grid.grid:getTile(i, j) if tile == 2 then -- this tile is the desination self.targetPosition[1], self.targetPosition[2] = i, j elseif tile == 1 then table.insert(self.spawnTiles, {i, j}) end end end else return false end -- TODO: make this a bit more dynamic local function validTileCallback(tile) return tile == 6 or tile == 2 or tile == 1 end -- Find path in the map if self:IsPathDynamic() then self.path = findPath(self:GetMOAIGrid(), vector{self.targetPosition[1], self.targetPosition[2]}, validTileCallback) else self.path = self.map.paths[1] self.targetPosition = self.path[#self.path] end return true end function Map:RandomStartingPosition() local startPosition = not self:IsPathDynamic() and self.path[1] or self.startPosition if not startPosition then local randomIndex = math.random(1, #self.spawnTiles) startPosition = self.spawnTiles[randomIndex] end return self:GridToWorldSpace(startPosition) end function Map:GridToWorldSpace(pos) return vector{self:GetMOAIGrid():getTileLoc(pos[1], pos[2], MOAIGridSpace.TILE_CENTER)} end -- Returns true if the path was found using a pathfinder function Map:IsPathDynamic() if self.map.paths then return false end return true end function Map:GetPath() return self.path end function Map:GetGrid() return self.grid end function Map:GetWaves() return self.map.waves end function Map:GetMOAIGrid() return self:GetGrid().grid end
require "source/pathfinder" require "source/utilities/vector" local Towers = require "assets/towers" Map = flower.class() function Map:init(t) -- Copy all data members of the table as member variables for k, d in pairs(t) do self[k] = d end -- Try to load the map if not self:Load() then print("Cannot Load Map: " .. self.file) end end function Map:Load(file) self.file = self.file or file if not (self.file and io.fileExists(self.file)) then return false end self.map = dofile(self.file) self.width = self.map.width or self.width self.height = self.map.height or self.height self.grid = flower.MapImage(self.texture, self.width, self.height, self.tileWidth, self.tileHeight, self.radius) self.grid:setShape(MOAIGridSpace.HEX_SHAPE) self.grid:setLayer(self.layer) self.grid:setRepeat(false, false) self.grid:setPos(0,0) if type(self.map.tiles) == "table" then for i = 1,self.width do for j = 1,self.height do self.grid.grid:setTile(i, j, self.map.default_tile) end end for i, data in ipairs(self.map.tiles) do for j, pos in ipairs(data) do self.grid.grid:setTile(pos[1], pos[2], i) end end elseif type(self.map.tiles) == "string" then -- Load file from stream local fileStream = MOAIFileStream.new() if not fileStream:open(self.map.tiles, MOAIFileStream.READ) then return false end self.grid.grid:streamTilesIn(fileStream) fileStream:close() -- TODO: turn the tower types into global variables instead of hardcoding them -- Check which tiles are enemy tiles self.spawnTiles = {} self.targetPosition = {} for i = 1,self.width do for j = 1,self.height do local tile = self.grid.grid:getTile(i, j) if tile == 2 then -- this tile is the desination self.targetPosition[1], self.targetPosition[2] = i, j elseif tile == 1 then table.insert(self.spawnTiles, {i, j}) end end end else return false end -- TODO: make this a bit more dynamic local function validTileCallback(tile) return tile == 6 or tile == 2 or tile == 1 end -- Find path in the map if self:IsPathDynamic() then self.path = findPath(self:GetMOAIGrid(), vector{self.targetPosition[1], self.targetPosition[2]}, validTileCallback) else self.path = self.map.paths[1] self.targetPosition = self.path[#self.path] end return true end function Map:RandomStartingPosition() local startPosition = not self:IsPathDynamic() and self.path[1] or self.startPosition if not startPosition then local randomIndex = math.random(1, #self.spawnTiles) startPosition = self.spawnTiles[randomIndex] end return self:GridToWorldSpace(startPosition) end function Map:GridToWorldSpace(pos) return vector{self:GetMOAIGrid():getTileLoc(pos[1], pos[2], MOAIGridSpace.TILE_CENTER)} end -- Returns true if the path was found using a pathfinder function Map:IsPathDynamic() if self.map.paths then return false end return true end function Map:GetPath() return self.path end function Map:GetGrid() return self.grid end function Map:GetWaves() return self.map.waves end function Map:GetMOAIGrid() return self:GetGrid().grid end
Fixed trying to load the saved map if the file cannot be loaded.
Fixed trying to load the saved map if the file cannot be loaded.
Lua
mit
BryceMehring/Hexel
52033c8697ad7298f6ee765158ac1f9c857f901d
build/scripts/actions/package.lua
build/scripts/actions/package.lua
newoption({ trigger = "pack-libdir", description = "Specifiy the subdirectory in lib/ to be used when packaging the project" }) ACTION.Name = "Package" ACTION.Description = "Pack Nazara binaries/include/lib together" ACTION.Function = function () local libDir = _OPTIONS["pack-libdir"] if (not libDir or #libDir == 0) then local libDirs = os.matchdirs("../lib/*") if (#libDirs > 1) then error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used") elseif (#libDirs == 0) then error("No subdirectory was found in the lib directory, have you built the engine yet?") else libDir = path.getname(libDirs[1]) print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used") end end local realLibDir = "../lib/" .. libDir .. "/" if (not os.isdir(realLibDir)) then error(string.format("\"%s\" doesn't seem to be an existing directory", realLibDir)) end local archEnabled = { ["x64"] = false, ["x86"] = false } local enabledArchs = {} for k,v in pairs(os.matchdirs(realLibDir .. "*")) do local arch = path.getname(v) if (archEnabled[arch] ~= nil) then archEnabled[arch] = true table.insert(enabledArchs, arch) else print("Unknown directory " .. v .. " found, ignored") end end enabledArchs = table.concat(enabledArchs, ", ") print(enabledArchs .. " arch found") local packageDir = "../package/" local copyTargets = { { -- Engine headers Masks = {"**.hpp", "**.inl"}, Source = "../include/", Target = "include/" }, { -- SDK headers Masks = {"**.hpp", "**.inl"}, Source = "../SDK/include/", Target = "include/" }, { -- Examples files Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../examples/", Target = "examples/" }, { -- Demo resources Masks = {"**.*"}, Source = "../examples/bin/resources/", Target = "examples/bin/resources/" }, -- Unit test sources { Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../tests/", Target = "tests/src/" }, -- Unit test resources { Masks = {"**.*"}, Source = "../tests/resources/", Target = "tests/resources/" } } local binFileMasks local libFileMasks local exeFileExt local exeFilterFunc if (os.is("windows")) then binFileMasks = {"**.dll", "**.pdb"} libFileMasks = {"**.lib", "**.a"} exeFileExt = ".exe" exeFilterFunc = function (filePath) return true end else if (os.is("macosx")) then binFileMasks = {"**.dynlib"} else binFileMasks = {"**.so"} end libFileMasks = {"**.a"} exeFileExt = "" exeFilterFunc = function (filePath) return path.getextension(filePath):contains('/') end end for arch, enabled in pairs(archEnabled) do if (enabled) then local archLibSrc = realLibDir .. arch .. "/" local arch3rdPartyBinSrc = "../extlibs/lib/common/" .. arch .. "/" local archBinDst = "bin/" .. arch .. "/" local archLibDst = "lib/" .. arch .. "/" -- Engine/SDK binaries table.insert(copyTargets, { Masks = binFileMasks, Source = archLibSrc, Target = archBinDst }) -- Engine/SDK libraries table.insert(copyTargets, { Masks = libFileMasks, Source = archLibSrc, Target = archLibDst }) -- 3rd party binary dep table.insert(copyTargets, { Masks = binFileMasks, Source = arch3rdPartyBinSrc, Target = archBinDst }) end end -- Demo executable table.insert(copyTargets, { Masks = {"Demo*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test table.insert(copyTargets, { Masks = {"*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../tests/", Target = "tests/" }) -- Processing os.mkdir(packageDir) local size = 0 for k,v in pairs(copyTargets) do local target = packageDir .. v.Target local includePrefix = v.Source local targetFiles = {} for k, mask in pairs(v.Masks) do print(includePrefix .. mask .. " => " .. target) local files = os.matchfiles(includePrefix .. mask) if (v.Filter) then for k,path in pairs(files) do if (not v.Filter(path)) then files[k] = nil end end end targetFiles = table.join(targetFiles, files) end for k,v in pairs(targetFiles) do local relPath = v:sub(#includePrefix + 1) local targetPath = target .. relPath local targetDir = path.getdirectory(targetPath) if (not os.isdir(targetDir)) then local ok, err = os.mkdir(targetDir) if (not ok) then print("Failed to create directory \"" .. targetDir .. "\": " .. err) end end local ok, err if (os.is("windows")) then ok, err = os.copyfile(v, targetPath) else -- Workaround: As premake is translating this to "cp %s %s", it fails if space are presents in source/destination paths. ok, err = os.copyfile(string.format("\"%s\"", v), string.format("\"%s\"", targetPath)) end if (not ok) then print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err) end local stat = os.stat(targetPath) if (stat) then size = size + stat.size end end end local config = libDir .. " - " .. enabledArchs print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size // (1024 * 1024), config)) end
newoption({ trigger = "pack-libdir", description = "Specifiy the subdirectory in lib/ to be used when packaging the project" }) ACTION.Name = "Package" ACTION.Description = "Pack Nazara binaries/include/lib together" ACTION.Function = function () local libDir = _OPTIONS["pack-libdir"] if (not libDir or #libDir == 0) then local libDirs = os.matchdirs("../lib/*") if (#libDirs > 1) then error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used") elseif (#libDirs == 0) then error("No subdirectory was found in the lib directory, have you built the engine yet?") else libDir = path.getname(libDirs[1]) print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used") end end local realLibDir = "../lib/" .. libDir .. "/" if (not os.isdir(realLibDir)) then error(string.format("\"%s\" doesn't seem to be an existing directory", realLibDir)) end local archEnabled = { ["x64"] = false, ["x86"] = false } local enabledArchs = {} for k,v in pairs(os.matchdirs(realLibDir .. "*")) do local arch = path.getname(v) if (archEnabled[arch] ~= nil) then archEnabled[arch] = true table.insert(enabledArchs, arch) else print("Unknown directory " .. v .. " found, ignored") end end enabledArchs = table.concat(enabledArchs, ", ") print(enabledArchs .. " arch found") local packageDir = "../package/" local copyTargets = { { -- Engine headers Masks = {"**.hpp", "**.inl"}, Source = "../include/", Target = "include/" }, { -- SDK headers Masks = {"**.hpp", "**.inl"}, Source = "../SDK/include/", Target = "include/" }, { -- Examples files Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../examples/", Target = "examples/" }, { -- Demo resources Masks = {"**.*"}, Source = "../examples/bin/resources/", Target = "examples/bin/resources/" }, -- Unit test sources { Masks = {"**.hpp", "**.inl", "**.cpp"}, Source = "../tests/", Target = "tests/src/" }, -- Unit test resources { Masks = {"**.*"}, Source = "../tests/resources/", Target = "tests/resources/" } } local binFileMasks local libFileMasks local exeFileExt local exeFilterFunc if (os.ishost("windows")) then binFileMasks = {"**.dll", "**.pdb"} libFileMasks = {"**.lib", "**.a"} exeFileExt = ".exe" exeFilterFunc = function (filePath) return true end else if (os.ishost("macosx")) then binFileMasks = {"**.dynlib"} else binFileMasks = {"**.so"} end libFileMasks = {"**.a"} exeFileExt = "" exeFilterFunc = function (filePath) return path.getextension(filePath):contains('/') end end for arch, enabled in pairs(archEnabled) do if (enabled) then local archLibSrc = realLibDir .. arch .. "/" local arch3rdPartyBinSrc = "../extlibs/lib/common/" .. arch .. "/" local archBinDst = "bin/" .. arch .. "/" local archLibDst = "lib/" .. arch .. "/" -- Engine/SDK binaries table.insert(copyTargets, { Masks = binFileMasks, Source = archLibSrc, Target = archBinDst }) -- Engine/SDK libraries table.insert(copyTargets, { Masks = libFileMasks, Source = archLibSrc, Target = archLibDst }) -- 3rd party binary dep table.insert(copyTargets, { Masks = binFileMasks, Source = arch3rdPartyBinSrc, Target = archBinDst }) end end -- Demo executable table.insert(copyTargets, { Masks = {"Demo*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../examples/bin/", Target = "examples/bin/" }) -- Unit test table.insert(copyTargets, { Masks = {"*" .. exeFileExt}, Filter = exeFilterFunc, Source = "../tests/", Target = "tests/" }) -- Processing os.mkdir(packageDir) local size = 0 for k,v in pairs(copyTargets) do local target = packageDir .. v.Target local includePrefix = v.Source local targetFiles = {} for k, mask in pairs(v.Masks) do print(includePrefix .. mask .. " => " .. target) local files = os.matchfiles(includePrefix .. mask) if (v.Filter) then for k,path in pairs(files) do if (not v.Filter(path)) then files[k] = nil end end end targetFiles = table.join(targetFiles, files) end for k,v in pairs(targetFiles) do local relPath = v:sub(#includePrefix + 1) local targetPath = target .. relPath local targetDir = path.getdirectory(targetPath) if (not os.isdir(targetDir)) then local ok, err = os.mkdir(targetDir) if (not ok) then print("Failed to create directory \"" .. targetDir .. "\": " .. err) end end local ok, err = os.copyfile(v, targetPath) if (not ok) then print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err) end local stat = os.stat(targetPath) if (stat) then size = size + stat.size end end end local config = libDir .. " - " .. enabledArchs print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size // (1024 * 1024), config)) end
Package: Fix resource copy on Linux
Package: Fix resource copy on Linux
Lua
mit
DigitalPulseSoftware/NazaraEngine
7c0415c793a74f0c4f0f817387cab71f46fb84a2
loot.lua
loot.lua
local mod = EPGP:NewModule("EPGP_Loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local pattern_cache = {} local function deformat(str, format) local pattern = pattern_cache[format] if not pattern then -- print(string.format("Format: %s", format)) -- Escape special characters pattern = format:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", function(c) return "%"..c end) -- print(string.format("Escaped pattern: %s", pattern)) -- Substitute formatting elements with captures (only s and d -- supported now). Obviously now a formatting element will look -- like %%s because we escaped the %. pattern = pattern:gsub("%%%%([sd])", { ["s"] = "(.-)", ["d"] = "(%d+)", }) --print(string.format("Final pattern: %s", pattern)) pattern_cache[format] = pattern end return str:match(pattern) end local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_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 local function ParseLootMessage(msg) local player = UnitName("player") local item, quantity = deformat(msg, LOOT_ITEM_SELF_MULTIPLE) if item and quantity then return player, item, tonumber(quantity) end quantity = 1 item = deformat(msg, LOOT_ITEM_SELF) if item then return player, item, tonumber(quantity) end player, item, quantity = deformat(msg, LOOT_ITEM_MULTIPLE) if player and item and quantity then return player, item, tonumber(quantity) end quantity = 1 player, item = deformat(msg, LOOT_ITEM) return player, item, tonumber(quantity) end function mod:CHAT_MSG_LOOT(event_type, msg) if not EPGP.db.profile.auto_loot or not IsRLorML() then return end local player, item, quantity = ParseLootMessage(msg) if not player or not item then return end local item_name, item_link, item_rarity = GetItemInfo(item) if item_rarity < EPGP.db.profile.auto_loot_threshold then return end local item_id = select(3, item_link:find("item:(%d+):")) if not item_id then return end item_id = tonumber(item_id:trim()) if not item_id then return end if ignored_items[item_id] then return end self:SendMessage("LootReceived", player, item_link, quantity) end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, itemLink = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not itemLink then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(itemLink) local r, g, b = GetItemQualityColor(itemRarity) local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end local function LootReceived(event_name, player, itemLink, quantity) tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1) end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:Debug() LootReceived("LootReceived", UnitName("player"), "\124cffa335ee|Hitem:39235:0:0:0:0:0:0:531162426:8\124h[Bone-Framed Bracers]\124h\124r") end function mod:OnEnable() self:RegisterEvent("CHAT_MSG_LOOT") self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") self:RegisterMessage("LootReceived", LootReceived) end
local mod = EPGP:NewModule("EPGP_Loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local pattern_cache = {} local function deformat(str, format) local pattern = pattern_cache[format] if not pattern then -- print(string.format("Format: %s", format)) -- Escape special characters pattern = format:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", function(c) return "%"..c end) -- print(string.format("Escaped pattern: %s", pattern)) -- Substitute formatting elements with captures (only s and d -- supported now). Obviously now a formatting element will look -- like %%s because we escaped the %. pattern = pattern:gsub("%%%%([sd])", { ["s"] = "(.-)", ["d"] = "(%d+)", }) --print(string.format("Final pattern: %s", pattern)) pattern_cache[format] = pattern end return str:match(pattern) end local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_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 local function ParseLootMessage(msg) local player = UnitName("player") local item, quantity = deformat(msg, LOOT_ITEM_SELF_MULTIPLE) if item and quantity then return player, item, tonumber(quantity) end quantity = 1 item = deformat(msg, LOOT_ITEM_SELF) if item then return player, item, tonumber(quantity) end player, item, quantity = deformat(msg, LOOT_ITEM_MULTIPLE) if player and item and quantity then return player, item, tonumber(quantity) end quantity = 1 player, item = deformat(msg, LOOT_ITEM) return player, item, tonumber(quantity) end function mod:CHAT_MSG_LOOT(event_type, msg) if not EPGP.db.profile.auto_loot or not IsRLorML() then return end local player, item, quantity = ParseLootMessage(msg) if not player or not item then return end local item_name, item_link, item_rarity = GetItemInfo(item) if item_rarity < EPGP.db.profile.auto_loot_threshold then return end local item_id = select(3, item_link:find("item:(%d+):")) if not item_id then return end item_id = tonumber(item_id:trim()) if not item_id then return end if ignored_items[item_id] then return end self:SendMessage("LootReceived", player, item_link, quantity) end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, itemLink = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not itemLink then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(itemLink) local r, g, b = GetItemQualityColor(itemRarity) local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end local function LootReceived(event_name, player, itemLink, quantity) if CanEditOfficerNote() then tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:Debug() LootReceived("LootReceived", UnitName("player"), "\124cffa335ee|Hitem:39235:0:0:0:0:0:0:531162426:8\124h[Bone-Framed Bracers]\124h\124r") end function mod:OnEnable() self:RegisterEvent("CHAT_MSG_LOOT") self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") self:RegisterMessage("LootReceived", LootReceived) end
Do not add items to the loot queue of awards if a member is not able to credit those GP. This fixes issue 286.
Do not add items to the loot queue of awards if a member is not able to credit those GP. This fixes issue 286.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp
2031b518b0d8cec7e9fc8f43f2a3a1f23d8cc1f8
xmake/actions/config/scanner.lua
xmake/actions/config/scanner.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file scanner.lua -- -- imports import("core.project.config") import("core.project.project") import("core.project.template") import("core.language.language") -- scan project and generate xmake.lua automaticlly if the project codes exist function make() -- trace cprint("${yellow}xmake.lua not found, scanning files ..") -- scan source files for the current directory local targetkinds = {} local sourcefiles = {} local sourcefiles_main = {} for extension, sourcekind in pairs(language.extensions()) do -- load language instance local instance = language.load_sk(sourcekind) -- get check main() script local check_main = instance:get("check_main") -- scan source files local filecount = 0 for _, sourcefile in ipairs(os.files("*" .. extension)) do if check_main and check_main(sourcefile) then table.insert(sourcefiles_main, sourcefile) else table.insert(sourcefiles, sourcefile) end filecount = filecount + 1 end -- add targetkinds if filecount > 0 then for targetkind, _ in pairs(instance:targetkinds()) do targetkinds[targetkind] = true end end end sourcefiles = table.unique(sourcefiles) sourcefiles_main = table.unique(sourcefiles_main) -- remove config directory first os.rm(config.directory()) -- project not found if #sourcefiles == 0 and #sourcefiles_main == 0 then raise("project not found!") end -- generate xmake.lua local file = io.open("xmake.lua", "w") if file then -- get target name local targetname = path.basename(os.curdir()) -- define static/binary target if #sourcefiles > 0 then -- get targetkind local targetkind = nil if targetkinds["static"] then targetkind = "static" elseif targetkinds["binary"] then targetkind = "binary" end assert(targetkind, "unknown target kind!") -- trace cprint("target(${magenta}%s${clear}): %s", targetname, targetkind) -- add target file:print("-- define target") file:print("target(\"%s\")", targetname) file:print("") file:print(" -- set kind") file:print(" set_kind(\"%s\")", targetkind) file:print("") file:print(" -- add files") for _, sourcefile in ipairs(sourcefiles) do -- trace cprint(" ${green}[+]: ${clear}%s", sourcefile) -- add file file:print(" add_files(\"%s\")", sourcefile) end file:print("") end -- define binary targets for _, sourcefile in ipairs(sourcefiles_main) do -- trace cprint("target(${magenta}%s${clear}): binary", path.basename(sourcefile)) cprint(" ${green}[+]: ${clear}%s", sourcefile) -- add target file:print("-- define target") file:print("target(\"%s\")", path.basename(sourcefile)) file:print("") file:print(" -- set kind") file:print(" set_kind(\"binary\")") file:print("") file:print(" -- add files") file:print(" add_files(\"%s\")", sourcefile) file:print("") -- add deps if #sourcefiles > 0 then file:print(" -- add deps") file:print(" add_deps(\"%s\")", targetname) file:print("") end end -- add FAQ file:print(template.faq()) -- exit file file:close() end -- generate .gitignore if not exists if not os.isfile(".gitignore") then os.cp("$(programdir)/scripts/gitignore", ".gitignore") end -- trace cprint("${bright}xmake.lua generated, scan ok!${clear}${ok_hand}") end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file scanner.lua -- -- imports import("core.project.config") import("core.project.project") import("core.project.template") import("core.language.language") -- scan project and generate xmake.lua automaticlly if the project codes exist function make() -- trace cprint("${yellow}xmake.lua not found, scanning files ..") -- scan source files for the current directory local targetkinds = {} local sourcefiles = {} local sourcefiles_main = {} for extension, sourcekind in pairs(language.extensions()) do -- load language instance local instance = language.load_sk(sourcekind) -- get check main() script local check_main = instance:get("check_main") -- scan source files local filecount = 0 for _, sourcefile in ipairs(os.files("*" .. extension)) do if check_main and check_main(sourcefile) then table.insert(sourcefiles_main, sourcefile) else table.insert(sourcefiles, sourcefile) end filecount = filecount + 1 end -- add targetkinds if filecount > 0 then for targetkind, _ in pairs(instance:targetkinds()) do targetkinds[targetkind] = true end end end sourcefiles = table.unique(sourcefiles) sourcefiles_main = table.unique(sourcefiles_main) -- remove config directory first os.rm(config.directory()) -- project not found if #sourcefiles == 0 and #sourcefiles_main == 0 then raise("project not found!") end -- generate xmake.lua local file = io.open("xmake.lua", "w") if file then -- get target name local targetname = path.basename(os.curdir()) -- define static/binary target if #sourcefiles > 0 then -- get targetkind local targetkind = nil if targetkinds["static"] then targetkind = "static" elseif targetkinds["binary"] then targetkind = "binary" end assert(targetkind, "unknown target kind!") -- trace cprint("target(${magenta}%s${clear}): %s", targetname, targetkind) -- add target file:print("-- define target") file:print("target(\"%s\")", targetname) file:print("") file:print(" -- set kind") file:print(" set_kind(\"%s\")", targetkind) file:print("") file:print(" -- add files") for _, sourcefile in ipairs(sourcefiles) do -- trace cprint(" ${green}[+]: ${clear}%s", sourcefile) -- add file file:print(" add_files(\"%s\")", sourcefile) end file:print("") end -- define binary targets for _, sourcefile in ipairs(sourcefiles_main) do -- trace local name = path.basename(sourcefile) if name == targetname then name = name .. "1" end cprint("target(${magenta}%s${clear}): binary", name) cprint(" ${green}[+]: ${clear}%s", sourcefile) -- add target file:print("-- define target") file:print("target(\"%s\")", name) file:print("") file:print(" -- set kind") file:print(" set_kind(\"binary\")") file:print("") file:print(" -- add files") file:print(" add_files(\"%s\")", sourcefile) file:print("") -- add deps if #sourcefiles > 0 then file:print(" -- add deps") file:print(" add_deps(\"%s\")", targetname) file:print("") end end -- add FAQ file:print(template.faq()) -- exit file file:close() end -- generate .gitignore if not exists if not os.isfile(".gitignore") then os.cp("$(programdir)/scripts/gitignore", ".gitignore") end -- trace cprint("${bright}xmake.lua generated, scan ok!${clear}${ok_hand}") end
fix name conflict for scanner
fix name conflict for scanner
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake
c216164d742e2987da7da1b00daacdfd9fa933b3
mark.lua
mark.lua
worldedit.marker1 = {} worldedit.marker2 = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos = worldedit.pos1[name] if worldedit.marker1[name] == nil then --marker does not yet exist if pos ~= nil then --add marker worldedit.marker1[name] = minetest.env:add_entity(pos, "worldedit:pos1") end else --marker already exists if pos == nil then --remove marker worldedit.marker1[name]:remove() worldedit.marker1[name] = nil else --move marker worldedit.marker1[name]:setpos(pos) end end end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos = worldedit.pos2[name] if worldedit.marker2[name] == nil then --marker does not yet exist if pos ~= nil then --add marker worldedit.marker2[name] = minetest.env:add_entity(pos, "worldedit:pos2") end else --marker already exists if pos == nil then --remove marker worldedit.marker2[name]:remove() worldedit.marker2[name] = nil else --move marker worldedit.marker2[name]:setpos(pos) end end end minetest.register_entity("worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, }, on_punch = function(self, hitter) self.object:remove() local name = hitter:get_player_name() worldedit.marker1[name] = nil end, }) minetest.register_entity("worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, }, on_punch = function(self, hitter) self.object:remove() local name = hitter:get_player_name() worldedit.marker2[name] = nil end, })
worldedit.marker1 = {} worldedit.marker2 = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos = worldedit.pos1[name] if worldedit.marker1[name] ~= nil then --marker already exists worldedit.marker1[name]:remove() --remove marker worldedit.marker1[name] = nil end if pos ~= nil then --add marker worldedit.marker1[name] = minetest.env:add_entity(pos, "worldedit:pos1") end end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos = worldedit.pos2[name] if worldedit.marker2[name] ~= nil then --marker already exists worldedit.marker2[name]:remove() --remove marker worldedit.marker2[name] = nil end if pos ~= nil then --add marker worldedit.marker2[name] = minetest.env:add_entity(pos, "worldedit:pos2") end end minetest.register_entity("worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, }, on_punch = function(self, hitter) self.object:remove() local name = hitter:get_player_name() worldedit.marker1[name] = nil end, }) minetest.register_entity("worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, }, on_punch = function(self, hitter) self.object:remove() local name = hitter:get_player_name() worldedit.marker2[name] = nil end, })
Simplify marker placement and fix wierd bug where object:setpos() didn't work.
Simplify marker placement and fix wierd bug where object:setpos() didn't work.
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
e74163ee0704f535f726e0754a183f7c9c46d023
mod_auto_accept_subscriptions/mod_auto_accept_subscriptions.lua
mod_auto_accept_subscriptions/mod_auto_accept_subscriptions.lua
local rostermanager = require "core.rostermanager"; local jid = require "util.jid"; local st = require "util.stanza"; local core_post_stanza = prosody.core_post_stanza; local function handle_inbound_subscription_request(origin, stanza) local to_bare, from_bare = jid.bare(stanza.attr.to), jid.bare(stanza.attr.from); local node, host = jid.split(to_bare); stanza.attr.from, stanza.attr.to = from_bare, to_bare; module:log("info", "Auto-accepting inbound subscription request from %s to %s", from_bare, to_bare); if not rostermanager.is_contact_subscribed(node, host, from_bare) then core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt module:log("debug", "receipt acknowledged"); if rostermanager.set_contact_pending_in(node, host, from_bare) then module:log("debug", "set pending in"); if rostermanager.subscribed(node, host, from_bare) then module:log("debug", "set subscribed"); rostermanager.roster_push(node, host, to_bare); module:log("debug", "pushed roster item"); local subscribed_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribed"; core_post_stanza(hosts[host], subscribed_stanza); module:log("debug", "sent subscribed"); hosts[host].modules.presence.send_presence_of_available_resources(node, host, to_bare, origin); module:log("debug", "sent available presence of all resources"); -- Add return subscription from user to contact local subscribe_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribe"; if rostermanager.set_contact_pending_out(node, host, from_bare) then rostermanager.roster_push(node, host, from_bare); end core_post_stanza(hosts[host], subscribe_stanza); return true; end end end module:log("warn", "Failed to auto-accept subscription request from %s to %s", from_bare, to_bare); end module:hook("presence/bare", function (event) local stanza = event.stanza; if stanza.attr.type == "subscribe" then handle_inbound_subscription_request(event.origin, stanza); return true; end end, 0.1);
local rostermanager = require "core.rostermanager"; local jid = require "util.jid"; local st = require "util.stanza"; local core_post_stanza = prosody.core_post_stanza; local function handle_inbound_subscription_request(origin, stanza) local to_bare, from_bare = jid.bare(stanza.attr.to), jid.bare(stanza.attr.from); local node, host = jid.split(to_bare); stanza.attr.from, stanza.attr.to = from_bare, to_bare; module:log("info", "Auto-accepting inbound subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); if not rostermanager.is_contact_subscribed(node, host, from_bare) then core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt module:log("debug", "receipt acknowledged"); if rostermanager.set_contact_pending_in(node, host, from_bare) then module:log("debug", "set pending in"); if rostermanager.subscribed(node, host, from_bare) then module:log("debug", "set subscribed"); rostermanager.roster_push(node, host, to_bare); module:log("debug", "pushed roster item"); local subscribed_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribed"; core_post_stanza(hosts[host], subscribed_stanza); module:log("debug", "sent subscribed"); hosts[host].modules.presence.send_presence_of_available_resources(node, host, to_bare, origin); module:log("debug", "sent available presence of all resources"); -- Add return subscription from user to contact local subscribe_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribe"; if rostermanager.set_contact_pending_out(node, host, from_bare) then rostermanager.roster_push(node, host, from_bare); end core_post_stanza(hosts[host], subscribe_stanza); return true; end end end module:log("warn", "Failed to auto-accept subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); end module:hook("presence/bare", function (event) local stanza = event.stanza; if stanza.attr.type == "subscribe" then handle_inbound_subscription_request(event.origin, stanza); return true; end end, 0.1);
mod_auto_accept_subscriptions: Fix passing nil in log message
mod_auto_accept_subscriptions: Fix passing nil in log message
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
f0100ab02f193945cc88ac7995c6752980847ee6
Core.lua
Core.lua
local L = EPGPGlobalStrings EPGP = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0", "AceDebug-2.0", "AceEvent-2.0", "AceModuleCore-2.0") ------------------------------------------------------------------------------- -- DB defaults ------------------------------------------------------------------------------- EPGP:RegisterDB("EPGP_Core_DB", "EPGP_Core_PerCharDB") EPGP:RegisterDefaults("profile", { report_channel = "GUILD", current_listing = "GUILD", RAID = { show_alts = true, }, GUILD = { show_alts = false, }, gp_in_tooltips = true, master_loot_popup = true, master_loot_popup_quality_threshold = 2, -- Rare and above alts = {}, outsiders = {}, dummies = {}, data = {}, info = {}, flat_credentials = false, min_eps = 1000, decay_percent = 10, group_by_class = false, backup_notes = {}, recurring_ep_period = 15 * 60, }) function EPGP:OnEnable() --EPGP:SetDebugging(true) BINDING_HEADER_EPGP = L["EPGP Options"] BINDING_NAME_EPGP = L["Toggle EPGP UI"] -- Set shift-E as the toggle button if it is not bound if #GetBindingAction("J") == 0 then SetBinding("J", "EPGP") -- Save to character bindings SaveBindings(2) end self:RegisterChatCommand({ "/epgp" }, { type = "group", desc = L["EPGP Options"], args = { ["show"] = { type = "execute", name = L["Show UI"], desc = L["Shows the EPGP UI"], disabled = function() return EPGPFrame:IsShown() end, func = function() ShowUIPanel(EPGPFrame) end, order = 1, }, ["decay"] = { type = "execute", name = L["Decay EP and GP"], desc = string.format(L["Decay EP and GP by %d%%"], EPGP.db.profile.decay_percent), disabled = function() return not self:GetModule("EPGP_Backend"):CanLogRaids() end, func = function() self:GetModule("EPGP_Backend"):NewRaid() end, order = 4, confirm = string.format(L["Decay EP and GP by %d%%?"], EPGP.db.profile.decay_percent), }, ["reset"] = { type = "execute", name = L["Reset EPGP"], desc = L["Reset all EP and GP to 0 and make officer notes readable by all."], guiHidden = true, disabled = function() return not self:GetModule("EPGP_Backend"):CanChangeRules() end, func = function() self:GetModule("EPGP_Backend"):ResetEPGP() end, confirm = L["Reset all EP and GP to 0 and make officer notes readable by all?"], order = 11, }, }, }, "EPGP") end
local L = EPGPGlobalStrings EPGP = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0", "AceDebug-2.0", "AceEvent-2.0", "AceModuleCore-2.0") ------------------------------------------------------------------------------- -- DB defaults ------------------------------------------------------------------------------- EPGP:RegisterDB("EPGP_Core_DB", "EPGP_Core_PerCharDB") EPGP:RegisterDefaults("profile", { report_channel = "GUILD", current_listing = "GUILD", RAID = { show_alts = true, }, GUILD = { show_alts = false, }, gp_in_tooltips = true, master_loot_popup = true, master_loot_popup_quality_threshold = 2, -- Rare and above alts = {}, outsiders = {}, dummies = {}, data = {}, info = {}, flat_credentials = false, min_eps = 1000, decay_percent = 10, group_by_class = false, backup_notes = {}, recurring_ep_period = 15 * 60, }) function EPGP:OnInitialize() self:RegisterChatCommand({ "/epgp" }, { type = "group", desc = L["EPGP Options"], args = { ["show"] = { type = "execute", name = L["Show UI"], desc = L["Shows the EPGP UI"], disabled = function() return EPGPFrame:IsShown() end, func = function() ShowUIPanel(EPGPFrame) end, order = 1, }, ["decay"] = { type = "execute", name = L["Decay EP and GP"], desc = string.format(L["Decay EP and GP by %d%%"], EPGP.db.profile.decay_percent), disabled = function() return not self:GetModule("EPGP_Backend"):CanLogRaids() end, func = function() self:GetModule("EPGP_Backend"):NewRaid() end, order = 4, confirm = string.format(L["Decay EP and GP by %d%%?"], EPGP.db.profile.decay_percent), }, ["reset"] = { type = "execute", name = L["Reset EPGP"], desc = L["Reset all EP and GP to 0 and make officer notes readable by all."], guiHidden = true, disabled = function() return not self:GetModule("EPGP_Backend"):CanChangeRules() end, func = function() self:GetModule("EPGP_Backend"):ResetEPGP() end, confirm = L["Reset all EP and GP to 0 and make officer notes readable by all?"], order = 11, }, }, }, "EPGP") end function EPGP:OnEnable() --EPGP:SetDebugging(true) BINDING_HEADER_EPGP = L["EPGP Options"] BINDING_NAME_EPGP = L["Toggle EPGP UI"] -- Set shift-E as the toggle button if it is not bound if #GetBindingAction("J") == 0 then SetBinding("J", "EPGP") -- Save to character bindings SaveBindings(2) end end
Fix problem with epgp hiding command line interface when suspended (Issue 114)
Fix problem with epgp hiding command line interface when suspended (Issue 114)
Lua
bsd-3-clause
hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,protomech/epgp-dkp-reloaded,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf
4d348c4450786efb10e5f0e9699730984a4d5131
scripts/src/h.lua
scripts/src/h.lua
require "lmkbuild" local assert = assert local append = lmkbuild.append_local local cp = lmkbuild.cp local file_newer = lmkbuild.file_newer local ipairs = ipairs local is_valid = lmkbuild.is_valid local mkdir = lmkbuild.mkdir local print = print local resolve = lmkbuild.resolve local rm = lmkbuild.rm local split = lmkbuild.split local sys = lmkbuild.system () module (...) function main (files) if sys == "iphone" then mkdir ("$(lmk.includeDir)dmz/") append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)dmz/") else mkdir ("$(lmk.includeDir)$(name)") append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)$(name)/") end for index, item in ipairs (files) do item = resolve (item) p, f, e = split (item) if sys == "iphone" then file = "$(lmk.includeDir)dmz/" .. f .. "." .. e else file = "$(lmk.includeDir)$(name)/" .. f .. "." .. e end if file_newer (item, file) then print ("Exporting: " .. item) assert ( cp (item, file), "Failed copying file: " .. item .. " to " .. resolve (file)) end end end function test (files) main (files) end function clean (files) for index, item in ipairs (files) do local p, file, e = split (item) if sys == "iphone" then file = resolve ("$(lmk.includeDir)dmz/" .. f .. "." .. e) else file = resolve ("$(lmk.includeDir)$(name)/" .. f .. "." .. e) end if is_valid (file) then rm (file) end end end function clobber (files) clean (files) end
require "lmkbuild" local assert = assert local append = lmkbuild.append_local local cp = lmkbuild.cp local file_newer = lmkbuild.file_newer local ipairs = ipairs local is_valid = lmkbuild.is_valid local mkdir = lmkbuild.mkdir local print = print local resolve = lmkbuild.resolve local rm = lmkbuild.rm local split = lmkbuild.split local sys = lmkbuild.system () module (...) function main (files) if sys == "iphone" then mkdir ("$(lmk.includeDir)dmz/") append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)dmz/") else mkdir ("$(lmk.includeDir)$(name)") append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)$(name)/") end for index, item in ipairs (files) do local file = nil local item = resolve (item) local p, f, e = split (item) if sys == "iphone" then file = "$(lmk.includeDir)dmz/" .. f .. "." .. e else file = "$(lmk.includeDir)$(name)/" .. f if e then file = file .. "." .. e end end if file_newer (item, file) then print ("Exporting: " .. item) assert ( cp (item, file), "Failed copying file: " .. item .. " to " .. resolve (file)) end end end function test (files) main (files) end function clean (files) for index, item in ipairs (files) do local file = nil local p, f, e = split (item) if sys == "iphone" then file = resolve ("$(lmk.includeDir)dmz/" .. f .. "." .. e) else if e then file = resolve ("$(lmk.includeDir)$(name)/" .. f .. "." .. e) else file = resolve ("$(lmk.includeDir)$(name)/" .. f) end end if is_valid (file) then rm (file) end end end function clobber (files) clean (files) end
bug fix when header file is missing the .h
bug fix when header file is missing the .h
Lua
mit
dmzgroup/lmk,shillcock/lmk
1fadd23e8bf611248c8c09c52fbb6029a6998226
MMOCoreORB/bin/scripts/object/tangible/instrument/base/instrument_base.lua
MMOCoreORB/bin/scripts/object/tangible/instrument/base/instrument_base.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_instrument_base_instrument_base = object_tangible_instrument_base_shared_instrument_base:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" } } ObjectTemplates:addTemplate(object_tangible_instrument_base_instrument_base, "object/tangible/instrument/base/instrument_base.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_instrument_base_instrument_base = object_tangible_instrument_base_shared_instrument_base:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/ithorian_male.iff" } } ObjectTemplates:addTemplate(object_tangible_instrument_base_instrument_base, "object/tangible/instrument/base/instrument_base.iff")
[fixed] missed some races
[fixed] missed some races git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4209 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
196d216c8f30b3251b2504a7ad1bd304c0c7760d
stdlib/log/logger.lua
stdlib/log/logger.lua
--- Logger module -- @module log Logger = {} --- Creates a new logger object -- In debug mode, the logger writes immediately. Otherwise it buffers lines. -- Logger flushes after 60 seconds has elapsed since the last message. -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G["game"] then local floor = math.floor local time_s = floor(game.tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d\.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, game.tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (game.tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G["game"] then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
--- Logger module -- @module log Logger = {} --- Creates a new logger object -- In debug mode, the logger writes immediately. Otherwise it buffers lines. -- Logger flushes after 60 seconds has elapsed since the last message. -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G["game"] then local tick = game.tick local floor = math.floor local time_s = floor(tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G["game"] then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
A bit of logger optimization and fix invalid escape sequence
A bit of logger optimization and fix invalid escape sequence
Lua
isc
Afforess/Factorio-Stdlib
d054497edaab5e132cd39270eeeaf0de925b9137
server.lua
server.lua
-- https://github.com/szym/display -- Copyright (c) 2015, Szymon Jakubczak (MIT License) -- Forwards any data POSTed to /events to an event-stream at /events. -- Serves files from /static otherwise. local async = require('async') local sys = require('sys') local function getMime(ext) if ext == '.css' then return 'text/css' elseif ext == '.js' then return 'text/javascript' else return 'text/html' -- TODO: other mime types end end local subscribers = {} local function handler(req, res, client) print(req.method, req.url.path) if req.url.path == '/events' then local headers = { ['Content-Type'] = 'text/event-stream', ['Cache-Control'] = 'no-cache', ['Connection'] = 'keep-alive', ['Transfer-Encoding'] = 'chunked' } if req.method == 'GET' then res('', headers, 200) table.insert(subscribers, client) elseif req.method == 'POST' then local body = req.body for i=1,#subscribers do local client = subscribers[i] assert(type(body) == 'string') -- send chunk local headlen = 8 client.write(string.format('%x\r\n', #body + headlen)) client.write('data: ') -- 6 client.write(body) client.write('\n\n') -- 2 client.write('\r\n') end res('', {}) else res('Invalid method!', {}, 405) end else -- serve files from static local path = req.url.path if path == '/' or path == '' then path = '/index.html' end local ext = string.match(path, "%.%l%l%l?") local mime = getMime(ext) local file = io.open(sys.fpath() .. '/static' .. path, 'r') if file ~= nil then local content = file:read("*all") file:close() res(content, {['Content-Type']=mime}) else res('Not found!', {}, 404) end end end function server(hostname, port) async.http.listen('http://' .. hostname .. ':' .. port .. '/', handler) print('server listening on http://' .. hostname .. ':' .. port) async.go() end return server
-- https://github.com/szym/display -- Copyright (c) 2015, Szymon Jakubczak (MIT License) -- Forwards any data POSTed to /events to an event-stream at /events. -- Serves files from /static otherwise. local async = require('async') local paths = require('paths') local sys = require('sys') local function getMime(ext) if ext == '.css' then return 'text/css' elseif ext == '.js' then return 'text/javascript' else return 'text/html' -- TODO: other mime types end end local subscribers = {} local function handler(req, res, client) print(req.method, req.url.path) if req.url.path == '/events' then local headers = { ['Content-Type'] = 'text/event-stream', ['Cache-Control'] = 'no-cache', ['Connection'] = 'keep-alive', ['Transfer-Encoding'] = 'chunked' } if req.method == 'GET' then res('', headers, 200) table.insert(subscribers, client) elseif req.method == 'POST' then local body = req.body for i=1,#subscribers do local client = subscribers[i] assert(type(body) == 'string') -- send chunk local headlen = 8 client.write(string.format('%x\r\n', #body + headlen)) client.write('data: ') -- 6 client.write(body) client.write('\n\n') -- 2 client.write('\r\n') end res('', {}) else res('Invalid method!', {}, 405) end else -- serve files from static local path = req.url.path if path == '/' or path == '' then path = '/index.html' end local ext = string.match(path, "%.%l%l%l?") local mime = getMime(ext) local file = io.open(paths.dirname(sys.fpath()) .. '/static' .. path, 'r') if file ~= nil then local content = file:read("*all") file:close() res(content, {['Content-Type']=mime}) else res('Not found!', {}, 404) end end end function server(hostname, port) async.http.listen('http://' .. hostname .. ':' .. port .. '/', handler) print('server listening on http://' .. hostname .. ':' .. port) async.go() end return server
Fix misuse of sys.fpath()
Fix misuse of sys.fpath()
Lua
mit
szym/display,szym/display,szym/display,szym/display
daf9b6caca19906059e05ae57d7dfd3be0c0d6a6
SpatialConvolution.lua
SpatialConvolution.lua
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padding = padding or 0 self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() self.padding = self.padding or 0 if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end function SpatialConvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padding = padding or 0 self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() self.padding = self.padding or 0 if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function makeContiguous(self, input, gradOutput) if not input:isContiguous() then self._input = self._input or input.new() self._input:resizeAs(input):copy(input) input = self._input end if gradOutput then if not gradOutput:isContiguous() then self._gradOutput = self._gradOutput or gradOutput.new() self._gradOutput:resizeAs(gradOutput):copy(gradOutput) gradOutput = self._gradOutput end end return input, gradOutput end -- function to re-view the weight layout in a way that would make the MM ops happy local function viewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end end local function unviewWeight(self) self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end function SpatialConvolution:updateOutput(input) backCompatibility(self) viewWeight(self) input = makeContiguous(self, input) local out = input.nn.SpatialConvolutionMM_updateOutput(self, input) unviewWeight(self) return out end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then backCompatibility(self) viewWeight(self) input, gradOutput = makeContiguous(self, input, gradOutput) local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput) unviewWeight(self) return out end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) backCompatibility(self) input, gradOutput = makeContiguous(self, input, gradOutput) viewWeight(self) local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale) unviewWeight(self) return out end function SpatialConvolution:type(type) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self,type) end
SpatialConvolution empty gradParams fix
SpatialConvolution empty gradParams fix
Lua
bsd-3-clause
andreaskoepf/nn,PierrotLC/nn,Djabbz/nn,sbodenstein/nn,PraveerSINGH/nn,hery/nn,davidBelanger/nn,fmassa/nn,eulerreich/nn,abeschneider/nn,Moodstocks/nn,GregSatre/nn,apaszke/nn,lukasc-ch/nn,ivendrov/nn,caldweln/nn,adamlerer/nn,ominux/nn,nicholas-leonard/nn,lvdmaaten/nn,joeyhng/nn,elbamos/nn,Aysegul/nn,Jeffyrao/nn,aaiijmrtt/nn,jzbontar/nn,colesbury/nn,jonathantompson/nn,witgo/nn,kmul00/nn,clementfarabet/nn,rotmanmi/nn,noa/nn,hughperkins/nn,mys007/nn,vgire/nn,bartvm/nn,xianjiec/nn,boknilev/nn,karpathy/nn,zchengquan/nn,jhjin/nn,douwekiela/nn,sagarwaghmare69/nn,LinusU/nn,eriche2016/nn,forty-2/nn,szagoruyko/nn,zhangxiangxiao/nn,EnjoyHacking/nn,mlosch/nn,diz-vara/nn
510e85f53be3216f9ab3d9179d92dfa7cb1da6f2
deps/ustring.lua
deps/ustring.lua
local ustring = {} local tostring = tostring local _meta = {} local strsub = string.sub local strbyte = string.byte local band = bit.band local rshift = bit.rshift local function chlen(byte) if rshift(byte,7) == 0x00 then return 1 elseif rshift(byte,5) == 0x06 then return 2 elseif rshift(byte,4) == 0x0E then return 3 elseif rshift(byte,3) == 0x1E then return 4 else -- RFC 3629 (2003.11) says UTF-8 don't have characters larger than 4 bytes. -- They will not be processed although they may be appeared in some old systems. return 0 end end ustring.chlen = chlen function ustring.new(str,allowInvaild) local str = str and tostring(str) or "" local ustr = {} local index = 1; local append = 0; for i = 1,#str do repeat local char = strsub(str,i,i) local byte = strbyte(char) if append ~= 0 then if not allowInvaild then if rshift(byte,6) ~= 0x02 then error("Invaild UTF-8 sequence at "..i) end end ustr[index] = ustr[index] .. char append = append - 1 if append == 0 then index = index + 1 end break end local charLen = chlen(byte) assert(charLen ~= 0 or allowInvaild,"Invaild UTF-8 sequence at "..tostring(i)..",byte:"..tostring(byte)) ustr[index] = char if charLen == 1 then index = index + 1 end append = append + charLen - 1 until true end setmetatable(ustr,_meta) return ustr end function ustring.copy(ustr) local u = ustring.new() for i = 1,#ustr do u[i] = ustr[i] end return u end function ustring.uindex(ustr,rawindex,initrawindex,initindex) -- get the index of the UTF-8 character from a raw string index -- return `nil` when rawindex is invaild -- the last 2 arguments is used for speed up local index = (initindex or 1) rawindex = rawindex - (initrawindex or 1) + 1 repeat local byte = ustr[index] if byte == nil then return nil end local len = #byte index = index + 1 rawindex = rawindex - len until rawindex <= 0 return index - 1 end local gsub = string.gsub local find = string.find local format = string.format local gmatch = string.gmatch local match = string.match local lower = string.lower local upper = string.upper ustring.len = rawlen function ustring.gsub(ustr,pattern,repl,n) return ustring.new(gsub(tostring(ustr),tostring(pattern),tostring(repl),n)) end function ustring.sub(ustr,i,j) local u = ustring.new() j = j or -1 local len = #ustr if i < 0 then i = len + i + 1 end if j < 0 then j = len + j + 1 end for ii = i,math.min(j,len) do u[#u + 1] = ustr[ii] end return u end function ustring.find(ustr,pattern,init,plain) local first,last = find(tostring(ustr),tostring(pattern),init,plain) local ufirst = ustring.uindex(ustr,first) local ulast = ustring.uindex(ustr,last,first,ufirst) return ufirst,ulast end function ustring.format(formatstring,...) return ustring.new(format(tostring(formatstring),...)) end function ustring.gmatch(ustr,pattern) return gmatch(tostring(ustr),pattern) end function ustring.match(ustr,pattern,init) return match(tostring(ustr),tostring(pattern),init) end function ustring.lower(ustr) local u = ustring.copy(ustr) for i = 1,#u do u = lower(u) end return u end function ustring.upper(ustr) local u = ustring.copy(ustr) for i = 1,#u do u = upper(u) end return u end function ustring.rep(ustr,n) local u = ustring.new() for i = 1,n do for ii = 1,#ustr do u[#u + 1] = ustr[ii] end end return u end function ustring.reverse(ustr) local u = ustring.copy(ustr) local len = #ustr; for i = 1,len do u[i] = ustr[len - i + 1] end return u end _meta.__index = ustring function _meta.__eq(ustr1,ustr2) if type(ustr2) == "string" then return tostring(ustr1) == ustr2 end local len1 = #ustr1 local len2 = #ustr2 if len1 ~= len2 then return false end for i = 1,len1 do if ustr1[i] ~= ustr2[i] then return false end end return true end function _meta.__tostring(self) return tostring(table.concat(self)) end function _meta.__concat(ustr1,ustr2) local u = ustring.copy(ustr1) for i = 1,#ustr2 do u[#u + 1] = ustr2[i] end return u end _meta.__len = ustring.len return ustring
local ustring = {} local tostring = tostring local _meta = {} local strsub = string.sub local strbyte = string.byte local band = bit.band local rshift = bit.rshift local function chlen(byte) if rshift(byte,7) == 0x00 then return 1 elseif rshift(byte,5) == 0x06 then return 2 elseif rshift(byte,4) == 0x0E then return 3 elseif rshift(byte,3) == 0x1E then return 4 else -- RFC 3629 (2003.11) says UTF-8 don't have characters larger than 4 bytes. -- They will not be processed although they may be appeared in some old systems. return 0 end end ustring.chlen = chlen function ustring.new(str,allowInvaild) local str = str and tostring(str) or "" local ustr = {} local index = 1; local append = 0; for i = 1,#str do repeat local char = strsub(str,i,i) local byte = strbyte(char) if append ~= 0 then if not allowInvaild then if rshift(byte,6) ~= 0x02 then error("Invaild UTF-8 sequence at "..i) end end ustr[index] = ustr[index] .. char append = append - 1 if append == 0 then index = index + 1 end break end local charLen = chlen(byte) if charLen == 0 and not allowInvaild then error("Invaild UTF-8 sequence at "..tostring(i)..",byte:"..tostring(byte)) end ustr[index] = char if charLen == 1 then index = index + 1 end append = append + charLen - 1 until true end setmetatable(ustr,_meta) return ustr end function ustring.copy(ustr) local u = ustring.new() for i = 1,#ustr do u[i] = ustr[i] end return u end function ustring.uindex(ustr,rawindex,initrawindex,initindex) -- get the index of the UTF-8 character from a raw string index -- return `nil` when rawindex is invaild -- the last 2 arguments is used for speed up local index = (initindex or 1) rawindex = rawindex - (initrawindex or 1) + 1 repeat local byte = ustr[index] if byte == nil then return nil end local len = #byte index = index + 1 rawindex = rawindex - len until rawindex <= 0 return index - 1 end local gsub = string.gsub local find = string.find local format = string.format local gmatch = string.gmatch local match = string.match local lower = string.lower local upper = string.upper ustring.len = rawlen function ustring.gsub(ustr,pattern,repl,n) return ustring.new(gsub(tostring(ustr),tostring(pattern),tostring(repl),n)) end function ustring.sub(ustr,i,j) local u = ustring.new() j = j or -1 local len = #ustr if i < 0 then i = len + i + 1 end if j < 0 then j = len + j + 1 end for ii = i,math.min(j,len) do u[#u + 1] = ustr[ii] end return u end function ustring.find(ustr,pattern,init,plain) local first,last = find(tostring(ustr),tostring(pattern),init,plain) local ufirst = ustring.uindex(ustr,first) local ulast = ustring.uindex(ustr,last,first,ufirst) return ufirst,ulast end function ustring.format(formatstring,...) return ustring.new(format(tostring(formatstring),...)) end function ustring.gmatch(ustr,pattern) return gmatch(tostring(ustr),pattern) end function ustring.match(ustr,pattern,init) return match(tostring(ustr),tostring(pattern),init) end function ustring.lower(ustr) local u = ustring.copy(ustr) for i = 1,#u do u = lower(u) end return u end function ustring.upper(ustr) local u = ustring.copy(ustr) for i = 1,#u do u = upper(u) end return u end function ustring.rep(ustr,n) local u = ustring.new() for i = 1,n do for ii = 1,#ustr do u[#u + 1] = ustr[ii] end end return u end function ustring.reverse(ustr) local u = ustring.copy(ustr) local len = #ustr; for i = 1,len do u[i] = ustr[len - i + 1] end return u end _meta.__index = ustring function _meta.__eq(ustr1,ustr2) if type(ustr2) == "string" then return tostring(ustr1) == ustr2 end local len1 = #ustr1 local len2 = #ustr2 if len1 ~= len2 then return false end for i = 1,len1 do if ustr1[i] ~= ustr2[i] then return false end end return true end function _meta.__tostring(self) return tostring(table.concat(self)) end function _meta.__concat(ustr1,ustr2) local u = ustring.copy(ustr1) for i = 1,#ustr2 do u[#u + 1] = ustr2[i] end return u end _meta.__len = ustring.len return ustring
little fix
little fix
Lua
apache-2.0
luvit/luvit,zhaozg/luvit,zhaozg/luvit,luvit/luvit
0266ebeab06a910cd4ea58f99dbd8f98cf402937
extensions/logger/init.lua
extensions/logger/init.lua
--- === hs.logger === --- --- Simple logger for debugging purposes -- * This can mainly be useful for diagnosing complex scripts; however there is some overhead involved. -- * Implementing a mock version could help, although not completely as lua lacks lazy evaluation local date,time = os.date,os.time local format,sub=string.format,string.sub local select,print,concat,min=select,print,table.concat,math.min local fnutils=require'hs.fnutils' local ERROR , WARNING , INFO , DEBUG , VERBOSE =1,2,3,4,5 local levels={'error','warning','info','debug','verbose'} levels[0]='nothing' local slevels={{'ERROR',''},{'Warn:',''},{'',''},{'','-- '},{'',' -- '}} local lastid local lasttime=0 local fmt={'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',} local lf = function(loglevel,lvl,id,fmt,...) if loglevel<lvl then return end local ct = time() local stime = ' ' if ct-lasttime>0 or lvl<3 then stime=date('%X') lasttime=ct end if id==lastid and lvl>3 then id=' ' else lastid=id end print(format('%s %s%s %s'..fmt,stime,slevels[lvl][1],id,slevels[lvl][2],...)) end local l = function(loglevel,lvl,id,...) if loglevel>=lvl then return lf(loglevel,lvl,id,concat(fmt,' ',1,min(select('#',...),#fmt)),...) end end --- hs.logger.new(id, loglevel) -> logger --- Function --- Creates a new logger instance --- --- Parameters: --- * id - a string identifier for the instance (usually the module name) --- * loglevel - can be 'nothing', 'error', 'warning', 'info', 'debug', or 'verbose'; or a corresponding number between 0 and 5; defaults to 'warning' if omitted --- --- Returns: --- * the new logger instance --- --- Usage: --- * `local log = hs.logger.new('mymodule','debug')` --- * `log.i('Initializing')` -- will print `[mymodule] Initializing` to the console local function new(id,loglevel) if type(id)~='string' then error('id must be a string',2) end id=format('%10s','['..format('%.8s',id)..']') local function setLogLevel(lvl) if type(lvl)=='string' then local i = fnutils.indexOf(levels,string.lower(lvl)) if i then loglevel = i else error('loglevel must be one of '..table.concat(levels,', ',0,#levels),2) end elseif type(lvl)=='number' then if lvl<0 or lvl>#levels then error('loglevel must be between 0 and '..#levels,2) end loglevel=lvl else error('loglevel must be a string or a number',2) end end if not loglevel then loglevel=2 else setLogLevel(loglevel) end local r = { setLogLevel = setLogLevel, e = function(...) return l(loglevel,ERROR,id,...) end, w = function(...) return l(loglevel,WARNING,id,...) end, i = function(...) return l(loglevel,INFO,id,...) end, d = function(...) return l(loglevel,DEBUG,id,...) end, v = function(...) return l(loglevel,VERBOSE,id,...) end, ef = function(fmt,...) return lf(loglevel,ERROR,id,fmt,...) end, wf = function(fmt,...) return lf(loglevel,WARNING,id,fmt,...) end, f = function(fmt,...) return lf(loglevel,INFO,id,fmt,...) end, df = function(fmt,...) return lf(loglevel,DEBUG,id,fmt,...) end, vf = function(fmt,...) return lf(loglevel,VERBOSE,id,fmt,...) end, } r.log=r.i r.logf=r.f return r end return {new=new} --- hs.logger:setLogLevel(loglevel) --- Method --- Sets the log level of the logger instance --- --- Parameters: --- * loglevel - can be 'nothing', 'error', 'warning', 'info', 'debug', or 'verbose'; or a corresponding number between 0 and 5 --- hs.logger:e(...) --- Method --- Logs an error to the console --- --- Parameters: --- * ... - one or more message strings --- hs.logger:ef(fmt,...) --- Method --- Logs a formatted error to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- hs.logger:w(...) --- Method --- Logs a warning to the console --- --- Parameters: --- * ... - one or more message strings --- hs.logger:wf(fmt,...) --- Method --- Logs a formatted warning to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- hs.logger:i(...) --- Method --- Logs info to the console --- --- Parameters: --- * ... - one or more message strings --- hs.logger:f(fmt,...) --- Method --- Logs formatted info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- hs.logger:d(...) --- Method --- Logs debug info to the console --- --- Parameters: --- * ... - one or more message strings --- hs.logger:df(fmt,...) --- Method --- Logs formatted debug info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- hs.logger:v(...) --- Method --- Logs verbose info to the console --- --- Parameters: --- * ... - one or more message strings --- hs.logger:vf(fmt,...) --- Method --- Logs formatted verbose info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt
--- === hs.logger === --- --- Simple logger for debugging purposes local date,time = os.date,os.time local format,sub=string.format,string.sub local select,print,concat,min=select,print,table.concat,math.min local fnutils=require'hs.fnutils' local ERROR , WARNING , INFO , DEBUG , VERBOSE =1,2,3,4,5 local levels={'error','warning','info','debug','verbose'} levels[0]='nothing' local slevels={{'ERROR',''},{'Warn:',''},{'',''},{'','-- '},{'',' -- '}} local lastid local lasttime=0 local fmt={'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',} local lf = function(loglevel,lvl,id,fmt,...) if loglevel<lvl then return end local ct = time() local stime = ' ' if ct-lasttime>0 or lvl<3 then stime=date('%X') lasttime=ct end if id==lastid and lvl>3 then id=' ' else lastid=id end print(format('%s %s%s %s'..fmt,stime,slevels[lvl][1],id,slevels[lvl][2],...)) end local l = function(loglevel,lvl,id,...) if loglevel>=lvl then return lf(loglevel,lvl,id,concat(fmt,' ',1,min(select('#',...),#fmt)),...) end end --- hs.logger.new(id, loglevel) -> logger --- Function --- Creates a new logger instance --- --- Parameters: --- * id - a string identifier for the instance (usually the module name) --- * loglevel - can be 'nothing', 'error', 'warning', 'info', 'debug', or 'verbose'; or a corresponding number between 0 and 5; defaults to 'warning' if omitted --- --- Returns: --- * the new logger instance --- --- Usage: --- local log = hs.logger.new('mymodule','debug') --- log.i('Initializing') -- will print "[mymodule] Initializing" to the console local function new(id,loglevel) if type(id)~='string' then error('id must be a string',2) end id=format('%10s','['..format('%.8s',id)..']') local function setLogLevel(lvl) if type(lvl)=='string' then local i = fnutils.indexOf(levels,string.lower(lvl)) if i then loglevel = i else error('loglevel must be one of '..table.concat(levels,', ',0,#levels),2) end elseif type(lvl)=='number' then if lvl<0 or lvl>#levels then error('loglevel must be between 0 and '..#levels,2) end loglevel=lvl else error('loglevel must be a string or a number',2) end end if not loglevel then loglevel=2 else setLogLevel(loglevel) end local r = { setLogLevel = setLogLevel, e = function(...) return l(loglevel,ERROR,id,...) end, w = function(...) return l(loglevel,WARNING,id,...) end, i = function(...) return l(loglevel,INFO,id,...) end, d = function(...) return l(loglevel,DEBUG,id,...) end, v = function(...) return l(loglevel,VERBOSE,id,...) end, ef = function(fmt,...) return lf(loglevel,ERROR,id,fmt,...) end, wf = function(fmt,...) return lf(loglevel,WARNING,id,fmt,...) end, f = function(fmt,...) return lf(loglevel,INFO,id,fmt,...) end, df = function(fmt,...) return lf(loglevel,DEBUG,id,fmt,...) end, vf = function(fmt,...) return lf(loglevel,VERBOSE,id,fmt,...) end, } r.log=r.i r.logf=r.f return r end return {new=new} --- hs.logger:setLogLevel(loglevel) --- Method --- Sets the log level of the logger instance --- --- Parameters: --- * loglevel - can be 'nothing', 'error', 'warning', 'info', 'debug', or 'verbose'; or a corresponding number between 0 and 5 --- --- Returns: --- * None --- hs.logger:e(...) --- Method --- Logs an error to the console --- --- Parameters: --- * ... - one or more message strings --- --- Returns: --- * None --- hs.logger:ef(fmt,...) --- Method --- Logs a formatted error to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- --- Returns: --- * None --- hs.logger:w(...) --- Method --- Logs a warning to the console --- --- Parameters: --- * ... - one or more message strings --- --- Returns: --- * None --- hs.logger:wf(fmt,...) --- Method --- Logs a formatted warning to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- --- Returns: --- * None --- hs.logger:i(...) --- Method --- Logs info to the console --- --- Parameters: --- * ... - one or more message strings --- --- Returns: --- * None --- hs.logger:f(fmt,...) --- Method --- Logs formatted info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- --- Returns: --- * None --- hs.logger:d(...) --- Method --- Logs debug info to the console --- --- Parameters: --- * ... - one or more message strings --- --- Returns: --- * None --- hs.logger:df(fmt,...) --- Method --- Logs formatted debug info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- --- Returns: --- * None --- hs.logger:v(...) --- Method --- Logs verbose info to the console --- --- Parameters: --- * ... - one or more message strings --- --- Returns: --- * None --- hs.logger:vf(fmt,...) --- Method --- Logs formatted verbose info to the console --- --- Parameters: --- * fmt - formatting string as per string.format --- * ... - arguments to fmt --- --- Returns: --- * None
fix docstrings
fix docstrings
Lua
mit
junkblocker/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,wsmith323/hammerspoon,peterhajas/hammerspoon,tmandry/hammerspoon,knu/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,Stimim/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,knu/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,hypebeast/hammerspoon,nkgm/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,TimVonsee/hammerspoon,peterhajas/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,knl/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,chrisjbray/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,lowne/hammerspoon,kkamdooong/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,joehanchoi/hammerspoon,wsmith323/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon
c3de24889e87b01064beca79859d821b6dcb9c68
premake4.lua
premake4.lua
-- -- Premake 5.x build configuration script -- Use this script to configure the project with Premake4. -- -- -- Define the project. Put the release configuration first so it will be the -- default when folks build using the makefile. That way they don't have to -- worry about the /scripts argument and all that. -- solution "Premake5" configurations { "Release", "Debug" } location ( _OPTIONS["to"] ) project "Premake5" targetname "premake5" language "C" kind "ConsoleApp" flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" } includedirs { "src/host/lua-5.1.4/src" } files { "*.txt", "**.lua", "src/**.h", "src/**.c", "src/host/scripts.c" } excludes { "src/host/lua-5.1.4/src/lua.c", "src/host/lua-5.1.4/src/luac.c", "src/host/lua-5.1.4/src/print.c", "src/host/lua-5.1.4/**.lua", "src/host/lua-5.1.4/etc/*.c" } configuration "Debug" targetdir "bin/debug" defines "_DEBUG" flags { "Symbols" } configuration "Release" targetdir "bin/release" defines "NDEBUG" flags { "OptimizeSize" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "vs2005" defines {"_CRT_SECURE_NO_DEPRECATE" } configuration "windows" links { "ole32" } configuration "linux or bsd or hurd" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } linkoptions { "-rdynamic" } configuration "linux or hurd" links { "dl" } configuration "macosx" defines { "LUA_USE_MACOSX" } links { "CoreServices.framework" } configuration { "macosx", "gmake" } -- toolset "clang" (not until a 5.0 binary is available) buildoptions { "-mmacosx-version-min=10.4" } linkoptions { "-mmacosx-version-min=10.4" } configuration { "solaris" } linkoptions { "-Wl,--export-dynamic" } configuration "aix" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } -- -- A more thorough cleanup. -- if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end -- -- Use the --to=path option to control where the project files get generated. I use -- this to create project files for each supported toolset, each in their own folder, -- in preparation for deployment. -- newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" } -- -- Use the embed action to convert all of the Lua scripts into C strings, which -- can then be built into the executable. Always embed the scripts before creating -- a release build. -- dofile("scripts/embed.lua") newaction { trigger = "embed", description = "Embed scripts in scripts.c; required before release builds", execute = doembed } -- -- Use the release action to prepare source and binary packages for a new release. -- This action isn't complete yet; a release still requires some manual work. -- dofile("scripts/release.lua") newaction { trigger = "release", description = "Prepare a new release (incomplete)", execute = dorelease }
-- -- Premake 5.x build configuration script -- Use this script to configure the project with Premake4. -- -- -- Define the project. Put the release configuration first so it will be the -- default when folks build using the makefile. That way they don't have to -- worry about the /scripts argument and all that. -- solution "Premake5" configurations { "Release", "Debug" } location ( _OPTIONS["to"] ) project "Premake5" targetname "premake5" language "C" kind "ConsoleApp" flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" } includedirs { "src/host/lua-5.1.4/src" } files { "*.txt", "**.lua", "src/**.h", "src/**.c", "src/host/scripts.c" } excludes { "src/host/lua-5.1.4/src/lauxlib.c", "src/host/lua-5.1.4/src/lua.c", "src/host/lua-5.1.4/src/luac.c", "src/host/lua-5.1.4/src/print.c", "src/host/lua-5.1.4/**.lua", "src/host/lua-5.1.4/etc/*.c" } configuration "Debug" targetdir "bin/debug" defines "_DEBUG" flags { "Symbols" } configuration "Release" targetdir "bin/release" defines "NDEBUG" flags { "OptimizeSize" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "vs2005" defines {"_CRT_SECURE_NO_DEPRECATE" } configuration "windows" links { "ole32" } configuration "linux or bsd or hurd" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } linkoptions { "-rdynamic" } configuration "linux or hurd" links { "dl" } configuration "macosx" defines { "LUA_USE_MACOSX" } links { "CoreServices.framework" } configuration { "macosx", "gmake" } -- toolset "clang" (not until a 5.0 binary is available) buildoptions { "-mmacosx-version-min=10.4" } linkoptions { "-mmacosx-version-min=10.4" } configuration { "solaris" } linkoptions { "-Wl,--export-dynamic" } configuration "aix" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m" } -- -- A more thorough cleanup. -- if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end -- -- Use the --to=path option to control where the project files get generated. I use -- this to create project files for each supported toolset, each in their own folder, -- in preparation for deployment. -- newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" } -- -- Use the embed action to convert all of the Lua scripts into C strings, which -- can then be built into the executable. Always embed the scripts before creating -- a release build. -- dofile("scripts/embed.lua") newaction { trigger = "embed", description = "Embed scripts in scripts.c; required before release builds", execute = doembed } -- -- Use the release action to prepare source and binary packages for a new release. -- This action isn't complete yet; a release still requires some manual work. -- dofile("scripts/release.lua") newaction { trigger = "release", description = "Prepare a new release (incomplete)", execute = dorelease }
Fix bootstrapping with premake4
Fix bootstrapping with premake4
Lua
bsd-3-clause
annulen/premake,annulen/premake,annulen/premake,annulen/premake
e0a288b4b7904c78cd6b429d1070ae247e340e5c
kong/plugins/hmac-auth/access.lua
kong/plugins/hmac-auth/access.lua
local cache = require "kong.tools.database_cache" local stringy = require "stringy" local responses = require "kong.tools.responses" local constants = require "kong.constants" local math_abs = math.abs local ngx_time = ngx.time local ngx_gmatch = ngx.re.gmatch local ngx_decode_base64 = ngx.decode_base64 local ngx_parse_time = ngx.parse_http_time local ngx_sha1 = ngx.hmac_sha1 local ngx_set_header = ngx.req.set_header local ngx_set_headers = ngx.req.get_headers local ngx_log = ngx.log local split = stringy.split local AUTHORIZATION = "authorization" local PROXY_AUTHORIZATION = "proxy-authorization" local DATE = "date" local X_DATE = "x-date" local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified" local _M = {} local function retrieve_hmac_fields(request, headers, header_name, conf) local hmac_params = {} local authorization_header = headers[header_name] -- parse the header to retrieve hamc parameters if authorization_header then local iterator, iter_err = ngx_gmatch(authorization_header, "\\s*[Hh]mac\\s*username=\"(.+)\",\\s*algorithm=\"(.+)\",\\s*headers=\"(.+)\",\\s*signature=\"(.+)\"") if not iterator then ngx_log(ngx.ERR, iter_err) return end local m, err = iterator() if err then ngx_log(ngx.ERR, err) return end if m and #m >= 4 then hmac_params.username = m[1] hmac_params.algorithm = m[2] hmac_params.hmac_headers = split(m[3], " ") hmac_params.signature = m[4] end end if conf.hide_credentials then request.clear_header(header_name) end return hmac_params end local function create_hash(request, hmac_params, headers) local signing_string = "" local hmac_headers = hmac_params.hmac_headers local count = #hmac_headers for i = 1, count do local header = hmac_headers[i] local header_value = headers[header] if not header_value then if header == "request-line" then -- request-line in hmac headers list signing_string = signing_string..split(request.raw_header(), "\r\n")[1] else signing_string = signing_string..header..":" end else signing_string = signing_string..header..":".." "..header_value end if i < count then signing_string = signing_string.."\n" end end return ngx_sha1(hmac_params.secret, signing_string) end local function validate_signature(request, hmac_params, headers) local digest = create_hash(request, hmac_params, headers) if digest then return digest == ngx_decode_base64(hmac_params.signature) end end local function hmacauth_credential_key(username) return "hmacauth_credentials/"..username end local function load_credential(username) local credential if username then credential = cache.get_or_set(hmacauth_credential_key(username), function() local keys, err = dao.hmacauth_credentials:find_by_keys { username = username } local result if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif #keys > 0 then result = keys[1] end return result end) end return credential end local function validate_clock_skew(headers, date_header_name, allowed_clock_skew) local date = headers[date_header_name] if not date then return false end local requestTime = ngx_parse_time(date) if not requestTime then return false end local skew = math_abs(ngx_time() - requestTime) if skew > allowed_clock_skew then return false end return true end function _M.execute(conf) local headers = ngx_set_headers(); -- If both headers are missing, return 401 if not (headers[AUTHORIZATION] or headers[PROXY_AUTHORIZATION]) then return responses.send_HTTP_UNAUTHORIZED() end -- validate clock skew if not (validate_clock_skew(headers, X_DATE, conf.clock_skew) or validate_clock_skew(headers, DATE, conf.clock_skew)) then responses.send_HTTP_FORBIDDEN("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication") end -- retrieve hmac parameter from Proxy-Authorization header local hmac_params = retrieve_hmac_fields(ngx.req, headers, PROXY_AUTHORIZATION, conf) -- Try with the authorization header if not hmac_params.username then hmac_params = retrieve_hmac_fields(ngx.req, headers, AUTHORIZATION, conf) end if not (hmac_params.username and hmac_params.signature) then responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID) end -- validate signature local credential = load_credential(hmac_params.username) if not credential then responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID) end hmac_params.secret = credential.secret if not validate_signature(ngx.req, hmac_params, headers) then return responses.send_HTTP_FORBIDDEN("HMAC signature does not match") end -- Retrieve consumer local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function() local result, err = dao.consumers:find_by_primary_key({ id = credential.consumer_id }) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return result end) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.req.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username) ngx.ctx.authenticated_credential = credential end return _M
local cache = require "kong.tools.database_cache" local stringy = require "stringy" local responses = require "kong.tools.responses" local constants = require "kong.constants" local math_abs = math.abs local ngx_time = ngx.time local ngx_gmatch = ngx.re.gmatch local ngx_decode_base64 = ngx.decode_base64 local ngx_parse_time = ngx.parse_http_time local ngx_sha1 = ngx.hmac_sha1 local ngx_set_header = ngx.req.set_header local ngx_set_headers = ngx.req.get_headers local ngx_log = ngx.log local split = stringy.split local AUTHORIZATION = "authorization" local PROXY_AUTHORIZATION = "proxy-authorization" local DATE = "date" local X_DATE = "x-date" local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified" local _M = {} local function retrieve_hmac_fields(request, headers, header_name, conf) local hmac_params = {} local authorization_header = headers[header_name] -- parse the header to retrieve hamc parameters if authorization_header then local iterator, iter_err = ngx_gmatch(authorization_header, "\\s*[Hh]mac\\s*username=\"(.+)\",\\s*algorithm=\"(.+)\",\\s*headers=\"(.+)\",\\s*signature=\"(.+)\"") if not iterator then ngx_log(ngx.ERR, iter_err) return end local m, err = iterator() if err then ngx_log(ngx.ERR, err) return end if m and #m >= 4 then hmac_params.username = m[1] hmac_params.algorithm = m[2] hmac_params.hmac_headers = split(m[3], " ") hmac_params.signature = m[4] end end if conf.hide_credentials then request.clear_header(header_name) end return hmac_params end local function create_hash(request, hmac_params, headers) local signing_string = "" local hmac_headers = hmac_params.hmac_headers local count = #hmac_headers for i = 1, count do local header = hmac_headers[i] local header_value = headers[header] if not header_value then if header == "request-line" then -- request-line in hmac headers list signing_string = signing_string..split(request.raw_header(), "\r\n")[1] else signing_string = signing_string..header..":" end else signing_string = signing_string..header..":".." "..header_value end if i < count then signing_string = signing_string.."\n" end end return ngx_sha1(hmac_params.secret, signing_string) end local function is_digest_equal(digest_1, digest_2) if #digest_1 ~= #digest_1 then return false end local result = true for i=1, #digest_1 do if digest_1:sub(i, i) ~= digest_2:sub(i, i) then result = false end end return result end local function validate_signature(request, hmac_params, headers) local digest = create_hash(request, hmac_params, headers) if digest then return is_digest_equal(digest, ngx_decode_base64(hmac_params.signature)) end end local function hmacauth_credential_key(username) return "hmacauth_credentials/"..username end local function load_credential(username) local credential if username then credential = cache.get_or_set(hmacauth_credential_key(username), function() local keys, err = dao.hmacauth_credentials:find_by_keys { username = username } local result if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif #keys > 0 then result = keys[1] end return result end) end return credential end local function validate_clock_skew(headers, date_header_name, allowed_clock_skew) local date = headers[date_header_name] if not date then return false end local requestTime = ngx_parse_time(date) if not requestTime then return false end local skew = math_abs(ngx_time() - requestTime) if skew > allowed_clock_skew then return false end return true end function _M.execute(conf) local headers = ngx_set_headers(); -- If both headers are missing, return 401 if not (headers[AUTHORIZATION] or headers[PROXY_AUTHORIZATION]) then return responses.send_HTTP_UNAUTHORIZED() end -- validate clock skew if not (validate_clock_skew(headers, X_DATE, conf.clock_skew) or validate_clock_skew(headers, DATE, conf.clock_skew)) then responses.send_HTTP_FORBIDDEN("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication") end -- retrieve hmac parameter from Proxy-Authorization header local hmac_params = retrieve_hmac_fields(ngx.req, headers, PROXY_AUTHORIZATION, conf) -- Try with the authorization header if not hmac_params.username then hmac_params = retrieve_hmac_fields(ngx.req, headers, AUTHORIZATION, conf) end if not (hmac_params.username and hmac_params.signature) then responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID) end -- validate signature local credential = load_credential(hmac_params.username) if not credential then responses.send_HTTP_FORBIDDEN(SIGNATURE_NOT_VALID) end hmac_params.secret = credential.secret if not validate_signature(ngx.req, hmac_params, headers) then return responses.send_HTTP_FORBIDDEN("HMAC signature does not match") end -- Retrieve consumer local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function() local result, err = dao.consumers:find_by_primary_key({ id = credential.consumer_id }) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return result end) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.req.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username) ngx.ctx.authenticated_credential = credential end return _M
hotfix(hmac-auth) constant time digest comparison
hotfix(hmac-auth) constant time digest comparison fix #655
Lua
apache-2.0
li-wl/kong,salazar/kong,ajayk/kong,Kong/kong,jebenexer/kong,Kong/kong,Mashape/kong,smanolache/kong,akh00/kong,icyxp/kong,shiprabehera/kong,jerizm/kong,xvaara/kong,beauli/kong,ccyphers/kong,Kong/kong,Vermeille/kong
a8a62566cea8d638a8f0779cff110038ac3383ae
himan-scripts/nwcsaf-low-and-high-cloud.lua
himan-scripts/nwcsaf-low-and-high-cloud.lua
--[[ // Effective cloudinessin fiksausta // Leila & Anniina Versio 31/3/22 // Korjaa satelliitin karkean resoluution aiheuttamia aukkoja ylä- ja alapilvialueiden rajoilla ]] function Write(res) result:SetParam(param("NWCSAF_EFFCLD-0TO1")) result:SetValues(res) luatool:WriteToFile(result) end function LowAndHighCloudGapFix() local effc = luatool:FetchWithType(current_time, current_level, param("NWCSAF_EFFCLD-0TO1"), current_forecast_type) local ctt = luatool:FetchWithType(current_time, current_level, param("CTBT-K"), current_forecast_type) local mnwc_prod = producer(7, "MNWC") mnwc_prod:SetCentre(251) mnwc_prod:SetProcess(7) local mnwc_origintime = raw_time(radon:GetLatestTime(mnwc_prod, "", 0)) local mnwc_time = forecast_time(mnwc_origintime, current_time:GetValidDateTime()) local o = {forecast_time = mnwc_time, level = current_level, param = param("NH-0TO1"), forecast_type = current_forecast_type, producer = mnwc_prod, geom_name = "", read_previous_forecast_if_not_found = true } local nh = luatool:FetchWithArgs(o) o["param"] = param("NM-0TO1") local nm = luatool:FetchWithArgs(o) o["param"] = param("NL-0TO1") local nl = luatool:FetchWithArgs(o) if not effc or not ctt or not nh or not nm or not nl then logger:Error("Some data not found") Write(effc) return end local filter = matrix(3, 3, 1, missing) filter:Fill(1/9.) local Nmat = matrix(result:GetGrid():GetNi(), result:GetGrid():GetNj(), 1, 0) Nmat:SetValues(effc) local effc_p1 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() filter = matrix(7, 7, 1, missing) filter:Fill(1/49.) local effc_p2 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local res = {} for i=1,#effc do local effc_ = effc[i] local ctt_ = ctt[i] local nl_ = nl[i] local nm_ = nm[i] local nh_ = nh[i] local effc_p1_ = effc_p1[i] local effc_p2_ = effc_p2[i] -- Luodaan alkuun näennäinen cloudmask cloudtop brightness temperaturen avulla. -- Jos arvo -> on pilvi if IsValid(ctt_) then effc_ = math.max(effc_, 0.8) end -- Keskiarvostetaan pienimpiä aukkoja ja reunoja. if effc_ <= 0.9 and effc_p1_ > 0.65 then effc_ = 0.9 end if effc_ <= 0.9 and effc_p2_ > 0.55 then effc_ = 0.9 end -- Vähennetään pilveä, jos vain ylä if effc_ > 0.4 and nh_ > 0.5 and nl_ < 0.2 and nm_ < 0.2 then effc_ = 0.4 end res[i] = effc_ end Write(res) end local mon = tonumber(current_time:GetValidDateTime():String("%m")) -- Fix is valid for winter months September ... March if mon >= 10 or mon <= 3 then LowAndHighCloudGapFix() end
--[[ // Effective cloudinessin fiksausta // Leila & Anniina Versio 31/3/22 // Korjaa satelliitin karkean resoluution aiheuttamia aukkoja ylä- ja alapilvialueiden rajoilla ]] function Write(res) result:SetParam(param("NWCSAF_EFFCLD-0TO1")) result:SetValues(res) luatool:WriteToFile(result) end function LowAndHighCloudGapFix() local effc = luatool:FetchWithType(current_time, current_level, param("NWCSAF_EFFCLD-0TO1"), current_forecast_type) local ctt = luatool:FetchWithType(current_time, current_level, param("CTBT-K"), current_forecast_type) local mnwc_prod = producer(7, "MNWC") mnwc_prod:SetCentre(251) mnwc_prod:SetProcess(7) local mnwc_origintime = raw_time(radon:GetLatestTime(mnwc_prod, "", 0)) local mnwc_time = forecast_time(mnwc_origintime, current_time:GetValidDateTime()) local o = {forecast_time = mnwc_time, level = current_level, param = param("NH-0TO1"), forecast_type = current_forecast_type, producer = mnwc_prod, geom_name = "", read_previous_forecast_if_not_found = true } local nh = luatool:FetchWithArgs(o) o["param"] = param("NM-0TO1") local nm = luatool:FetchWithArgs(o) o["param"] = param("NL-0TO1") local nl = luatool:FetchWithArgs(o) if not effc or not ctt or not nh or not nm or not nl then logger:Error("Some data not found") Write(effc) return end local filter = matrix(3, 3, 1, missing) filter:Fill(1/9.) local Nmat = matrix(result:GetGrid():GetNi(), result:GetGrid():GetNj(), 1, 0) Nmat:SetValues(effc) local effc_p1 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() filter = matrix(7, 7, 1, missing) filter:Fill(1/49.) local effc_p2 = Filter2D(Nmat, filter, configuration:GetUseCuda()):GetValues() local res = {} for i=1,#effc do local effc_ = effc[i] local ctt_ = ctt[i] local nl_ = nl[i] local nm_ = nm[i] local nh_ = nh[i] local effc_p1_ = effc_p1[i] local effc_p2_ = effc_p2[i] -- Luodaan alkuun näennäinen cloudmask cloudtop brightness temperaturen avulla. -- Jos arvo -> on pilvi if IsValid(ctt_) then effc_ = math.max(effc_, 0.8) end -- Keskiarvostetaan pienimpiä aukkoja ja reunoja. if effc_ <= 0.9 and effc_p1_ > 0.65 then effc_ = 0.9 end if effc_ <= 0.9 and effc_p2_ > 0.55 then effc_ = 0.9 end -- Vähennetään pilveä, jos vain ylä if effc_ > 0.4 and nh_ > 0.5 and nl_ < 0.2 and nm_ < 0.2 then effc_ = 0.4 end res[i] = effc_ end return res end function MissingCloudFixWithRH(effc) local snwc_prod = producer(281, "SMARTMETNWC") snwc_prod:SetCentre(86) snwc_prod:SetProcess(207) local latest_origintime = raw_time(radon:GetLatestTime(snwc_prod, "", 0)) local ftime = forecast_time(latest_origintime, current_time:GetValidDateTime()) logger:Info(string.format("SmartMet NWC origintime: %s validtime: %s", ftime:GetOriginDateTime():String("%Y-%m-%d %H:%M:%S"), ftime:GetValidDateTime():String("%Y-%m-%d %H:%M:%S"))) o = {forecast_time = ftime, level = level(HPLevelType.kHeight, 2), param = param("RH-PRCNT"), forecast_type = current_forecast_type, producer = snwc_prod, geom_name = "", read_previous_forecast_if_not_found = false, time_interpolation = true, time_interpolation_search_step = time_duration("00:15:00") } local snwc_rh = luatool:FetchWithArgs(o) if not snwc_rh then logger:Warning("Unable to perform RH based fix") return effc end local num_changed = 0 local changesum = 0 for i=1,#snwc_rh do local old_effc = effc[i] if effc[i] < 0.1 and snwc_rh[i] >= 89 then effc[i] = 0.6 end if effc[i] <= 0.6 and snwc_rh[i] >= 98 then effc[i] = 0.8 end if effc[i] ~= old_effc then num_changed = num_changed + 1 changesum = changesum + (effc[i] - old_effc) end end logger:Info(string.format("Changed %d values (%.1f%% of grid values), average change was %.3f", num_changed, 100*num_changed/#snwc_rh, changesum / num_changed)) return effc end local mon = tonumber(current_time:GetValidDateTime():String("%m")) -- Fix is valid for winter months September ... March if mon >= 10 or mon <= 3 then effc = LowAndHighCloudGapFix() effc = MissingCloudFixWithRH(effc) Write(effc) end
Implement a fix for false clear sky data
Implement a fix for false clear sky data Smartmet NWC relative humidity data is used to determine if low-level cloud is missing from NWCSAF
Lua
mit
fmidev/himan,fmidev/himan,fmidev/himan
c38d37153fa9fc503fb5f868308fee50ce514dbb
vanilla/v/request.lua
vanilla/v/request.lua
-- perf local error = error local pairs = pairs local setmetatable = setmetatable local sfind = string.find local Request = {} function Request:new() local params = {} -- body params local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = sfind(header, "multipart") if is_multipart and is_multipart>0 then -- upload request, should not invoke ngx.req.read_body() else ngx.req.read_body() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end else ngx.req.read_body() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end local instance = { uri = ngx.var.uri, req_uri = ngx.var.request_uri, req_args = ngx.var.args, params = params, uri_args = ngx.req.get_uri_args(), method = ngx.req.get_method(), headers = headers, body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end function Request:getControllerName() return self.controller_name end function Request:getActionName() return self.action_name end function Request:getHeaders() return self.headers end function Request:getHeader(key) if self.headers[key] ~= nil then return self.headers[key] else return false end end function Request:getParams() return self.params end function Request:getParam(key) return self.params[key] end function Request:setParam(key, value) self.params[key] = value end function Request:getMethod() return self.method end function Request:isGet() if self.method == 'GET' then return true else return false end end return Request
-- perf local error = error local pairs = pairs local setmetatable = setmetatable local sfind = string.find local Request = {} function Request:new() local params = {} -- body params local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = sfind(header, "multipart") if is_multipart and is_multipart>0 then -- upload request, should not invoke ngx.req.read_body() else ngx.req.read_body() params = ngx.req.get_uri_args() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end else ngx.req.read_body() params = ngx.req.get_uri_args() local post_args = ngx.req.get_post_args() if post_args and type(post_args) == "table" then for k,v in pairs(post_args) do params[k] = v end end end local instance = { uri = ngx.var.uri, req_uri = ngx.var.request_uri, req_args = ngx.var.args, params = params, uri_args = ngx.req.get_uri_args(), method = ngx.req.get_method(), headers = headers, body_raw = ngx.req.get_body_data() } setmetatable(instance, {__index = self}) return instance end function Request:getControllerName() return self.controller_name end function Request:getActionName() return self.action_name end function Request:getHeaders() return self.headers end function Request:getHeader(key) if self.headers[key] ~= nil then return self.headers[key] else return false end end function Request:getParams() return self.params end function Request:getParam(key) return self.params[key] end function Request:setParam(key, value) self.params[key] = value end function Request:getMethod() return self.method end function Request:isGet() if self.method == 'GET' then return true else return false end end return Request
Fix bug
Fix bug Put request data to params too
Lua
mit
lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla,lhmwzy/vanilla
534437b722d7dbe2175ec8aa201ebf6a6234f227
init.lua
init.lua
require("keybindings") require("plugins") vim.cmd('source funks.vim') local options = { number = true, relativenumber = true, hidden = true, inccommand = 'nosplit', hlsearch = false, ignorecase = true, smartcase = true, mouse = 'a', breakindent = true, wrap = false, updatetime = 250, ttimeout = true, ttimeoutlen = 50 , signcolumn = 'yes', cursorline = true , colorcolumn = '81' , splitbelow = true , splitright = true , showtabline = 0, clipboard = "unnamedplus", completeopt = { "menuone", "noselect" }, undofile = true, -- Save undo history writebackup = false, -- if a file is being edited by another program (or was written to file while editing with another program), it is not allowed to be edited swapfile = false, -- creates a swapfile backup = false, -- creates a backup file scrolloff = 8, sidescrolloff = 8, expandtab = true, shiftwidth = 2, tabstop = 2, smartcase = true, smartindent = true, } vim.opt.shortmess:append "c" for k, v in pairs(options) do vim.opt[k] = v end -- status line: modifiedflag, charcount, filepercent, filepath vim.cmd [[set statusline=%f%=%m\ %c\ %P]] vim.o.termguicolors = true vim.g.onedark_terminal_italics = 2 vim.o.background = 'dark' vim.cmd [[colorscheme kuroi]] -- Highlight on yank (copy). It will do a nice highlight blink of the thing you just copied. vim.api.nvim_exec( [[ augroup YankHighlight autocmd! autocmd TextYankPost * silent! lua vim.highlight.on_yank() augroup end ]], false ) -- Set dark theme if macOS theme is dark, light otherwise. -- local theme = vim.fn.system("defaults read -g AppleInterfaceStyle") -- print(theme) -- if theme and (string.find(theme, 'Dark')) then -- vim.o.background = 'dark' -- vim.cmd [[colorscheme kuroi]] -- else -- vim.o.background = 'light' -- vim.cmd [[colorscheme quietlight]] -- end
require("keybindings") require("plugins") vim.cmd('source funks.vim') local options = { number = true, relativenumber = true, hidden = true, inccommand = 'nosplit', hlsearch = false, ignorecase = true, smartcase = true, mouse = 'a', breakindent = true, wrap = false, updatetime = 250, ttimeout = true, ttimeoutlen = 50 , signcolumn = 'yes', cursorline = true , colorcolumn = '81' , splitbelow = true , splitright = true , showtabline = 0, clipboard = "unnamedplus", completeopt = { "menuone", "noselect" }, undofile = true, -- Save undo history writebackup = false, -- if a file is being edited by another program (or was written to file while editing with another program), it is not allowed to be edited swapfile = false, -- creates a swapfile backup = false, -- creates a backup file scrolloff = 8, sidescrolloff = 8, expandtab = true, shiftwidth = 2, tabstop = 2, smartcase = true, smartindent = true, } vim.opt.shortmess:append "c" for k, v in pairs(options) do vim.opt[k] = v end -- status line: modifiedflag, charcount, filepercent, filepath vim.cmd [[set statusline=%f%=%m\ %c\ %P]] vim.o.termguicolors = true vim.g.onedark_terminal_italics = 2 vim.o.background = 'dark' vim.cmd [[colorscheme kuroi]] -- Highlight on yank (copy). It will do a nice highlight blink of the thing you just copied. vim.api.nvim_exec( [[ augroup YankHighlight autocmd! autocmd TextYankPost * silent! lua vim.highlight.on_yank() augroup end ]], false ) -- Set colorscheme for macOS local theme = vim.fn.system("defaults read -g AppleInterfaceStyle") if theme and (string.find(theme, 'Light')) then vim.o.background = 'light' vim.cmd [[colorscheme quietlight]] else vim.o.background = 'dark' vim.cmd [[colorscheme kuroi]] end
Fix auto setting colorscheme for macOS
Fix auto setting colorscheme for macOS
Lua
mit
aasare/aaku
93cf041b6401d08484332e2b9b4a4840784dd90d
init.lua
init.lua
local WebSocket = require("websocket") local json = require("json") local table = require("table") local md5 = require("md5") local os = require("os") local math = require("math") local base64 = require("base64") exports.new = function(func) local t = {} t.listener = {connect = {}, data = {}, disconnect = {}, timeout = {}} t.clients = {} t.on = function(self, s, c) if self.listener[s] and type(self.listener[s]) == "table" and type(c) == "function" then table.insert(self.listener[s], c) end return self end t.call = function(self, s, ...) if self.listener[s] and type(self.listener[s]) == "table" then local t = {} for k,v in pairs(self.listener[s]) do if type(v) == "function" then local r = v(...) if r then table.insert(t, r) end end end return unpack(t) end end t.server = WebSocket.server.new() :on("connect", function(sock) local client = {} client.socket = sock client.listener = {} client.ip = client.socket:address().ip client.uid = md5.hex(client.ip .. tostring(os.time()) .. tostring(math.random())) client.socket.client = client client.send = function(self, key, data) local _data = base64.encodeTable({packet = key, data = data}) client.socket:send(json.encode(_data)) end client.on = function(self, event, cb) self.listener[event] = cb end client.call = function(self, event, ...) if type(self.listener[event]) == "function" then self.listener[event](...) end end t.clients[client.uid] = client t:call("connect", client) end) :on("disconnect", function(sock) sock.client:call("disconnect") t:call("disconnect", sock.client) t.clients[sock.client.uid] = nil sock.client.socket = nil sock.client = nil end) :on("timeout", function(sock) sock.client:call("disconnect") t:call("disconnect", sock.client) t.clients[sock.client.uid] = nil sock.client.socket = nil sock.client = nil end) :on("data", function(sock, message) if message and #message > 3 then local data = base64.decodeTable(json:decode(message)) if data.packet then sock.client:call(data.packet, data.data) t:call(data.packet, sock.client, data.data) end end end) t.listen = function(self, ...) self.server:listen(...) return self end if type(func) == "function" then func(t) end return t end
local WebSocket = require("websocket") local json = require("json") local table = require("table") local md5 = require("md5") local os = require("os") local math = require("math") local base64 = require("base64") exports.new = function(func) local t = {} t.listener = {connect = {}, data = {}, disconnect = {}, timeout = {}} t.clients = {} t.on = function(self, s, c) if self.listener[s] and type(self.listener[s]) == "table" and type(c) == "function" then table.insert(self.listener[s], c) end return self end t.call = function(self, s, ...) if self.listener[s] and type(self.listener[s]) == "table" then local t = {} for k,v in pairs(self.listener[s]) do if type(v) == "function" then local r = v(...) if r then table.insert(t, r) end end end return unpack(t) end end t.server = WebSocket.server.new() :on("connect", function(sock) local client = {} client.socket = sock client.listener = {} client.ip = client.socket:address().ip client.uid = md5.hex(client.ip .. tostring(os.time()) .. tostring(math.random())) client.socket.client = client client.send = function(self, key, data) local _data = base64.encodeTable({packet = key, data = data}) client.socket:send(json.encode(_data)) end client.on = function(self, event, cb) self.listener[event] = cb end client.call = function(self, event, ...) if type(self.listener[event]) == "function" then self.listener[event](...) end end t.clients[client.uid] = client t:call("connect", client) end) :on("disconnect", function(client) client:call("disconnect") t:call("disconnect", client) t.clients[client.uid] = nil client.socket = nil client = nil end) :on("timeout", function(client) client:call("timeout") t:call("timeout", client) t.clients[client.uid] = nil client.socket = nil client = nil end) :on("data", function(sock, message) if message and #message > 3 then local data = base64.decodeTable(json:decode(message)) if data.packet then sock.client:call(data.packet, data.data) t:call(data.packet, sock.client, data.data) end end end) t.listen = function(self, ...) self.server:listen(...) return self end if type(func) == "function" then func(t) end return t end
Added timeout event + hopefully fixed both, disconnect and timeout events.
Added timeout event + hopefully fixed both, disconnect and timeout events.
Lua
mit
b42nk/LuvSocks,b42nk/LuvSocks
4f74b38ff9a01e1ed1678b8b5765c4a4f8634169
init.lua
init.lua
-- -- A torch client for `display` graphics server -- Based heavily on https://github.com/clementfarabet/gfx.js/blob/master/clients/torch/js.lua -- local mime = require 'mime' local http = require 'socket.http' local ltn12 = require 'ltn12' local json = require 'cjson' local ffi = require 'ffi' require 'image' -- image module is broken for now local torch = require 'torch' M = { url = 'http://localhost:8000/events' } local function uid() return 'pane_' .. (os.time() .. math.random()):gsub('%.', '') end local function send(command) -- TODO: make this asynchronous, don't care about result, but don't want to block execution command = json.encode(command) http.request({ url = M.url, method = 'POST', headers = { ['content-length'] = #command, ['content-type'] = 'application/text' }, source = ltn12.source.string(command), }) end local function pane(type, win, title, content) win = win or uid() send({ command='pane', type=type, id=win, title=title, content=content }) return win end local function normalize(img, opts) -- rescale image to 0 .. 1 local min = opts.min or img:min() local max = opts.max or img:max() img = torch.FloatTensor(img:size()):copy(img) img:add(-min):mul(1/(max-min)) return img end -- Set the URL of the listening server function M.configure(config) local port = config.port or 8000 local hostname = config.hostname or '127.0.0.1' M.url = 'http://' .. hostname .. ':' .. port ..'/events' end function M.image(img, opts) -- options: opts = opts or {} if type(img) == 'table' then return M.images(img, opts) end -- img is a collection? if img:dim() == 4 or (img:dim() == 3 and img:size(1) > 3) then local images = {} for i = 1,img:size(1) do images[i] = img[i] end return M.images(images, opts) end img = normalize(img, opts) -- write to in-memory compressed JPG local inmem_img = image.compressJPG(img) local imgdata = 'data:image/jpg;base64,' .. mime.b64(ffi.string(inmem_img:data(), inmem_img:nElement())) return pane('image', opts.win, opts.title, { src=imgdata, labels=opts._labels, width=opts.width }) end function M.images(images, opts) opts = opts or {} local labels = opts.labels or {} local nperrow = opts.nperrow or math.ceil(math.sqrt(#images)) local maxsize = {1, 0, 0} for i, img in ipairs(images) do if opts.normalize then img = normalize(img, opts) end if img:dim() == 2 then img = torch.expand(img:view(1, img:size(1), img:size(2)), maxsize[1], img:size(1), img:size(2)) end images[i] = img maxsize[1] = math.max(maxsize[1], img:size(1)) maxsize[2] = math.max(maxsize[2], img:size(2)) maxsize[3] = math.max(maxsize[3], img:size(3)) end -- merge all images onto one big canvas local _labels = {} local numrows = math.ceil(#images / nperrow) local canvas = torch.FloatTensor(maxsize[1], maxsize[2] * numrows, maxsize[3] * nperrow):fill(0.5) local row = 0 local col = 0 for i, img in ipairs(images) do canvas:narrow(2, maxsize[2] * row + 1, img:size(2)):narrow(3, maxsize[3] * col + 1, img:size(3)):copy(img) if labels[i] then table.insert(_labels, { col / nperrow, row / numrows, labels[i] }) end col = col + 1 if col == nperrow then col = 0 row = row + 1 end end opts._labels = _labels; return M.image(canvas, opts) end -- data is either a 2-d torch.Tensor, or a list of lists -- opts.labels is a list of series names, e.g. -- plot({ { 1, 23 }, { 2, 12 } }, { labels={'iteration', 'score'} }) -- first series is always the X-axis -- See http://dygraphs.com/options.html for supported options function M.plot(data, opts) opts = opts or {} local dataset = {} if torch.typename(data) then for i = 1, data:size(1) do local row = {} for j = 1, data:size(2) do table.insert(row, data[{i, j}]) end table.insert(dataset, row) end else dataset = data end -- clone opts into options options = {} for k, v in pairs(opts) do options[k] = v end options.file = dataset if options.labels then options.xlabel = options.xlabel or options.labels[1] end -- Don't pass our options to dygraphs. 'title' is ok options.win = nil return pane('plot', opts.win, opts.title, options) end function M.text(text, opts) opts = opts or {} return pane('text', opts.win, opts.title, text) end function M.audio(data, opts) opts = opts or {} if not pcall(require, 'audio') then print("Warning: audio package could not be loaded. Skipping audio.") return end local fname local delete = false local inmem = false if torch.isTensor(data) then -- audio as tensor if data:dim() ~= 2 then print('Warning: audio tensor has to be 2D Tensor of NSamples x NChannels. Other tensor shapes are not supported') return end local sampleRate = opts.rate or 44100 -- default sample rate if ffi.os == 'Linux' then -- only linux supports fmemopen OOB fname = audio.compress(data, sampleRate, 'ogg') inmem = true else -- use temporary file fname = os.tmpname() .. '.ogg' audio.save(fname, data, sampleRate) delete = true end elseif torch.type(data) == 'string' then -- audio file fname = data -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) if not (ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac') then print('Warning: mp3, wav, ogg, aac files supported. But found extension: ' .. ext) return end else print("Warning: unknown input type. Need a Tensor, or a filename") return end -- load the audio as binary blob local buf, ext, size if inmem == true then buf = fname ext = 'ogg' size = buf:nElement() else local f = assert(torch.DiskFile(fname, 'r', true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); size = f:position() - 1 f:seek(1) buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local pos = fname:reverse():find('%.') ext = fname:sub(#fname-pos + 2) end if delete then os.execute('rm -f ' .. fname) end local audio_data = 'data:audio/' .. ext .. ';base64,' .. mime.b64(ffi.string(torch.data(buf), size)) return pane('audio', opts.win, opts.title, audio_data) end return M
-- -- A torch client for `display` graphics server -- Based heavily on https://github.com/clementfarabet/gfx.js/blob/master/clients/torch/js.lua -- local mime = require 'mime' local http = require 'socket.http' local ltn12 = require 'ltn12' local json = require 'cjson' local ffi = require 'ffi' require 'image' -- image module is broken for now local torch = require 'torch' M = { url = 'http://localhost:8000/events' } local function uid() return 'pane_' .. (os.time() .. math.random()):gsub('%.', '') end local function send(command) -- TODO: make this asynchronous, don't care about result, but don't want to block execution command = json.encode(command) http.request({ url = M.url, method = 'POST', headers = { ['content-length'] = #command, ['content-type'] = 'application/text' }, source = ltn12.source.string(command), }) end local function pane(type, win, title, content) win = win or uid() send({ command='pane', type=type, id=win, title=title, content=content }) return win end local function normalize(img, opts) -- rescale image to 0 .. 1 local min = opts.min or img:min() local max = opts.max or img:max() img = torch.FloatTensor(img:size()):copy(img) img:add(-min):mul(1/(max-min)) return img end -- Set the URL of the listening server function M.configure(config) local port = config.port or 8000 local hostname = config.hostname or '127.0.0.1' M.url = 'http://' .. hostname .. ':' .. port ..'/events' end function M.image(img, opts) local defaultType = torch.getdefaulttensortype() -- the image package expects this to be DoubleTensor -- if CudaTensor then clampImage from package image will attempt to index field 'image' (a nil value) of the CudaTensor torch.setdefaulttensortype('torch.DoubleTensor') -- options: opts = opts or {} if type(img) == 'table' then return M.images(img, opts) end -- img is a collection? if img:dim() == 4 or (img:dim() == 3 and img:size(1) > 3) then local images = {} for i = 1,img:size(1) do images[i] = img[i] end return M.images(images, opts) end img = normalize(img, opts) -- write to in-memory compressed JPG local inmem_img = image.compressJPG(img) local imgdata = 'data:image/jpg;base64,' .. mime.b64(ffi.string(inmem_img:data(), inmem_img:nElement())) torch.setdefaulttensortype(defaultType) return pane('image', opts.win, opts.title, { src=imgdata, labels=opts._labels, width=opts.width }) end function M.images(images, opts) opts = opts or {} local labels = opts.labels or {} local nperrow = opts.nperrow or math.ceil(math.sqrt(#images)) local maxsize = {1, 0, 0} for i, img in ipairs(images) do if opts.normalize then img = normalize(img, opts) end if img:dim() == 2 then img = torch.expand(img:view(1, img:size(1), img:size(2)), maxsize[1], img:size(1), img:size(2)) end images[i] = img maxsize[1] = math.max(maxsize[1], img:size(1)) maxsize[2] = math.max(maxsize[2], img:size(2)) maxsize[3] = math.max(maxsize[3], img:size(3)) end -- merge all images onto one big canvas local _labels = {} local numrows = math.ceil(#images / nperrow) local canvas = torch.FloatTensor(maxsize[1], maxsize[2] * numrows, maxsize[3] * nperrow):fill(0.5) local row = 0 local col = 0 for i, img in ipairs(images) do canvas:narrow(2, maxsize[2] * row + 1, img:size(2)):narrow(3, maxsize[3] * col + 1, img:size(3)):copy(img) if labels[i] then table.insert(_labels, { col / nperrow, row / numrows, labels[i] }) end col = col + 1 if col == nperrow then col = 0 row = row + 1 end end opts._labels = _labels; return M.image(canvas, opts) end -- data is either a 2-d torch.Tensor, or a list of lists -- opts.labels is a list of series names, e.g. -- plot({ { 1, 23 }, { 2, 12 } }, { labels={'iteration', 'score'} }) -- first series is always the X-axis -- See http://dygraphs.com/options.html for supported options function M.plot(data, opts) opts = opts or {} local dataset = {} if torch.typename(data) then for i = 1, data:size(1) do local row = {} for j = 1, data:size(2) do table.insert(row, data[{i, j}]) end table.insert(dataset, row) end else dataset = data end -- clone opts into options options = {} for k, v in pairs(opts) do options[k] = v end options.file = dataset if options.labels then options.xlabel = options.xlabel or options.labels[1] end -- Don't pass our options to dygraphs. 'title' is ok options.win = nil return pane('plot', opts.win, opts.title, options) end function M.text(text, opts) opts = opts or {} return pane('text', opts.win, opts.title, text) end function M.audio(data, opts) opts = opts or {} if not pcall(require, 'audio') then print("Warning: audio package could not be loaded. Skipping audio.") return end local fname local delete = false local inmem = false if torch.isTensor(data) then -- audio as tensor if data:dim() ~= 2 then print('Warning: audio tensor has to be 2D Tensor of NSamples x NChannels. Other tensor shapes are not supported') return end local sampleRate = opts.rate or 44100 -- default sample rate if ffi.os == 'Linux' then -- only linux supports fmemopen OOB fname = audio.compress(data, sampleRate, 'ogg') inmem = true else -- use temporary file fname = os.tmpname() .. '.ogg' audio.save(fname, data, sampleRate) delete = true end elseif torch.type(data) == 'string' then -- audio file fname = data -- get prefix local pos = fname:reverse():find('%.') local ext = fname:sub(#fname-pos + 2) if not (ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac') then print('Warning: mp3, wav, ogg, aac files supported. But found extension: ' .. ext) return end else print("Warning: unknown input type. Need a Tensor, or a filename") return end -- load the audio as binary blob local buf, ext, size if inmem == true then buf = fname ext = 'ogg' size = buf:nElement() else local f = assert(torch.DiskFile(fname, 'r', true), 'File could not be opened: ' .. fname):binary(); f:seekEnd(); size = f:position() - 1 f:seek(1) buf = torch.CharStorage(size); assert(f:readChar(buf) == size, 'wrong number of bytes read') f:close() local pos = fname:reverse():find('%.') ext = fname:sub(#fname-pos + 2) end if delete then os.execute('rm -f ' .. fname) end local audio_data = 'data:audio/' .. ext .. ';base64,' .. mime.b64(ffi.string(torch.data(buf), size)) return pane('audio', opts.win, opts.title, audio_data) end return M
Default Tensor type fix
Default Tensor type fix
Lua
mit
szym/display,szym/display,szym/display,szym/display
65e675a8cc7c96918d140656af55941afbfa8104
main.lua
main.lua
-- -- Copyright (c) 2016, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- require 'torch' require 'paths' require 'optim' require 'nn' local DataLoader = require 'dataloader' local models = require 'models/init' local Trainer = require 'train' local opts = require 'opts' local checkpoints = require 'checkpoints' torch.setdefaulttensortype('torch.FloatTensor') torch.setnumthreads(1) local opt = opts.parse(arg) torch.manualSeed(opt.manualSeed) cutorch.manualSeedAll(opt.manualSeed) -- Load previous checkpoint, if it exists local checkpoint, optimState = checkpoints.latest(opt) local optimState = checkpoint and torch.load(checkpoint.optimFile) or nil -- Create model local model, criterion = models.setup(opt, checkpoint) -- Data loading local trainLoader, valLoader = DataLoader.create(opt) -- The trainer handles the training loop and evaluation on validation set local trainer = Trainer(model, criterion, opt, optimState) if opt.testOnly then local top1Err, top5Err = trainer:test(0, valLoader) print(string.format(' * Results top1: %6.3f top5: %6.3f', top1Err, top5Err)) return end local startEpoch = checkpoint and checkpoint.epoch + 1 or opt.epochNumber local bestTop1 = math.huge local bestTop5 = math.huge for epoch = startEpoch, opt.nEpochs do -- Train for a single epoch local trainTop1, trainTop5, trainLoss = trainer:train(epoch, trainLoader) -- Run model on validation set local testTop1, testTop5 = trainer:test(epoch, valLoader) local bestModel = false if testTop1 < bestTop1 then bestModel = true bestTop1 = testTop1 bestTop5 = testTop5 print(' * Best model ', testTop1, testTop5) end checkpoints.save(epoch, model, trainer.optimState, bestModel) end print(string.format(' * Finished top1: %6.3f top5: %6.3f', bestTop1, bestTop5))
-- -- Copyright (c) 2016, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- require 'torch' require 'paths' require 'optim' require 'nn' local DataLoader = require 'dataloader' local models = require 'models/init' local Trainer = require 'train' local opts = require 'opts' local checkpoints = require 'checkpoints' torch.setdefaulttensortype('torch.FloatTensor') torch.setnumthreads(1) local opt = opts.parse(arg) torch.manualSeed(opt.manualSeed) cutorch.manualSeedAll(opt.manualSeed) -- Load previous checkpoint, if it exists local checkpoint, optimState = checkpoints.latest(opt) -- Create model local model, criterion = models.setup(opt, checkpoint) -- Data loading local trainLoader, valLoader = DataLoader.create(opt) -- The trainer handles the training loop and evaluation on validation set local trainer = Trainer(model, criterion, opt, optimState) if opt.testOnly then local top1Err, top5Err = trainer:test(0, valLoader) print(string.format(' * Results top1: %6.3f top5: %6.3f', top1Err, top5Err)) return end local startEpoch = checkpoint and checkpoint.epoch + 1 or opt.epochNumber local bestTop1 = math.huge local bestTop5 = math.huge for epoch = startEpoch, opt.nEpochs do -- Train for a single epoch local trainTop1, trainTop5, trainLoss = trainer:train(epoch, trainLoader) -- Run model on validation set local testTop1, testTop5 = trainer:test(epoch, valLoader) local bestModel = false if testTop1 < bestTop1 then bestModel = true bestTop1 = testTop1 bestTop5 = testTop5 print(' * Best model ', testTop1, testTop5) end checkpoints.save(epoch, model, trainer.optimState, bestModel) end print(string.format(' * Finished top1: %6.3f top5: %6.3f', bestTop1, bestTop5))
Remove (incorrect) duplicate loading of optimState from checkpoint
Remove (incorrect) duplicate loading of optimState from checkpoint Fixes #34
Lua
bsd-3-clause
ltrottier/pelu.resnet.torch,ltrottier/pelu.resnet.torch
a9c6a3af1812a76cf6f047b554e587eef2ffccde
Peripherals/HDD.lua
Peripherals/HDD.lua
local events = require("Engine.events") --A function that calculates the total size of a directory local function calcSize(dir) local total = 0 local files = love.filesystem.getDirectoryItems(dir) for k,filename in ipairs(files) do if love.filesystem.isDirectory(dir..filename) then total = total + calcSize(path..filename.."/") else total = total + love.filesystem.getSize(dir..filename) end end return total end return function(config) --A function that creates a new HDD peripheral. --Pre-init-- if not love.filesystem.exists("/drives") then love.filesystem.createDirectory("/drives") end --Create the folder that holds virtual drives. local drives = {} --Load the virtual hdds configurations-- for letter, size in pairs(config) do if not love.filesystem.exists("/drives/"..letter) then love.filesystem.createDirectory("/drives/"..letter) --Create the drive directory if doesn't exists drives[letter] = {size = size, usage = 0} --It's a new empty drive ! else drives[letter] = {size = size, usage = calcSize("/drives/"..letter)} --Register the drive end end --The api starts here-- local HDD = {} local ad = "C" --The active drive letter --Returns a list of the available drives. function HDD.drivers() local dlist = {} for k,v in ipairs(drives) do dlist[k] = {size=drives[k].size,usage=drives[k].usage} end return true,dlist end --Sets or gets the current active drive. function HDD.drive(letter) if letter then if type(letter) ~= "string" then return false, "The drive letter must be a string, provided: "..type(letter) end --Error ad = letter --Set the active drive letter. else return ad end end function HDD.write(fname,data,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(data) == "nil" then return false, "Should provide the data to write" end local data = tostring(data) if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end local path = "/drives/"..ad.."/"..fname local oldsize = (love.filesystem.exists(path) and love.filesystem.isFile(path)) and love.filesystem.getSize(path) or 0 --Old file size. local file,err = love.filesystem.newFile(path,"w") if not file then return false,err end --Error file:write(data,size) --Write to the file (without saving) local newsize = file:getSize() --The size of the new file if drives[ad].size < ((drives[ad].usage - oldsize) + newsize) then file:close() return false, "No more enough space" end --Error file:flush() --Save the new file file:close() --Close the file return true, newsize end function HDD.read(fname,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end local data, err = love.filesystem.read("/drives/"..ad.."/"..fname,size) if data then return true,data else return false,err enx end return HDD end
local events = require("Engine.events") --A function that calculates the total size of a directory local function calcSize(dir) local total = 0 local files = love.filesystem.getDirectoryItems(dir) for k,filename in ipairs(files) do if love.filesystem.isDirectory(dir..filename) then total = total + calcSize(path..filename.."/") else total = total + love.filesystem.getSize(dir..filename) end end return total end return function(config) --A function that creates a new HDD peripheral. --Pre-init-- if not love.filesystem.exists("/drives") then love.filesystem.createDirectory("/drives") end --Create the folder that holds virtual drives. local drives = {} --Load the virtual hdds configurations-- for letter, size in pairs(config) do if not love.filesystem.exists("/drives/"..letter) then love.filesystem.createDirectory("/drives/"..letter) --Create the drive directory if doesn't exists drives[letter] = {size = size, usage = 0} --It's a new empty drive ! else drives[letter] = {size = size, usage = calcSize("/drives/"..letter)} --Register the drive end end --The api starts here-- local HDD = {} local ad = "C" --The active drive letter --Returns a list of the available drives. function HDD.drivers() local dlist = {} for k,v in ipairs(drives) do dlist[k] = {size=drives[k].size,usage=drives[k].usage} end return true,dlist end --Sets or gets the current active drive. function HDD.drive(letter) if letter then if type(letter) ~= "string" then return false, "The drive letter must be a string, provided: "..type(letter) end --Error if not drives[letter] then return false, "The drive '"..letter.."' doesn't exists" end ad = letter --Set the active drive letter. else return ad end end function HDD.write(fname,data,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(data) == "nil" then return false, "Should provide the data to write" end local data = tostring(data) if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end local path = "/drives/"..ad.."/"..fname local oldsize = (love.filesystem.exists(path) and love.filesystem.isFile(path)) and love.filesystem.getSize(path) or 0 --Old file size. local file,err = love.filesystem.newFile(path,"w") if not file then return false,err end --Error file:write(data,size) --Write to the file (without saving) local newsize = file:getSize() --The size of the new file if drives[ad].size < ((drives[ad].usage - oldsize) + newsize) then file:close() return false, "No more enough space" end --Error file:flush() --Save the new file file:close() --Close the file drives[ad].usage = (drives[ad].usage - oldsize) + newsize --Update the usage return true, newsize end function HDD.read(fname,size) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error if type(size) ~= "number" and size then return false, "Size must be a number, provided: "..type(size) end --Error local data, err = love.filesystem.read("/drives/"..ad.."/"..fname,size) if data then return true,data else return false,err enx end function HDD.getSize(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error return love.filesystem.getSize("/drives/"..ad.."/"..fname) end function HDD.exists(fname) if type(fname) ~= "string" then return false, "File/Folder name must be a string, provided: "..type(fname) end --Error return true, love.filesystem.exists("/drives/"..ad.."/"..fname) end function HDD.newFolder(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error return love.filesystem.createDirectory("/drives/"..ad.."/"..fname) end function HDD.isFile(fname) if type(fname) ~= "string" then return false, "Filename must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The file doesn't exists" end --Error return true, love.filesystem.isFile(path) end function HDD.isFolder(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "The folder doesn't exists" end --Error return true, love.filesystem.isFolder(path) end function HDD.getDirectoryItems(fname) if type(fname) ~= "string" then return false, "Foldername must be a string, provided: "..type(fname) end --Error local path = "/drives/"..ad.."/"..fname if not love.filesystem.exists(path) then return false, "Folder doesn't exists" end --Error if not love.filesystem.isFolder(path) then return false, "Provided a path to a file instead of a folder" end --Error return true, love.filesystem.getDirectoryItems(path) end return HDD end
Added a set of hdd commands and nade some bugfixes
Added a set of hdd commands and nade some bugfixes
Lua
mit
RamiLego4Game/LIKO-12
ee3d1cff449e383c11be5f7d82812e9bacffd25d
goif.lua
goif.lua
-- -- goif -- -- Copyright (c) 2016 BearishMushroom -- -- This library is free software; you can redistribute it and/or modify it -- under the terms of the MIT license. See LICENSE for details. -- local goif = goif or {} goif.frame = 0 goif.active = false goif.canvas = nil goif.width = 0 goif.height = 0 goif.data = {} local path = (...):match("(.-)[^%.]+$") path = path:gsub('(%.)', '\\') local libname = 'none' if love.system.getOS() == "Windows" then if jit.arch == 'x86' then libname = 'libgoif_32.dll' elseif jit.arch == 'x64' then libname = 'libgoif_64.dll' else error("ERROR, UNSUPPORTED ARCH") end elseif love.system.getOS() == "Linux" then libname = 'libgoif.so' path = './' end local lib = package.loadlib(path .. libname, 'luaopen_libgoif') lib = lib() local function bind() love.graphics.setCanvas(goif.canvas) love.graphics.clear() end local function unbind() love.graphics.setCanvas() end goif.start = function(width, height) width = width or love.graphics.getWidth() height = height or love.graphics.getHeght() goif.frame = 0 goif.data = {} goif.active = true if goif.canvas == nil then goif.width = width goif.height = height goif.canvas = love.graphics.newCanvas(goif.width, goif.height) end end goif.stop = function(file, verbose) file = file or "gif.gif" verbose = verbose or false goif.active = false if verbose then print("Frames: " .. tostring(#goif.data)) end lib.set_frames(goif.frame - 2, goif.width, goif.height, verbose) -- compensate for skipped frames love.filesystem.createDirectory("goif") for i = 3, #goif.data do -- skip 2 frames for allocation lag local e = goif.data[i] lib.push_frame(e:getPointer(), e:getSize(), verbose) end lib.save(file, verbose) goif.data = {} collectgarbage() end goif.start_frame = function() if goif.active then bind() end end goif.end_frame = function() if goif.active then unbind() love.graphics.setColor(255, 255, 255) love.graphics.draw(goif.canvas) goif.data[goif.frame + 1] = goif.canvas:newImageData(0, 0, goif.width, goif.height) goif.frame = goif.frame + 1 end end goif.submit_frame = function(canvas) goif.data[goif.frame + 1] = canvas:newImageData(0, 0, goif.width, goif.height) goif.frame = goif.frame + 1 end return goif
-- -- goif -- -- Copyright (c) 2016 BearishMushroom -- -- This library is free software; you can redistribute it and/or modify it -- under the terms of the MIT license. See LICENSE for details. -- local goif = goif or {} goif.frame = 0 goif.active = false goif.canvas = nil goif.width = 0 goif.height = 0 goif.data = {} local path = (...):match("(.-)[^%.]+$") local libname = 'none' if love.system.getOS() == "Windows" then if jit.arch == 'x86' then libname = 'libgoif_32.dll' elseif jit.arch == 'x64' then libname = 'libgoif_64.dll' else error("GOIF: Unsupported CPU arch.") end path = path:gsub('(%.)', '\\') elseif love.system.getOS() == "Linux" then if jit.arch == 'x64' then libname = 'libgoif.so' else error("GOIF: Unsupported CPU arch.") end path = './' .. path:gsub('(%.)', '/') end if libname == 'none' then error("GOIF: Couldn't find proper library file for current OS.") end local lib = package.loadlib(path .. libname, 'luaopen_libgoif') lib = lib() local function bind() love.graphics.setCanvas(goif.canvas) love.graphics.clear() end local function unbind() love.graphics.setCanvas() end goif.start = function(width, height) width = width or love.graphics.getWidth() height = height or love.graphics.getHeght() goif.frame = 0 goif.data = {} goif.active = true if goif.canvas == nil then goif.width = width goif.height = height goif.canvas = love.graphics.newCanvas(goif.width, goif.height) end end goif.stop = function(file, verbose) file = file or "gif.gif" verbose = verbose or false goif.active = false if verbose then print("Frames: " .. tostring(#goif.data)) end lib.set_frames(goif.frame - 2, goif.width, goif.height, verbose) -- compensate for skipped frames love.filesystem.createDirectory("goif") for i = 3, #goif.data do -- skip 2 frames for allocation lag local e = goif.data[i] lib.push_frame(e:getPointer(), e:getSize(), verbose) end lib.save(file, verbose) goif.data = {} collectgarbage() end goif.start_frame = function() if goif.active then bind() end end goif.end_frame = function() if goif.active then unbind() love.graphics.setColor(255, 255, 255) love.graphics.draw(goif.canvas) goif.data[goif.frame + 1] = goif.canvas:newImageData(0, 0, goif.width, goif.height) goif.frame = goif.frame + 1 end end goif.submit_frame = function(canvas) goif.data[goif.frame + 1] = canvas:newImageData(0, 0, goif.width, goif.height) goif.frame = goif.frame + 1 end return goif
The definitive Linux inclusion fix.
The definitive Linux inclusion fix.
Lua
mit
BearishMushroom/goif
e85c3eb24db6bf033870472f62728177e3f124c0
mods/soundset/init.lua
mods/soundset/init.lua
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} soundset.tmp = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) if not soundset.tmp[name] then soundset.tmp[name] = {} end soundset.tmp[name]["music"] = music soundset.tmp[name]["ambience"] = ambience soundset.tmp[name]["other"] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name or name == "" then return end local fmusic = soundset.tmp[name]["music"] or 50 local fambience = soundset.tmp[name]["ambience"] or 50 local fother = soundset.tmp[name]["other"] or 50 if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end soundset.tmp[name] = nil return elseif fields["abort"] == "Abort" then soundset.tmp[name] = nil return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then soundset.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
minetest.log("action","[mod soundset] Loading...") soundset = {} soundset.file = minetest.get_worldpath() .. "/sounds_config.txt" soundset.gainplayers = {} local tmp = {} tmp["music"] = {} tmp["ambience"] = {} tmp["other"] = {} local function save_sounds_config() local input = io.open(soundset.file, "w") if input then input:write(minetest.serialize(soundset.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file) end end local function load_sounds_config() local file = io.open(soundset.file, "r") if file then soundset.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then soundset.gainplayers = {} end end load_sounds_config() soundset.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if soundset.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end soundset.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end soundset.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end if not soundset.gainplayers[name] then return 1 end local gain = soundset.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/100 end local inc = function(value) value = value + 5 if value > 100 then value = 100 end return value end local dec = function(value) value = value - 5 if value < 0 then value = 0 end return value end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "label[0,3.2;OTHER]".. "image_button[1.6,3;1,1;soundset_dec.png;vother;-]".. "label[2.7,3.2;%s]".. "image_button[3.5,3;1,1;soundset_inc.png;vother;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience, other) tmp["music"][name] = music tmp["ambience"][name] = ambience tmp["other"][name] = other minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) )) end local clear_tmp = function(name) tmp["music"][name] = nil tmp["ambience"][name] = nil tmp["other"][name] = nil end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name or name == "" then return end local fmusic = tmp["music"][name] or 50 local fambience = tmp["ambience"][name] or 50 local fother = tmp["other"][name] or 50 if fields["abort"] == "Ok" then if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then soundset.gainplayers[name]["music"] = fmusic soundset.gainplayers[name]["ambience"] = fambience soundset.gainplayers[name]["other"] = fother save_sounds_config() end clear_tmp(name) return elseif fields["abort"] == "Abort" then clear_tmp(name) return elseif fields["vmusic"] == "+" then fmusic = inc(fmusic) elseif fields["vmusic"] == "-" then fmusic = dec(fmusic) elseif fields["vambience"] == "+" then fambience = inc(fambience) elseif fields["vambience"] == "-" then fambience = dec(fambience) elseif fields["vother"] == "+" then fother = inc(fother) elseif fields["vother"] == "-" then fother = dec(fother) elseif fields["quit"] == "true" then clear_tmp(name) return else return end on_show_settings(name, fmusic, fambience, fother) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", show_with = false, --Modif MFF (Crabman 30/06/2015) action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = soundset.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(soundset.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if soundset.gainplayers[name] == nil then soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
fix crash due to lag
fix crash due to lag
Lua
unlicense
Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
31f4af07be38e2a66112adda35b99360507d2397
src/lua-factory/sources/grl-metrolyrics.lua
src/lua-factory/sources/grl-metrolyrics.lua
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <me@victortoso.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-metrolyrics", name = "Metrolyrics", description = "a source for lyrics", supported_keys = { "lyrics" }, supported_media = { 'audio', 'video' }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, tags = { 'music', 'net:internet' }, } netopts = { user_agent = "Grilo Source Metrolyrics/0.2.8", } ------------------ -- Source utils -- ------------------ METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]" METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve() local url, req local artist, title req = grl.get_media_keys() if not req or not req.artist or not req.title or #req.artist == 0 or #req.title == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "") artist = artist:gsub("%s+", "-") title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "") title = title:gsub("%s+", "-") url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist) grl.fetch(url, "fetch_page_cb", netopts) end --------------- -- Utilities -- --------------- function fetch_page_cb(feed) local media = nil if feed and not feed:find("notfound") then media = metrolyrics_get_lyrics(feed) end grl.callback(media, 0) end function metrolyrics_get_lyrics(feed) local media = {} local res = {} local lyrics_body = '<div class="lyrics%-body">(.-)</div>' local lyrics_verse = "<p class='verse'>(.-)</p>" -- from html, get lyrics line by line into table res feed = feed:match(lyrics_body) for verse in feed:gmatch(lyrics_verse) do local start = 1 local e, s = verse:find("<br/>") while (e) do res[#res + 1] = verse:sub(start, e-1) start = s+1 e, s = verse:find("<br/>", start) end res[#res + 1] = verse:sub(start, #verse) .. '\n\n' end -- switch table to string media.lyrics = table.concat(res) return media end
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <me@victortoso.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-metrolyrics", name = "Metrolyrics", description = "a source for lyrics", supported_keys = { "lyrics" }, supported_media = { 'audio', 'video' }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, tags = { 'music', 'net:internet' }, } netopts = { user_agent = "Grilo Source Metrolyrics/0.2.8", } ------------------ -- Source utils -- ------------------ METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]" METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve() local url, req local artist, title req = grl.get_media_keys() if not req or not req.artist or not req.title or #req.artist == 0 or #req.title == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "") artist = artist:gsub("%s+", "-") title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "") title = title:gsub("%s+", "-") url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist) grl.fetch(url, "fetch_page_cb", netopts) end --------------- -- Utilities -- --------------- function fetch_page_cb(feed) local media = nil if feed and not feed:find("notfound") then media = metrolyrics_get_lyrics(feed) end grl.callback(media, 0) end function metrolyrics_get_lyrics(feed) local media = {} local lyrics_body = '<div id="lyrics%-body%-text">(.-)</div>' local noise_array = { { noise = "<p class='verse'><p class='verse'>", sub = "\n\n" }, { noise = "<p class='verse'>", sub = "" }, { noise = "<br/>", sub = "" }, } -- remove html noise feed = feed:match(lyrics_body) for _, it in ipairs (noise_array) do feed = feed:gsub(it.noise, it.sub) end -- strip the lyrics feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1") -- switch table to string media.lyrics = feed return media end
lua-factory: change in metrolyrics website
lua-factory: change in metrolyrics website The HTML part of the lyrics changed. I've changed the get_lyrics function to clean up the HTML that came with the lyrics instead of matching it. https://bugzilla.gnome.org/show_bug.cgi?id=741784
Lua
lgpl-2.1
MathieuDuponchelle/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins
37677190945947dfa6b7f445ca96c01e66e74430
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(RADIOFRANCE_URL, "radiofrance_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_fetch_cb(playlist) if parse_playlist(playlist, false) then grl.fetch(FRANCEBLEU_URL, "francebleu_fetch_cb") end end function francebleu_fetch_cb(playlist) parse_playlist(playlist, true) end ------------- -- Helpers -- ------------- function parse_playlist(playlist, francebleu) local match1_prefix, match2 if francebleu then match1_prefix = '_frequence' match2 = '{(.-logo_region.-)}' else match1_prefix = '_radio' match2 = '{(.-#rfdirect.-)}' end if not playlist then grl.callback() return false end local items = playlist:match('Flux = {.-' .. match1_prefix .. ' : {(.*)}.-}') for item in items:gmatch(match2) do local media = create_media(item, francebleu) if media then grl.callback(media, -1) end end if francebleu then grl.callback() end return true end function get_thumbnail(id) local images = {} images['FranceInter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['FranceInfo'] = 'http://www.franceinfo.fr/sites/all/themes/franceinfo/logo.png' images['FranceCulture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['FranceMusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['Fip'] = 'http://www.fipradio.fr/sites/all/themes/fip2/images/logo_121x121.png' images['LeMouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' images['FranceBleu'] = 'http://www.francebleu.fr/sites/all/themes/francebleu/logo.png' return images[id] end function create_media(item, francebleu) local media = {} if francebleu then media.url = item:match("mp3_direct : '(http://.-)'") else media.url = item:match("hifi :'(.-)'") end if not media.url or media.url == '' then return nil end media.type = "audio" media.mime_type = "audio/mpeg" media.id = item:match("id : '(.-)',") media.title = item:match("nom : '(.-)',") media.title = media.title:gsub("\\'", "'") if francebleu then media.thumbnail = get_thumbnail('FranceBleu') else media.thumbnail = get_thumbnail(media.id) end return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(RADIOFRANCE_URL, "radiofrance_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_fetch_cb(playlist) if parse_playlist(playlist, false) then grl.fetch(FRANCEBLEU_URL, "francebleu_fetch_cb") end end function francebleu_fetch_cb(playlist) parse_playlist(playlist, true) end ------------- -- Helpers -- ------------- function parse_playlist(playlist, francebleu) local match1_prefix, match2 if francebleu then match1_prefix = '_frequence' match2 = '{(.-logo_region.-)}' else match1_prefix = '_radio' match2 = '{(.-#rfdirect.-)}' end if not playlist then grl.callback() return false end local items = playlist:match('Flux = {.-' .. match1_prefix .. ' : {(.*)}.-}') if not items then grl.callback() return false end for item in items:gmatch(match2) do local media = create_media(item, francebleu) if media then grl.callback(media, -1) end end if francebleu then grl.callback() end return true end function get_thumbnail(id) local images = {} images['FranceInter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['FranceInfo'] = 'http://www.franceinfo.fr/sites/all/themes/franceinfo/logo.png' images['FranceCulture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['FranceMusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['Fip'] = 'http://www.fipradio.fr/sites/all/themes/fip2/images/logo_121x121.png' images['LeMouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' images['FranceBleu'] = 'http://www.francebleu.fr/sites/all/themes/francebleu/logo.png' return images[id] end function create_media(item, francebleu) local media = {} if francebleu then media.url = item:match("mp3_direct : '(http://.-)'") else media.url = item:match("hifi :'(.-)'") end if not media.url or media.url == '' then return nil end media.type = "audio" media.mime_type = "audio/mpeg" media.id = item:match("id : '(.-)',") media.title = item:match("nom : '(.-)',") media.title = media.title:gsub("\\'", "'") if francebleu then media.thumbnail = get_thumbnail('FranceBleu') else media.thumbnail = get_thumbnail(media.id) end return media end
radiofrance: Don't break when run behind a portal
radiofrance: Don't break when run behind a portal [lua-library] grl-lua-library.c:351: calling source callback function fail (radiofrance_fetch_cb) '/home/hadess/Projects/gnome-install/share/grilo-plugins/grl-lua-factory/grl-radiofrance.lua:87: attempt to index local 'items' (a nil value)' https://bugzilla.gnome.org/show_bug.cgi?id=727569
Lua
lgpl-2.1
MikePetullo/grilo-plugins,grilofw/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,vrutkovs/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins