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
ebf64c605c034d892275be70771f96be3b62ae28
src/cosy/loader/lua.lua
src/cosy/loader/lua.lua
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 or Luajit with 5.2 compatibility to run." end return function (t) t = t or {} local loader = {} local modules = setmetatable ({}, { __mode = "kv" }) loader.hotswap = t.hotswap or require "hotswap".new {} loader.require = function (name) return loader.hotswap.require (name) end loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.logto = t.logto loader.coroutine = loader.require "coroutine.make" () loader.scheduler = t.scheduler or loader.require "copas.ev" loader.request = t.request or loader.require "socket.http".request loader.load "cosy.string" return loader end
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 or Luajit with 5.2 compatibility to run." end return function (t) t = t or {} local loader = {} local modules = setmetatable ({}, { __mode = "kv" }) loader.hotswap = t.hotswap or require "hotswap".new {} loader.require = function (name) local back = _G.require _G.require = loader.hotswap.require local result = loader.hotswap.require (name) _G.require = back return result end -- loader.require = function (name) -- return loader.hotswap.require (name) -- end loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.logto = t.logto loader.coroutine = loader.require "coroutine.make" () loader.scheduler = t.scheduler or loader.require "copas.ev" loader.request = t.request or loader.require "socket.http".request loader.load "cosy.string" return loader end
Fix require in the loader.
Fix require in the loader.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
000672985e522417587619935ca0a819b277ff3a
nyagos.d/suffix.lua
nyagos.d/suffix.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local m = string.match(args[0],"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local path=nyagos.which(args[0]) if not path then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 1 then for key,val in pairs(share._suffixes) do local right=val if type(val) == "table" then right = table.concat(val," ") end print(key .. "=" .. right) end return end for i=1,#args do local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$") if right then local args={} for m in string.gmatch(right,"%S+") do args[#args+1] = m end share._setsuffix(left,args) else local val = share._suffixes[args[i]] if not val then val = "" elseif type(val) == "table" then val = table.concat(val," ") end print(args[i].."="..val) end end end
Do not insert interpreter when argv[0] does not have a suffix for #237
Do not insert interpreter when argv[0] does not have a suffix for #237 `suffix` on _nyagos called suffix.lua infinitely when the current directory is nyagos.d/ .
Lua
bsd-3-clause
tsuyoshicho/nyagos,zetamatta/nyagos,tyochiai/nyagos,nocd5/nyagos
895e415fd40ac0c4e01285b5166e1a588d2654e6
deviceloaders/dynamixel/serial.lua
deviceloaders/dynamixel/serial.lua
local M = {} local sched = require 'lumen.sched' local log = require 'lumen.log' local mutex = require 'lumen.mutex' local selector = require 'lumen.tasks.selector' local mx = mutex.new() --local my_path = debug.getinfo(1, "S").source:match[[^@?(.*[\/])[^\/]-$]] local NULL_CHAR = string.char(0x00) local PACKET_START = string.char(0xFF,0xFF) local function parseAx12Packet(s) local function generate_checksum(data) local checksum = 0 for i=1, #data do checksum = checksum + data:byte(i) end return 255 - (checksum%256) end --print('parseAx12Packet parsing', s:byte(1, #s)) local id = s:sub(3,3) --local data_length = s:byte(4) local data = s:sub(5, -1) if generate_checksum(s:sub(3,-1))~=0 then return nil,'READ_CHECKSUM_ERROR' end local errinpacket= data:byte(1,1) local payload = data:sub(2,-2) --print('parseAx12Packet parsed', id:byte(1, #id),'$', errinpacket,':', payload:byte(1, #payload)) return id, errinpacket, payload end local id_signals = setmetatable({}, {__index = function(t,k) local v = {} t[k] = v return v end }) local serial_timeout local id_waitds = setmetatable({}, {__index = function(t,k) local v = sched.new_waitd({id_signals[k], timeout = serial_timeout}) t[k] = v return v end }) M.new_bus = function (conf) local filename = conf.filename or '/dev/ttyUSB0' serial_timeout = conf.serialtimeout or 0.05 log('AX', 'INFO', 'usb device file: %s', tostring(filename)) local packet='' local insync=false local packlen=nil -- -1 --while true do -- local _, fragment, err_read = sched.wait(waitd_traffic) --------------------- local protocol_handler = function (_, fragment, err_read) if not fragment then --if err_read=='closed' then -- print('dynamixel file closed:', filename) -- return --end log('AX', 'ERROR', 'Read from dynamixel device file failed with %s', tostring(err_read)) return end if fragment==NULL_CHAR then error('No power on serial?') end packet=packet..fragment ---[[ while (not insync) and (#packet>2) and (packet:sub(1,2) ~= PACKET_START) do log('AX', 'DEBUG', 'resync on "%s"', packet:byte(1,10)) packet=packet:sub(2, -1) --=packet:sub(packet:find(PACKET_START) or -1, -1) end --]] if not insync and #packet>=4 then insync = true packlen = packet:byte(4) end --print('++++++++++++++++', #packet, packlen) while packlen and #packet>=packlen+4 do --#packet >3 and packlen <= #packet - 3 do if #packet == packlen+4 then --fast lane local id, errcode, payload=parseAx12Packet(packet) if id then --print('dynamixel message parsed (fast):',id:byte(), errcode,':', payload:byte(1,#payload)) sched.signal(id_signals[id], errcode, payload) end packet = '' packlen = nil else --slow lane local packet_pre = packet:sub( 1, packlen+4 ) local id, errcode, payload=parseAx12Packet(packet_pre) --assert(handler, 'failed parsing (slow)'..packet:byte(1,#packet)) if id then --print('dynamixel message parsed (slow):',id:byte(), errcode,':', payload:byte(1,#payload)) sched.signal(id_signals[id], errcode, payload) end local packet_remainder = packet:sub(packlen+5, -1 ) packet = packet_remainder packlen = packet:byte(4) end insync = false end return true end --sched.sigrun({filehandler.events.data}, protocol_handler):set_as_attached() --------------------- local filehandler, erropen = selector.new_fd(filename, {'rdwr', 'nonblock'}, -1, protocol_handler) local opencount=60 while not filehandler and opencount>0 do print('retrying open...', opencount) log('AX', 'WARNING', 'Retrying open on %s, countdown %s', tostring(filename), tostring(opencount)) sched.sleep(1) filehandler, erropen = selector.new_fd(filename, {'rdwr', 'nonblock'}, -1, protocol_handler) opencount=opencount-1 end if not filehandler then log('AX', 'ERROR', 'usb %s failed to open with %s', tostring(filename), tostring(erropen)) return end log('AX', 'INFO', 'usb %s opened', tostring(filename)) local tty_flags = conf.stty_flags or '-parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -ignbrk -brkint ' ..'-ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel ' ..'-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 -isig -icanon ' ..'-iexten -echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt -echoctl -echoke' local speed = conf.serialspeed or 1000000 local init_tty_string ='stty -F ' .. filename .. ' ' .. speed .. ' ' .. tty_flags os.execute(init_tty_string) filehandler.fd:sync() --flush() local bus = {} bus.sendAX12packet = mx:synchronize(function (s, id, get_response) filehandler:send_sync(s) if get_response then local ev, err, data = sched.wait(id_waitds[id]) if id==ev then return err, data end if ev then log('AX', 'WARN', 'out of order messages in bus, increase serialtimeout') end end end) return bus end return M
local M = {} local sched = require 'lumen.sched' local log = require 'lumen.log' local mutex = require 'lumen.mutex' local selector = require 'lumen.tasks.selector' local mx = mutex.new() --local my_path = debug.getinfo(1, "S").source:match[[^@?(.*[\/])[^\/]-$]] local NULL_CHAR = string.char(0x00) local PACKET_START = string.char(0xFF,0xFF) local function parseAx12Packet(s) local function generate_checksum(data) local checksum = 0 for i=1, #data do checksum = checksum + data:byte(i) end return 255 - (checksum%256) end --print('parseAx12Packet parsing', s:byte(1, #s)) local id = s:sub(3,3) --local data_length = s:byte(4) local data = s:sub(5, -1) if generate_checksum(s:sub(3,-1))~=0 then return nil,'READ_CHECKSUM_ERROR' end local errinpacket= data:byte(1,1) local payload = data:sub(2,-2) --print('parseAx12Packet parsed', id:byte(1, #id),'$', errinpacket,':', payload:byte(1, #payload)) return id, errinpacket, payload end local id_signals = setmetatable({}, {__index = function(t,k) local v = {} rawset(t, k, v) return v end }) local serial_timeout local id_waitds = setmetatable({}, {__index = function(t,k) local v = sched.new_waitd({id_signals[k], timeout = serial_timeout}) rawset(t, k, v) return v end }) M.new_bus = function (conf) local filename = conf.filename or '/dev/ttyUSB0' serial_timeout = conf.serialtimeout or 0.05 log('AX', 'INFO', 'usb device file: %s with timeout %s', tostring(filename), tostring(serial_timeout)) local packet='' local insync=false local packlen=nil -- -1 --while true do -- local _, fragment, err_read = sched.wait(waitd_traffic) --------------------- local protocol_handler = function (_, fragment, err_read) if not fragment then --if err_read=='closed' then -- print('dynamixel file closed:', filename) -- return --end log('AX', 'ERROR', 'Read from dynamixel device file failed with %s', tostring(err_read)) return end if fragment==NULL_CHAR then error('No power on serial?') end packet=packet..fragment ---[[ while (not insync) and (#packet>2) and (packet:sub(1,2) ~= PACKET_START) do log('AX', 'DEBUG', 'resync on "%s"', packet:byte(1,10)) packet=packet:sub(2, -1) --=packet:sub(packet:find(PACKET_START) or -1, -1) end --]] if not insync and #packet>=4 then insync = true packlen = packet:byte(4) end --print('++++++++++++++++', #packet, packlen) while packlen and #packet>=packlen+4 do --#packet >3 and packlen <= #packet - 3 do if #packet == packlen+4 then --fast lane local id, errcode, payload=parseAx12Packet(packet) if id then --print('dynamixel message parsed (fast):',id:byte(), errcode,':', payload:byte(1,#payload)) sched.signal(id_signals[id], errcode, payload) end packet = '' packlen = nil else --slow lane local packet_pre = packet:sub( 1, packlen+4 ) local id, errcode, payload=parseAx12Packet(packet_pre) --assert(handler, 'failed parsing (slow)'..packet:byte(1,#packet)) if id then --print('dynamixel message parsed (slow):',id:byte(), errcode,':', payload:byte(1,#payload)) sched.signal(id_signals[id], errcode, payload) end local packet_remainder = packet:sub(packlen+5, -1 ) packet = packet_remainder packlen = packet:byte(4) end insync = false end return true end --sched.sigrun({filehandler.events.data}, protocol_handler):set_as_attached() --------------------- local filehandler, erropen = selector.new_fd(filename, {'rdwr', 'nonblock'}, -1, protocol_handler) local opencount=60 while not filehandler and opencount>0 do print('retrying open...', opencount) log('AX', 'WARNING', 'Retrying open on %s, countdown %s', tostring(filename), tostring(opencount)) sched.sleep(1) filehandler, erropen = selector.new_fd(filename, {'rdwr', 'nonblock'}, -1, protocol_handler) opencount=opencount-1 end if not filehandler then log('AX', 'ERROR', 'usb %s failed to open with %s', tostring(filename), tostring(erropen)) return end log('AX', 'INFO', 'usb %s opened', tostring(filename)) local tty_flags = conf.stty_flags or '-parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -ignbrk -brkint ' ..'-ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel ' ..'-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 -isig -icanon ' ..'-iexten -echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt -echoctl -echoke' local speed = conf.serialspeed or 1000000 local init_tty_string ='stty -F ' .. filename .. ' ' .. speed .. ' ' .. tty_flags os.execute(init_tty_string) filehandler.fd:sync() --flush() local bus = {} bus.sendAX12packet = mx:synchronize(function (s, id, get_response) filehandler:send_sync(s) if get_response then local ev, err, data = sched.wait(id_waitds[id]) if ev==id_signals[id] then return err, data end if ev then log('AX', 'WARN', 'out of order messages in bus, increase serialtimeout') end end end) return bus end return M
dynamixel serial fix for lumen
dynamixel serial fix for lumen
Lua
mit
xopxe/Toribio,xopxe/Toribio,xopxe/Toribio
8caa7ce2fae55fc7abded30a4a4f918ec22b97db
src/actions/vstudio/vs2005.lua
src/actions/vstudio/vs2005.lua
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.indent = nil -- back to default io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations --HG-- branch : fix_issue41
Lua
bsd-3-clause
annulen/premake,warrenseine/premake,warrenseine/premake,annulen/premake,annulen/premake,annulen/premake,warrenseine/premake
ad0fb9d873639facb825a02484849d114327612c
openresty/app.lua
openresty/app.lua
local _M = {} local cjson = require "cjson" local mysql = require "resty.mysql" local math = require "math" local encode = cjson.encode local random = math.random local insert = table.insert local mysqlconn = { host = "DBHOSTNAME", port = 3306, database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass" } function _M.handler(ngx) ngx.header.content_type = 'application/json' if ngx.var.uri == '/json' then local resp = {message = "Hello, World!"} ngx.print( encode(resp) ) elseif ngx.var.uri == '/db' then local db, err = mysql:new() local ok, err = db:connect(mysqlconn) local num_queries = tonumber(ngx.var.arg_queries) or 1 local worlds = {} for i=1, num_queries do local wid = random(1, 10000) insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1]) end ngx.print( encode(worlds) ) local ok, err = db:set_keepalive(0, 256) end end return _M
local _M = {} local cjson = require "cjson" local mysql = require "resty.mysql" local math = require "math" local encode = cjson.encode local random = math.random local insert = table.insert local mysqlconn = { host = "DBHOSTNAME", port = 3306, database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass" } function _M.handler(ngx) ngx.header.content_type = 'application/json' if ngx.var.uri == '/json' then local resp = {message = "Hello, World!"} ngx.print( encode(resp) ) elseif ngx.var.uri == '/db' then local db, err = mysql:new() local ok, err = db:connect(mysqlconn) local num_queries = tonumber(ngx.var.arg_queries) or 1 local worlds = {} for i=1, num_queries do local wid = random(1, 10000) insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1]) end ngx.print( encode(worlds) ) local ok, err = db:set_keepalive(0, 256) end end return _M
fix formatting
fix formatting
Lua
bsd-3-clause
joshk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,actframework/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,dmacd/FB-try1,fabianmurariu/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,joshk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,methane/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,dmacd/FB-try1,steveklabnik/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,testn/FrameworkBenchmarks,doom369/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,leafo/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,dmacd/FB-try1,k-r-g/FrameworkBenchmarks,sxend/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,testn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,valyala/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sxend/FrameworkBenchmarks,khellang/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Verber/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,joshk/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,denkab/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Verber/FrameworkBenchmarks,dmacd/FB-try1,Synchro/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zloster/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sxend/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zloster/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,valyala/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,doom369/FrameworkBenchmarks,valyala/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,methane/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,grob/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,testn/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,methane/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Verber/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sgml/FrameworkBenchmarks,methane/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sgml/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,Verber/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,khellang/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,torhve/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jamming/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,doom369/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,methane/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,torhve/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sgml/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,herloct/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,leafo/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zapov/FrameworkBenchmarks,torhve/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,denkab/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,denkab/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jamming/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,methane/FrameworkBenchmarks,leafo/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,sxend/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,khellang/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,dmacd/FB-try1,Rayne/FrameworkBenchmarks,doom369/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,denkab/FrameworkBenchmarks,grob/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,zloster/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,khellang/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,khellang/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,joshk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,herloct/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,dmacd/FB-try1,sgml/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,grob/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,khellang/FrameworkBenchmarks,testn/FrameworkBenchmarks,sgml/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zapov/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,leafo/FrameworkBenchmarks,leafo/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,methane/FrameworkBenchmarks,methane/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,doom369/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,doom369/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,grob/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,methane/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,khellang/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sgml/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,grob/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,testn/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sgml/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,grob/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,torhve/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,methane/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zloster/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sxend/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Verber/FrameworkBenchmarks,testn/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jamming/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jamming/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zapov/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zloster/FrameworkBenchmarks,doom369/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,joshk/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,leafo/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Verber/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,doom369/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,actframework/FrameworkBenchmarks,actframework/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sgml/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zapov/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,methane/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,testn/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,dmacd/FB-try1,RockinRoel/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,testn/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sxend/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,grob/FrameworkBenchmarks,leafo/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,denkab/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zapov/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,dmacd/FB-try1,jamming/FrameworkBenchmarks,zapov/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zloster/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zloster/FrameworkBenchmarks,doom369/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,testn/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jamming/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,herloct/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zapov/FrameworkBenchmarks,valyala/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,testn/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zapov/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,leafo/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,dmacd/FB-try1,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,testn/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,torhve/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,methane/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,dmacd/FB-try1,Dith3r/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,leafo/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jamming/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,leafo/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,methane/FrameworkBenchmarks,leafo/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,denkab/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,torhve/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sgml/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,valyala/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,denkab/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,khellang/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Verber/FrameworkBenchmarks,grob/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,grob/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Verber/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,valyala/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,torhve/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,joshk/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,testn/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jamming/FrameworkBenchmarks,grob/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,grob/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,denkab/FrameworkBenchmarks,sxend/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sxend/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sxend/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zapov/FrameworkBenchmarks,khellang/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,actframework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,khellang/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zloster/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,grob/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zapov/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,actframework/FrameworkBenchmarks,testn/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,khellang/FrameworkBenchmarks,torhve/FrameworkBenchmarks,dmacd/FB-try1,hperadin/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zloster/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,joshk/FrameworkBenchmarks,joshk/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,dmacd/FB-try1,torhve/FrameworkBenchmarks,grob/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,herloct/FrameworkBenchmarks,herloct/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,doom369/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,doom369/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,leafo/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,testn/FrameworkBenchmarks
7c226e03734a4057489cd4c7062e937b36c501d7
src_trunk/resources/realism-system/c_thermal_vision.lua
src_trunk/resources/realism-system/c_thermal_vision.lua
blackMales = {7, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 28, 35, 36, 50, 51, 66, 67, 78, 79, 80, 83, 84, 102, 103, 104, 105, 106, 107, 134, 136, 142, 143, 144, 156, 163, 166, 168, 176, 180, 182, 183, 185, 220, 221, 222, 249, 253, 260, 262 } whiteMales = {23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 58, 59, 60, 61, 62, 68, 70, 72, 73, 78, 81, 82, 94, 95, 96, 97, 98, 99, 100, 101, 108, 109, 110, 111, 112, 113, 114, 115, 116, 120, 121, 122, 124, 127, 128, 132, 133, 135, 137, 146, 147, 153, 154, 155, 158, 159, 160, 161, 162, 164, 165, 170, 171, 173, 174, 175, 177, 179, 181, 184, 186, 187, 188, 189, 200, 202, 204, 206, 209, 212, 213, 217, 223, 230, 234, 235, 236, 240, 241, 242, 247, 248, 250, 252, 254, 255, 258, 259, 261, 264 } asianMales = {49, 57, 58, 59, 60, 117, 118, 120, 121, 122, 123, 170, 186, 187, 203, 210, 227, 228, 229} blackFemales = {9, 10, 11, 12, 13, 40, 41, 63, 64, 69, 76, 91, 139, 148, 190, 195, 207, 215, 218, 219, 238, 243, 244, 245, 256 } whiteFemales = {12, 31, 38, 39, 40, 41, 53, 54, 55, 56, 64, 75, 77, 85, 86, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 140, 145, 150, 151, 152, 157, 172, 178, 192, 193, 194, 196, 197, 198, 199, 201, 205, 211, 214, 216, 224, 225, 226, 231, 232, 233, 237, 243, 246, 251, 257, 263 } asianFemales = {38, 53, 54, 55, 56, 88, 141, 169, 178, 224, 225, 226, 263} local localPlayer = getLocalPlayer() function doVision() -- vehicles for key, value in ipairs(getElementsByType("vehicle")) do if (isElementOnScreen(value)) and (getPedOccupiedVehicle(localPlayer)~=value) then local x, y, z = getElementPosition(value) local tx, ty = getScreenFromWorldPosition(x, y, z+1, 5000, false) if (tx) then dxDrawLine(tx, ty, tx+150, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawLine(tx+150, ty-150, tx+300, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawText(getVehicleName(value), tx+150, ty-200, tx+300, tx-160, tocolor(255, 255, 255, 200), 1, "bankgothic", "center", "middle") end end end -- players for key, value in ipairs(getElementsByType("player")) do if (isElementOnScreen(value)) and (localPlayer~=value) then local x, y, z = getPedBonePosition(value, 6) local skin = getPedSkin(value) local text if (blackMales[skin]) then text = "Black Male" elseif (whiteMales[skin]) then text = "White Male" elseif (asianMales[skin]) then text = "Asian Male" elseif (blackFemales[skin]) then text = "Black Female" elseif (whiteFemales[skin]) then text = "White Female" elseif (asianFemales[skin]) then text = "Asian Female" else text = "White Male" end local tx, ty = getScreenFromWorldPosition(x, y, z+0.2, 5000, false) if (tx) then dxDrawLine(tx, ty, tx+150, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawLine(tx+150, ty-150, tx+300, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawText(text, tx+150, ty-200, tx+300, tx-160, tocolor(255, 255, 255, 200), 1, "bankgothic", "center", "middle") end end end end function applyVision(thePlayer, seat) if (seat==1 and thePlayer==localPlayer and getVehicleModel(source)==497) then addEventHandler("onClientRender", getRootElement(), doVision) end end addEventHandler("onClientVehicleEnter", getRootElement(), applyVision) function removeVision(thePlayer, seat) if (seat==1 and thePlayer==localPlayer and getVehicleModel(source)==497) then removeEventHandler("onClientRender", getRootElement(), doVision) end end addEventHandler("onClientVehicleExit", getRootElement(), removeVision)
blackMales = {0, 7, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 28, 35, 36, 50, 51, 66, 67, 78, 79, 80, 83, 84, 102, 103, 104, 105, 106, 107, 134, 136, 142, 143, 144, 156, 163, 166, 168, 176, 180, 182, 183, 185, 220, 221, 222, 249, 253, 260, 262 } whiteMales = {23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 58, 59, 60, 61, 62, 68, 70, 72, 73, 78, 81, 82, 94, 95, 96, 97, 98, 99, 100, 101, 108, 109, 110, 111, 112, 113, 114, 115, 116, 120, 121, 122, 124, 127, 128, 132, 133, 135, 137, 146, 147, 153, 154, 155, 158, 159, 160, 161, 162, 164, 165, 170, 171, 173, 174, 175, 177, 179, 181, 184, 186, 187, 188, 189, 200, 202, 204, 206, 209, 212, 213, 217, 223, 230, 234, 235, 236, 240, 241, 242, 247, 248, 250, 252, 254, 255, 258, 259, 261, 264 } asianMales = {49, 57, 58, 59, 60, 117, 118, 120, 121, 122, 123, 170, 186, 187, 203, 210, 227, 228, 229} blackFemales = {9, 10, 11, 12, 13, 40, 41, 63, 64, 69, 76, 91, 139, 148, 190, 195, 207, 215, 218, 219, 238, 243, 244, 245, 256 } whiteFemales = {12, 31, 38, 39, 40, 41, 53, 54, 55, 56, 64, 75, 77, 85, 86, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 140, 145, 150, 151, 152, 157, 172, 178, 192, 193, 194, 196, 197, 198, 199, 201, 205, 211, 214, 216, 224, 225, 226, 231, 232, 233, 237, 243, 246, 251, 257, 263 } asianFemales = {38, 53, 54, 55, 56, 88, 141, 169, 178, 224, 225, 226, 263} local localPlayer = getLocalPlayer() function doVision() local px, py, pz = getElementPosition(localPlayer) -- vehicles for key, value in ipairs(getElementsByType("vehicle")) do if (isElementOnScreen(value)) and (getPedOccupiedVehicle(localPlayer)~=value) then local x, y, z = getElementPosition(value) if (isLineOfSightClear(px, py, pz, x, y, z, true, false, false, true, false, false, true, true, getPedOccupiedVehicle(localPlayer))) then local tx, ty = getScreenFromWorldPosition(x, y, z+1, 5000, false) if (tx) then dxDrawLine(tx, ty, tx+150, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawLine(tx+150, ty-150, tx+300, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawText(getVehicleName(value), tx+150, ty-200, tx+300, tx-160, tocolor(255, 255, 255, 200), 1, "bankgothic", "center", "middle") end end end end -- players for key, value in ipairs(getElementsByType("player")) do if (isElementOnScreen(value)) and (localPlayer~=value) then local x, y, z = getPedBonePosition(value, 6) local skin = getPedSkin(value) if (isLineOfSightClear(px, py, pz, x, y, z, true, false, false, true, false, false, true, true, getPedOccupiedVehicle(localPlayer))) then local text -- needs fixing if (blackMales[skin]) then text = "Black Male" elseif (whiteMales[skin]) then text = "White Male" elseif (asianMales[skin]) then text = "Asian Male" elseif (blackFemales[skin]) then text = "Black Female" elseif (whiteFemales[skin]) then text = "White Female" elseif (asianFemales[skin]) then text = "Asian Female" else text = "White Male" end local tx, ty = getScreenFromWorldPosition(x, y, z+0.2, 5000, false) if (tx) then dxDrawLine(tx, ty, tx+150, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawLine(tx+150, ty-150, tx+300, ty-150, tocolor(255, 255, 255, 200), 2, false) dxDrawText(text, tx+150, ty-200, tx+300, tx-160, tocolor(255, 255, 255, 200), 1, "bankgothic", "center", "middle") end end end end end function applyVision(thePlayer, seat) if (seat==1 and thePlayer==localPlayer and getVehicleModel(source)==497) then addEventHandler("onClientRender", getRootElement(), doVision) end end addEventHandler("onClientVehicleEnter", getRootElement(), applyVision) function removeVision(thePlayer, seat) if (seat==1 and thePlayer==localPlayer and getVehicleModel(source)==497) then removeEventHandler("onClientRender", getRootElement(), doVision) end end addEventHandler("onClientVehicleExit", getRootElement(), removeVision)
Fix for vision goggles, still have two bugs in them: skin detection doesnt work, shouldn't display info for passengers in your vehicle.
Fix for vision goggles, still have two bugs in them: skin detection doesnt work, shouldn't display info for passengers in your vehicle. git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@808 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
7d7deb228c100360e269b985f64168a5d4e5cdda
SelectTable.lua
SelectTable.lua
local SelectTable, parent = torch.class('nn.SelectTable', 'nn.Module') function SelectTable:__init(index) parent.__init(self) self.index = index self.gradInput = {} end function SelectTable:updateOutput(input) assert(math.abs(self.index) <= #input, "arg 1 table idx out of range") if self.index < 0 then self.output = input[#input + self.index + 1] else self.output = input[self.index] end return self.output end local function zeroTableCopy(t1, t2) for k, v in pairs(t2) do if (torch.type(v) == "table") then t1[k] = zeroTableCopy(t1[k] or {}, t2[k]) else if not t1[k] then t1[k] = v:clone():zero() else local tensor = t1[k] if not tensor:isSameSizeAs(v) then t1[k]:resizeAs(v) t1[k]:zero() end end end end return t1 end function SelectTable:updateGradInput(input, gradOutput) if self.index < 0 then self.gradInput[#input + self.index + 1] = gradOutput else self.gradInput[self.index] = gradOutput end zeroTableCopy(self.gradInput, input) return self.gradInput end function SelectTable:type(type) self.gradInput = {} self.output = {} return parent.type(self, type) end
local SelectTable, parent = torch.class('nn.SelectTable', 'nn.Module') function SelectTable:__init(index) parent.__init(self) self.index = index self.gradInput = {} end function SelectTable:updateOutput(input) assert(math.abs(self.index) <= #input, "arg 1 table idx out of range") if self.index < 0 then self.output = input[#input + self.index + 1] else self.output = input[self.index] end return self.output end local function zeroTableCopy(t1, t2) for k, v in pairs(t2) do if (torch.type(v) == "table") then t1[k] = zeroTableCopy(t1[k] or {}, t2[k]) else if not t1[k] then t1[k] = v:clone():zero() else local tensor = t1[k] if not tensor:isSameSizeAs(v) then t1[k]:resizeAs(v) t1[k]:zero() end end end end return t1 end function SelectTable:updateGradInput(input, gradOutput) if self.index < 0 then self.gradInput[#input + self.index + 1] = gradOutput else self.gradInput[self.index] = gradOutput end zeroTableCopy(self.gradInput, input) for i=#input+1, #self.gradInput do self.gradInput[i] = nil end return self.gradInput end function SelectTable:type(type) self.gradInput = {} self.output = {} return parent.type(self, type) end
Fix SelectTable variable input size bug
Fix SelectTable variable input size bug
Lua
bsd-3-clause
caldweln/nn,aaiijmrtt/nn,noa/nn,nicholas-leonard/nn,jzbontar/nn,forty-2/nn,xianjiec/nn,PraveerSINGH/nn,davidBelanger/nn,LinusU/nn,witgo/nn,sagarwaghmare69/nn,colesbury/nn,ominux/nn,jhjin/nn,Jeffyrao/nn,PierrotLC/nn,Aysegul/nn,elbamos/nn,joeyhng/nn,kmul00/nn,hughperkins/nn,sbodenstein/nn,andreaskoepf/nn,clementfarabet/nn,douwekiela/nn,zhangxiangxiao/nn,Djabbz/nn,Moodstocks/nn,bartvm/nn,jonathantompson/nn,adamlerer/nn,rotmanmi/nn,lukasc-ch/nn,diz-vara/nn,eulerreich/nn,ivendrov/nn,vgire/nn,GregSatre/nn,apaszke/nn,lvdmaaten/nn,EnjoyHacking/nn,eriche2016/nn,abeschneider/nn,mlosch/nn
1133f0ed81b8f953a5281e73e4de744c83d3916e
states/splash.lua
states/splash.lua
local Sprite = require 'entities.sprite' local splash = {} function splash:init() self.componentList = { { parent = self, image = Sprite:new('assets/images/NezumiSplash.png'), initialAlpha = 0, finalAlpha = 255, fadeInTime = 1, stillTime = 1.5, fadeOutTime = 0.5, init = function(self) self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2) self.image.scale = Vector(2, 2) self.image:moveOriginToCorner('center') self.alpha = self.initialAlpha Timer.tween(self.fadeInTime, self, {alpha=self.finalAlpha}, 'linear', function() Timer.tween(self.stillTime, self, {}, 'linear', function() Timer.tween(self.fadeOutTime, self, {alpha=self.initialAlpha}, 'linear', function() self.parent:incrementActive() end) end) end) end, draw = function(self) self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2) self.image.scale = Vector(2, 2) self.image:moveOriginToCorner('center') self.image.color[4] = self.alpha self.image:draw() end, }, } for k, component in pairs(self.componentList) do component:init() end self.active = 1 end function splash:enter() end function splash:incrementActive() self.active = self.active + 1 if self.active > #self.componentList then State.switch(States.game) end end function splash:update(dt) end function splash:keyreleased(key, code) if key ~= 'f11' then State.switch(States.game) end end function splash:touchreleased(id, x, y, dx, dy, pressure) State.switch(States.game) end function splash:mousepressed(x, y, mbutton) end function splash:draw() local activeComponent = self.componentList[self.active] activeComponent:draw() end return splash
local Sprite = require 'entities.sprite' local splash = {} function splash:init() self.componentList = { { parent = self, image = Sprite:new('assets/images/NezumiSplash.png'), initialAlpha = 0, finalAlpha = 255, fadeInTime = 1, stillTime = 1.5, fadeOutTime = 0.5, init = function(self) self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2) self.image.scale = Vector(2, 2) self.image:moveOriginToCorner('center') self.alpha = self.initialAlpha Timer.tween(self.fadeInTime, self, {alpha=self.finalAlpha}, 'linear', function() Timer.tween(self.stillTime, self, {}, 'linear', function() Timer.tween(self.fadeOutTime, self, {alpha=self.initialAlpha}, 'linear', function() self.parent:incrementActive() end) end) end) end, draw = function(self) self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2) self.image.scale = Vector(2, 2) self.image:moveOriginToCorner('center') self.image.color[4] = self.alpha self.image:draw() end, }, } for k, component in pairs(self.componentList) do component:init() end self.active = 1 self.isStillActive = true end function splash:enter() end function splash:incrementActive() self.active = self.active + 1 if self.active > #self.componentList and self.isStillActive then State.switch(States.game) end end function splash:update(dt) end function splash:keyreleased(key, code) if key ~= 'f11' then self.isStillActive = false State.switch(States.game) end end function splash:touchreleased(id, x, y, dx, dy, pressure) self.isStillActive = false State.switch(States.game) end function splash:mousepressed(x, y, mbutton) self.isStillActive = false State.switch(States.game) end function splash:draw() local activeComponent = self.componentList[self.active] activeComponent:draw() end return splash
fixed splashscreen bug
fixed splashscreen bug -skipping the splashscreen would cause the game to be entered twice
Lua
mit
Nuthen/ludum-dare-39
a0e53d1f7ef1076988d07238e28315aafb47c44c
lua/caps.lua
lua/caps.lua
caps_table = {} function caps_callback(event, origin, params) -- create entry if it doesnt exist if caps_table[origin] == nil then caps_table[origin] = 0 end -- increment or decrement entry if params[2]:upper() == params[2] and params[2]:lower() ~= params[2] then caps_table[origin] = caps_table[origin] + 1 elseif caps_table[origin] > 0 then caps_table[origin] = caps_table[origin] - 1 end if caps_table[origin] > 7 then irc_raw("KICK "..params[1].." "..origin.." :i warned you!") elseif caps_table[origin] > 5 then irc_msg(params[1], origin..": calm down with the caps lock, bro!") end end register_callback("CHANNEL", "caps_callback")
caps_table = {} function caps_callback(event, origin, params) -- create entry if it doesnt exist if caps_table[origin] == nil then caps_table[origin] = 0 end -- determine if its caps lock local this_is_caps = false if params[2]:upper() == params[2] and params[2]:lower() ~= params[2] then this_is_caps = true end -- increment or decrement entry if this_is_caps then caps_table[origin] = caps_table[origin] + 1 elseif caps_table[origin] > 0 then caps_table[origin] = caps_table[origin] - 1 end -- determine if we should kick if caps_table[origin] > 7 and this_is_caps then irc_raw("KICK "..params[1].." "..origin.." :i warned you!") elseif caps_table[origin] > 5 and this_is_caps then irc_msg(params[1], origin..": calm down with the caps lock, bro!") end end register_callback("CHANNEL", "caps_callback")
bugfix
bugfix
Lua
mit
wetfish/denice,pielover88888/denice
2f6ca0401b823a158b9cccfe156c9fbfe09acf3b
init.lua
init.lua
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 for i = 1, buffer.column[buffer.current_pos] do local c = buffer.char_at[buffer.current_pos - i] if (c >= 32 and c <= 47)or(c >= 58 and c <= 64)then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end return shift, suggestions end local function remove_type_info(text, position) local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() end buffer:auto_c_cancel() end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 local curline = buffer:get_cur_line() local cur_col = buffer.column[buffer.current_pos] + 1 for i = 1, cur_col do local shifted_col = cur_col - i local c = curline:sub(shifted_col, shifted_col) if c == c:match("([^%w_-])") then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end return shift, suggestions end local function remove_type_info(text, position) local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() end buffer:auto_c_cancel() end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
More clear shift calculation (should be less buggy)
More clear shift calculation (should be less buggy)
Lua
mit
xomachine/textadept-nim
ce7af7c3fa340b68eeb574701be0c192a55c78bd
src/luacheck/flow.lua
src/luacheck/flow.lua
local non_ctrl_tags = { Nil = true, Dots = true, True = true, False = true, Number = true, String = true, Function = true, Table = true, Op = true, Paren = true, Call = true, Invoke = true, Id = true, Index = true, Set = true, Local = true, Localrec = true } local multi_stmt_tags = { Block = true, Do = true, While = true, Repeat = true, If = true, Fornum = true, Forin = true } -- Builds and returns flow graph for a closure. -- Adds graph nodes to intel.flow_nodes. local function build_graph(closure, intel) -- Maps labels and loops to label graph nodes and after-loop nodes. local jump_nodes = {} -- Array of pairs {node_from, stmt}, stmt is a break or goto. local jumps = {} local function new_node(ast_node) local node = {prevs = {}, nexts = {}, ast_node = ast_node} intel.flow_nodes[#intel.flow_nodes+1] = node return node end local first_node = new_node() local last_node = new_node() local function add_edge(from_node, to_node) from_node.nexts[#from_node.nexts+1] = to_node to_node.prevs[#to_node.prevs+1] = from_node end local function append_node(head, ast_node) local new = new_node(ast_node) add_edge(head, new) return new end -- Builds a "line" starting from start_node along array of statements. Returns end node of the line. local function build_line(stmts, start_node) local head = start_node for i=1, #stmts do local stmt = stmts[i] local tag = stmt.tag or "Block" if non_ctrl_tags[tag] then head = append_node(head, stmt) elseif multi_stmt_tags[tag] then if tag == "Block" or tag == "Do" then head = build_line(stmt, head) elseif tag == "If" then local after_if_node = new_node() for i=1, #stmt, 2 do head = append_node(head, stmt[i]) add_edge(build_line(stmt[i+1], head), after_if_node) end if #stmt % 2 == 1 then -- last else block add_edge(build_line(stmt[#stmt], head), after_if_node) else add_edge(head, after_if_node) end head = after_if_node elseif tag == "Forin" or tag == "Fornum" then head = append_node(head, stmt) -- save declaration of loop vars head = append_node(head) add_edge(build_line(stmt[5] or stmt[4] or stmt[3], head), head) head = append_node(head) jump_nodes[stmt] = head elseif tag == "While" then head = append_node(head, stmt[1]) add_edge(build_line(stmt[2], head), head) head = append_node(head) jump_nodes[stmt] = head elseif tag == "Repeat" then head = append_node(head) local repeat_end_node = build_line(stmt[1], head) repeat_end_node = append_node(repeat_end_node, stmt[2]) add_edge(repeat_end_node, head) head = append_node(repeat_end_node) jump_nodes[stmt] = head end elseif tag == "Return" then add_edge(append_node(head, stmt), last_node) head = new_node() elseif tag == "Break" or tag == "Goto" then jumps[#jumps+1] = {head, stmt} head = new_node() elseif tag == "Label" then head = append_node(head) jump_nodes[stmt] = head end end return head end add_edge(build_line(closure.stmts, first_node), last_node) for i=1, #jumps do add_edge(jumps[i][1], jump_nodes[intel.gotos[jumps[i][2]]]) end return first_node end -- Requires intel.closures, intel.gotos. -- intel.closures must be an array/map of closures. -- closure := {stmts = stmts, [...?]} -- intel.gotos must map breaks to loops and gotos to labels. -- Note: metalua actually does not support gotos? -- Sets closure.flow = flow graph for closure in intel.closures. -- Sets intel.flow_nodes to array of all flow graph nodes. -- graph := {nexts = {graph, ...}, prevs = {graph, ...}, ast_node = ast_node | nil} -- Each expression in the ast is mentioned exactly once in the graphs. -- -- Example usage: https://gist.github.com/mpeterv/d1741738876e9923e77c -- Will be used to resolve local variables and find unreachable code. -- TODO: implement intel.closures, intel.gotos -- TODO: tests local function flow(intel) intel.flow_nodes = {} for i=1, #intel.closures do intel.closures[i].flow = build_graph(intel.closures[i], intel) end end return flow
local non_ctrl_tags = { Nil = true, Dots = true, True = true, False = true, Number = true, String = true, Function = true, Table = true, Op = true, Paren = true, Call = true, Invoke = true, Id = true, Index = true, Set = true, Local = true, Localrec = true } local multi_stmt_tags = { Block = true, Do = true, While = true, Repeat = true, If = true, Fornum = true, Forin = true } -- Builds and returns flow graph for a closure. -- Adds graph nodes to intel.flow_nodes. local function build_graph(closure, intel) -- Maps labels and loops to label graph nodes and after-loop nodes. local jump_nodes = {} -- Array of pairs {node_from, stmt}, stmt is a break or goto. local jumps = {} local function new_node(ast_node) local node = {prevs = {}, nexts = {}, ast_node = ast_node} intel.flow_nodes[#intel.flow_nodes+1] = node return node end local first_node = new_node() local last_node = new_node() local function add_edge(from_node, to_node) from_node.nexts[#from_node.nexts+1] = to_node to_node.prevs[#to_node.prevs+1] = from_node end local function append_node(head, ast_node) local new = new_node(ast_node) add_edge(head, new) return new end -- Builds a "line" starting from start_node along array of statements. Returns end node of the line. local function build_line(stmts, start_node) local head = start_node for i=1, #stmts do local stmt = stmts[i] local tag = stmt.tag or "Block" if non_ctrl_tags[tag] then head = append_node(head, stmt) elseif multi_stmt_tags[tag] then if tag == "Block" or tag == "Do" then head = build_line(stmt, head) elseif tag == "If" then local after_if_node = new_node() for i=1, #stmt-1, 2 do head = append_node(head, stmt[i]) add_edge(build_line(stmt[i+1], head), after_if_node) end if #stmt % 2 == 1 then -- last else block add_edge(build_line(stmt[#stmt], head), after_if_node) else add_edge(head, after_if_node) end head = after_if_node elseif tag == "Forin" or tag == "Fornum" then head = append_node(head, stmt) -- save declaration of loop vars head = append_node(head) add_edge(build_line(stmt[5] or stmt[4] or stmt[3], head), head) head = append_node(head) jump_nodes[stmt] = head elseif tag == "While" then head = append_node(head, stmt[1]) add_edge(build_line(stmt[2], head), head) head = append_node(head) jump_nodes[stmt] = head elseif tag == "Repeat" then head = append_node(head) local repeat_end_node = build_line(stmt[1], head) repeat_end_node = append_node(repeat_end_node, stmt[2]) add_edge(repeat_end_node, head) head = append_node(repeat_end_node) jump_nodes[stmt] = head end elseif tag == "Return" then add_edge(append_node(head, stmt), last_node) head = new_node() elseif tag == "Break" or tag == "Goto" then jumps[#jumps+1] = {head, stmt} head = new_node() elseif tag == "Label" then head = append_node(head) jump_nodes[stmt] = head end end return head end add_edge(build_line(closure.stmts, first_node), last_node) for i=1, #jumps do add_edge(jumps[i][1], jump_nodes[intel.gotos[jumps[i][2]]]) end return first_node end -- Requires intel.closures, intel.gotos. -- intel.closures must be an array/map of closures. -- closure := {stmts = stmts, [...?]} -- intel.gotos must map breaks to loops and gotos to labels. -- Note: metalua actually does not support gotos? -- Sets closure.flow = flow graph for closure in intel.closures. -- Sets intel.flow_nodes to array of all flow graph nodes. -- graph := {nexts = {graph, ...}, prevs = {graph, ...}, ast_node = ast_node | nil} -- Each expression in the ast is mentioned exactly once in the graphs. -- -- Example usage: -- pfg printer: https://gist.github.com/mpeterv/d1741738876e9923e77c -- unreachable code detector: https://gist.github.com/mpeterv/65eb04e36f68a866dc58 -- Will be used to resolve local variables and find unreachable code. -- TODO: implement intel.closures, intel.gotos -- TODO: tests local function flow(intel) intel.flow_nodes = {} for i=1, #intel.closures do intel.closures[i].flow = build_graph(intel.closures[i], intel) end end return flow
Fixed luacheck.flow crash on if else
Fixed luacheck.flow crash on if else
Lua
mit
adan830/luacheck,kidaa/luacheck,mpeterv/luacheck,linuxmaniac/luacheck,adan830/luacheck,linuxmaniac/luacheck,tst2005/luacheck,xpol/luacheck,tst2005/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck,kidaa/luacheck,mpeterv/luacheck
42422c429ad04eda1955695badf59642fb16a24a
commands/build.lua
commands/build.lua
zpm.build.commands = {} zpm.build.rcommands = {} function zpm.build.commands.option( opt ) zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt) return zpm.build._currentDependency.options[opt] == true end function zpm.build.commands.export( commands ) local name = project().name local parent = zpm.build._currentDependency.projects[name].export local currExp = zpm.build._currentExportPath local currDep = zpm.build._currentDependency zpm.build._currentDependency.projects[name].export = function() if parent ~= nil then parent() end local old = zpm.build._currentExportPath local oldDep = zpm.build._currentDependency zpm.build._currentExportPath = currExp zpm.build._currentDependency = currDep zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) zpm.build._currentExportPath = old zpm.build._currentDependency = oldDep end zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) end function zpm.build.commands.uses( proj ) if type(proj) ~= "table" then proj = {proj} end local cname = project().name if zpm.build._currentDependency.projects[cname] == nil then zpm.build._currentDependency.projects[cname] = {} end if zpm.build._currentDependency.projects[cname].uses == nil then zpm.build._currentDependency.projects[cname].uses = {} end if zpm.build._currentDependency.projects[cname].packages == nil then zpm.build._currentDependency.projects[cname].packages = {} end for _, p in ipairs(proj) do if p:contains( "/" ) then local package = zpm.build.findProject( p ) if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then table.insert( zpm.build._currentDependency.projects[cname].packages, package ) end else local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then table.insert( zpm.build._currentDependency.projects[cname].uses, name ) end end end end function zpm.build.rcommands.project( proj ) local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) project( name ) location( zpm.install.getExternDirectory() ) targetdir( zpm.build._currentTargetPath ) objdir( zpm.build._currentObjPath ) if zpm.build._currentDependency.projects == nil then zpm.build._currentDependency.projects = {} end if zpm.build._currentDependency.projects[name] == nil then zpm.build._currentDependency.projects[name] = {} end end function zpm.build.rcommands.dependson( depdson ) if type(depdson) ~= "table" then depdson = {depdson} end for _, p in ipairs(depdson) do local dep = zpm.build._currentDependency dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) ) end end function zpm.build.rcommands.kind( knd ) local name = project().name zpm.build._currentDependency.projects[name].kind = knd kind( knd ) end function zpm.build.rcommands.filter( ... ) filter( ... ) end
zpm.build.commands = {} zpm.build.rcommands = {} function zpm.build.commands.option( opt ) zpm.assert(zpm.build._currentDependency.options ~= nil, "Option '%s' does not exist!", opt) zpm.assert(zpm.build._currentDependency.options[opt] ~= nil, "Option '%s' does not exist!", opt) return zpm.build._currentDependency.options[opt] == true end function zpm.build.commands.export( commands ) local name = project().name local parent = zpm.build._currentDependency.projects[name].export local currExp = zpm.build._currentExportPath local currDep = zpm.build._currentDependency zpm.build._currentDependency.projects[name].export = function() if parent ~= nil then parent() end local old = zpm.build._currentExportPath local oldDep = zpm.build._currentDependency zpm.build._currentExportPath = currExp zpm.build._currentDependency = currDep zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) zpm.build._currentExportPath = old zpm.build._currentDependency = oldDep end zpm.sandbox.run( commands, {env = zpm.build.getEnv()}) end function zpm.build.commands.uses( proj ) if type(proj) ~= "table" then proj = {proj} end local cname = project().name if zpm.build._currentDependency.projects[cname] == nil then zpm.build._currentDependency.projects[cname] = {} end if zpm.build._currentDependency.projects[cname].uses == nil then zpm.build._currentDependency.projects[cname].uses = {} end if zpm.build._currentDependency.projects[cname].packages == nil then zpm.build._currentDependency.projects[cname].packages = {} end for _, p in ipairs(proj) do if p:contains( "/" ) then local package = zpm.build.findProject( p ) if table.contains( zpm.build._currentDependency.projects[cname].packages, package ) == false then table.insert( zpm.build._currentDependency.projects[cname].packages, package ) end else local name = zpm.build.getProjectName( p, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) if table.contains( zpm.build._currentDependency.projects[cname].uses, name ) == false then table.insert( zpm.build._currentDependency.projects[cname].uses, name ) end end end end function zpm.build.rcommands.project( proj ) local name = zpm.build.getProjectName( proj, zpm.build._currentDependency.fullName, zpm.build._currentDependency.version ) project( name ) location( zpm.install.getExternDirectory() ) targetdir( zpm.build._currentTargetPath ) objdir( zpm.build._currentObjPath ) if zpm.build._currentDependency.projects == nil then zpm.build._currentDependency.projects = {} end if zpm.build._currentDependency.projects[name] == nil then zpm.build._currentDependency.projects[name] = {} end end function zpm.build.rcommands.dependson( depdson ) if type(depdson) ~= "table" then depdson = {depdson} end for _, p in ipairs(depdson) do local dep = zpm.build._currentDependency dependson( zpm.build.getProjectName( p, dep.fullName, dep.version ) ) end end function zpm.build.rcommands.kind( knd ) local name = project().name zpm.build._currentDependency.projects[name].kind = knd kind( knd ) end function zpm.build.rcommands.filter( ... ) filter( ... ) end
Fix option does not exist
Fix option does not exist
Lua
mit
Zefiros-Software/ZPM
b5e7d774b2146dbc70ae40b147af846ba4d8e896
init.lua
init.lua
-- Copyright 2015 BMC Software, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local split = framework.string.split local notEmpty = framework.string.notEmpty local Plugin = framework.Plugin local NetDataSource = framework.NetDataSource local Accumulator = framework.Accumulator local map = framework.functional.map local reduce = framework.functional.reduce local filter = framework.functional.filter local each = framework.functional.each local ipack = framework.util.ipack local params = framework.params local ds = NetDataSource:new(params.host, params.port, true) function ds:onFetch(socket) socket:write('mntr\n') end local plugin = Plugin:new(params, ds) local function parseLine(line) return split(line, '\t') end local function toMapReducer (acc, x) local k = x[1] local v = x[2] acc[k] = v return acc end local function parse(data) local lines = filter(notEmpty, split(data, '\n')) local parsedLines = map(parseLine, lines) local m = reduce(toMapReducer, {}, parsedLines) return m end local acc = Accumulator:new() function plugin:onParseValues(data) local parsed = parse(data) local metrics = {} metrics['ZK_WATCH_COUNT'] = false metrics['ZK_NUM_ALIVE_CONNECTIONS'] = false metrics['ZK_OPEN_FILE_DESCRIPTOR_COUNT'] = false metrics['ZK_OUTSTANDING_REQUESTS'] = false metrics['ZK_PACKETS_SENT'] = true metrics['ZK_PACKETS_RECEIVED'] = true metrics['ZK_APPROXIMATE_DATA_SIZE'] = true metrics['ZK_MIN_LATENCY'] = false metrics['ZK_MAX_LATENCY'] = false metrics['ZK_AVG_LATENCY'] = false metrics['ZK_EPHEMERALS_COUNT'] = false metrics['ZK_ZNODE_COUNT'] = false metrics['ZK_MAX_FILE_DESCRIPTOR_COUNT'] = false metrics['ZK_SERVER_STATE'] = false metrics['ZK_FOLLOWERS'] = false metrics['ZK_SYNCED_FOLLOWERS'] = false metrics['ZK_PENDING_SYNCS'] = false local result = {} each( function (boundary_name, accumulate) local metric_name = boundary_name:lower() if parsed[metric_name] then local value = (metric_name == "zk_server_state" and (parsed[metric_name] == "leader" and 1 or 0)) or tonumber(parsed[metric_name]) ipack(result, boundary_name, accumulate and acc(boundary_name, value) or value) end end, metrics) return result end plugin:run()
-- Copyright 2015 BMC Software, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local split = framework.string.split local notEmpty = framework.string.notEmpty local Plugin = framework.Plugin local NetDataSource = framework.NetDataSource local Accumulator = framework.Accumulator local map = framework.functional.map local reduce = framework.functional.reduce local filter = framework.functional.filter local each = framework.functional.each local ipack = framework.util.ipack local params = framework.params local ds = NetDataSource:new(params.host, params.port, true) function ds:onFetch(socket) socket:write('mntr\n') end local plugin = Plugin:new(params, ds) local function parseLine(line) return split(line, '\t') end local function toMapReducer (acc, x) local k = x[1] local v = x[2] acc[k] = v return acc end local function parse(data) local lines = filter(notEmpty, split(data, '\n')) local parsedLines = map(parseLine, lines) local m = reduce(toMapReducer, {}, parsedLines) return m end local acc = Accumulator:new() function plugin:onParseValues(data) local parsed = parse(data) local result = {} local metric = function (...) ipack(result, ...) end local src = notEmpty(params.source,nil) metric('ZK_WATCH_COUNT',parsed.zk_watch_count,nil,src) metric('ZK_NUM_ALIVE_CONNECTIONS',parsed.zk_num_alive_connections,nil,src) metric('ZK_OPEN_FILE_DESCRIPTOR_COUNT',parsed.zk_open_file_descriptor_count,nil,src) metric('ZK_OUTSTANDING_REQUESTS',parsed.zk_outstanding_requests,nil,src) metric('ZK_PACKETS_SENT',parsed.zk_packets_sent,nil,src) metric('ZK_PACKETS_RECEIVED',parsed.zk_packets_received,nil,src) metric('ZK_APPROXIMATE_DATA_SIZE',parsed.zk_approximate_data_size,nil,src) metric('ZK_MIN_LATENCY',parsed.zk_min_latency,nil,src) metric('ZK_MAX_LATENCY',parsed.zk_max_latency,nil,src) metric('ZK_AVG_LATENCY',parsed.zk_avg_latency,nil,src) metric('ZK_EPHEMERALS_COUNT',parsed.zk_ephemerals_count,nil,src) metric('ZK_ZNODE_COUNT',parsed.zk_znode_count,nil,src) metric('ZK_MAX_FILE_DESCRIPTOR_COUNT',parsed.zk_max_file_descriptor_count,nil,src) if parsed.zk_server_state == "leader" then metric('ZK_SERVER_STATE',1,nil,src) else metric('ZK_SERVER_STATE',0,nil,src) end metric('ZK_FOLLOWERS',(parsed.zk_followers or 0),nil,src) metric('ZK_SYNCED_FOLLOWERS',(parsed.zk_synced_followers or 0),nil,src) metric('ZK_PENDING_SYNCS',(parsed.zk_pending_syncs or 0),nil,src) return result end plugin:run()
simpler onparsevalues code to fix issue PLUG-174
simpler onparsevalues code to fix issue PLUG-174
Lua
apache-2.0
boundary/boundary-plugin-zookeeper
f761a44d3942be780616c0e43d70d1bf4927d4da
lua_modules/luvit-rackspace-monitoring-client/lib/client.lua
lua_modules/luvit-rackspace-monitoring-client/lib/client.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 JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local string = require('string') local fmt = require('string').format local https = require('https') local url = require('url') local table = require('table') local Error = require('core').Error local async = require('async') local misc = require('./misc') local errors = require('./errors') local KeystoneClient = require('keystone').Client local MAAS_CLIENT_KEYSTONE_URL = 'https://identity.api.rackspacecloud.com/v2.0' local MAAS_CLIENT_DEFAULT_HOST = 'monitoring.api.rackspacecloud.com' local MAAS_CLIENT_DEFAULT_VERSION = 'v1.0' --[[ ClientBase ]]-- local ClientBase = Object:extend() function ClientBase:initialize(host, port, version, apiType, options) local headers = {} self.host = host self.port = port self.version = version self.apiType = apiType self.tenantId = nil if self.apiType == 'public' then headers['User-Agent'] = 'agent/virgo' end self.headers = headers self.options = misc.merge({}, options) self.headers['Accept'] = 'application/json' self.headers['Content-Type'] = 'application/json' end function ClientBase:setToken(token, expiry) self.token = token self.headers['X-Auth-Token'] = token self._tokenExpiry = expiry end function ClientBase:setTenantId(tenantId) self.tenantId = tenantId end function ClientBase:_parseResponse(data, callback) local parsed = JSON.parse(data) callback(nil, parsed) end function ClientBase:_parseData(data) local res = { xpcall(function() return JSON.parse(data) end, function(e) return e end) } if res[1] == false then return res[2] else return JSON.parse(res[2]) end end function ClientBase:request(method, path, payload, expectedStatusCode, callback) local options local headers local extraHeaders = {} -- setup payload if payload then if type(payload) == 'table' and self.headers['Content-Type'] == 'application/json' then payload = JSON.stringify(payload) end extraHeaders['Content-Length'] = #payload else extraHeaders['Content-Length'] = 0 end -- setup path if self.tenantId then path = fmt('/%s/%s%s', self.version, self.tenantId, path) else path = fmt('/%s%s', self.version, path) end headers = misc.merge(self.headers, extraHeaders) options = { host = self.host, port = self.port, path = path, headers = headers, method = method } local req = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() self._lastRes = res if res.statusCode ~= expectedStatusCode then callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) else if res.statusCode == 200 then self:_parseResponse(data, callback) elseif res.statusCode == 201 or res.statusCode == 204 then callback(nil, res.headers['location']) else data = self:_parseData(data) callback(errors.HttpResponseError:new(res.statusCode, method, path, data)) end end end) end) if payload then req:write(payload) end req:done() end --[[ Client ]]-- local Client = ClientBase:extend() function Client:initialize(userId, key, options) options = options or {} self.userId = userId self.key = key self.authUrl = options.authUrl self.entities = {} self.agent_tokens = {} self:_init() ClientBase.initialize(self, MAAS_CLIENT_DEFAULT_HOST, 443, MAAS_CLIENT_DEFAULT_VERSION, 'public', options) end function Client:_init() self.entities.get = function(callback) self:request('GET', '/entities', nil, 200, callback) end self.agent_tokens.get = function(callback) self:request('GET', '/agent_tokens', nil, 200, callback) end self.agent_tokens.create = function(options, callback) local body = {} body['label'] = options.label self:request('POST', '/agent_tokens', body, 201, function(err, tokenUrl) if err then callback(err) return end callback(nil, string.match(tokenUrl, 'agent_tokens/(.*)')) end) end end function Client:auth(authUrl, username, keyOrPassword, callback) local apiKeyClient = KeystoneClient:new(authUrl, { username = self.userId, apikey = keyOrPassword }) local passwordClient = KeystoneClient:new(authUrl, { username = self.userId, password = keyOrPassword }) local errors = {} local responses = {} function iterator(client, callback) client:tenantIdAndToken(function(err, obj) if err then table.insert(errors, err) callback() else table.insert(responses, obj) callback() end end) end async.forEach({ apiKeyClient, passwordClient }, iterator, function() if #responses > 0 then callback(nil, responses[1]) else callback(errors) end end) end --[[ The request. callback.function(err, results) ]]-- function Client:request(method, path, payload, expectedStatusCode, callback) local authUrl = self.authUrl or MAAS_CLIENT_KEYSTONE_URL local authPayload local results async.waterfall({ function(callback) if self:tokenValid() then callback() return end self:auth(authUrl, self.userId, self.key, function(err, obj) if err then callback(err) return end self:setToken(obj.token, obj.expires) self:setTenantId(obj.tenantId) callback() end) end, function(callback) ClientBase.request(self, method, path, payload, expectedStatusCode, function(err, obj) if not err then results = obj end callback(err) end) end }, function(err) callback(err, results) end) end function Client:tokenValid() if self.token then return true end -- TODO add support for expiry return nil end local exports = {} exports.Client = Client return exports
rackspace-monitoring-client: bump client for parse fix
rackspace-monitoring-client: bump client for parse fix
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
256bc48eacba55c56a2de5420133fd655edcf5dc
pud/component/Component.lua
pud/component/Component.lua
local Class = require 'lib.hump.class' local property = require 'pud.component.property' -- Component -- local Component = Class{name='Component', function(self, newProperties) self._properties = {} self:_createProperties(newProperties) end } -- destructor function Component:destroy() for k in pairs(self._properties) do self._properties[k] = nil end self._properties = nil if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:detach(message(msg), self) end self._attachMessages = nil end self._mediator = nil end -- create properties from the given table, add default values if needed function Component:_createProperties(newProperties) if newProperties ~= nil then verify('table', newProperties) for p in pairs(newProperties) do self:_setProperty(p, newProperties[p]) end end -- add missing defaults if self._requiredProperties then verify('table', self._requiredProperties) for _,p in pairs(self._requiredProperties) do if not self._properties[p] then self:_setProperty(p) end end end end -- set the mediator who owns this component function Component:setMediator(mediator) verifyClass('pud.component.ComponentMediator', mediator) self._mediator = mediator end -- attach all of this component's messages to its mediator function Component:attachMessages() for _,msg in pairs(_attachMessages) do self._mediator:attach(message(msg), self) end end -- set a property for this component function Component:_setProperty(prop, data) self._properties[property(prop)] = data or property.default(prop) end -- receive a message -- precondition: msg is a valid component message function Component:receive(msg, ...) end -- return the given property if we have it, or nil if we do not -- precondition: p is a valid component property function Component:getProperty(p) return self._properties[p] end -- attach this component to the messages it wants to receive function Component:attachMessages() end -- the class return Component
local Class = require 'lib.hump.class' local property = require 'pud.component.property' local message = require 'pud.component.message' -- Component -- local Component = Class{name='Component', function(self, newProperties) self._properties = {} self:_createProperties(newProperties) end } -- destructor function Component:destroy() for k in pairs(self._properties) do self._properties[k] = nil end self._properties = nil if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:detach(message(msg), self) end self._attachMessages = nil end self._mediator = nil end -- create properties from the given table, add default values if needed function Component:_createProperties(newProperties) if newProperties ~= nil then verify('table', newProperties) for p in pairs(newProperties) do self:_setProperty(p, newProperties[p]) end end -- add missing defaults if self._requiredProperties then verify('table', self._requiredProperties) for _,p in pairs(self._requiredProperties) do if not self._properties[p] then self:_setProperty(p) end end end end -- set the mediator who owns this component function Component:setMediator(mediator) verifyClass('pud.component.ComponentMediator', mediator) self._mediator = mediator end -- attach all of this component's messages to its mediator function Component:attachMessages() if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:attach(message(msg), self) end end end -- set a property for this component function Component:_setProperty(prop, data) self._properties[property(prop)] = data or property.default(prop) end -- receive a message -- precondition: msg is a valid component message function Component:receive(msg, ...) end -- return the given property if we have it, or nil if we do not -- precondition: p is a valid component property function Component:getProperty(p) return self._properties[p] end -- the class return Component
fix attachMessages()
fix attachMessages()
Lua
mit
scottcs/wyx
d027c90bd0f6e3d2588d929de39faa60a8a3913e
tests/lua/tc_bug1.lua
tests/lua/tc_bug1.lua
local env = environment() local N = Const("N") local p = Const("p") local q = Const("q") local a = Const("a") local b = Const("b") local f = Const("f") local H1 = Const("H1") local H2 = Const("H2") local And = Const("and") local and_intro = Const("and_intro") local A = Local("A", Bool) local B = Local("B", Bool) env = add_decl(env, mk_var_decl("N", Type)) env = add_decl(env, mk_var_decl("p", mk_arrow(N, N, Bool))) env = add_decl(env, mk_var_decl("q", mk_arrow(N, Bool))) env = add_decl(env, mk_var_decl("f", mk_arrow(N, N))) env = add_decl(env, mk_var_decl("a", N)) env = add_decl(env, mk_var_decl("b", N)) env = add_decl(env, mk_var_decl("and", mk_arrow(Bool, Bool, Bool))) env = add_decl(env, mk_var_decl("and_intro", Pi({A, B}, mk_arrow(A, B, And(A, B))))) env = add_decl(env, mk_var_decl("foo_intro", Pi({A, B}, mk_arrow(B, B)))) env = add_decl(env, mk_var_decl("foo_intro2", Pi({A, B}, mk_arrow(B, B)))) env = add_decl(env, mk_axiom("Ax1", q(a))) env = add_decl(env, mk_axiom("Ax2", q(a))) env = add_decl(env, mk_axiom("Ax3", q(b))) local Ax1 = Const("Ax1") local Ax2 = Const("Ax2") local Ax3 = Const("Ax3") local foo_intro = Const("foo_intro") local foo_intro2 = Const("foo_intro2") local cs = {} local ng = name_generator("foo") local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) local m1 = mk_metavar("m1", Bool) print("before is_def_eq") assert(not tc:is_def_eq(and_intro(m1, q(a)), and_intro(q(a), q(b)))) assert(#cs == 0) local cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) assert(tc:is_def_eq(foo_intro(m1, q(a), Ax1), foo_intro(q(a), q(a), Ax2))) assert(#cs == 1) -- constraint is used, but there is an alternative that does not use it assert(cs[1]:lhs() == m1) assert(cs[1]:rhs() == q(a)) cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) assert(tc:is_def_eq(foo_intro(m1, q(a), Ax1), foo_intro2(q(a), q(a), Ax2))) assert(#cs == 0) -- constraint should be ignored since we have shown definitional equality using proof irrelevance cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) print("before failure") assert(not pcall(function() print(tc:check(and_intro(m1, q(a), Ax1, Ax3))) end)) assert(#cs == 0) -- the check failed, so the constraints should be preserved cs = {} print("before success") print(tc:check(and_intro(m1, q(a), Ax1, Ax2))) assert(#cs == 1) -- the check succeeded, and we must get one constraint -- Demo: infer method may generate constraints -- local m2 = mk_metavar("m2", mk_metavar("ty_m2", mk_sort(mk_meta_univ("s_m2")))) -- print(tc:infer(mk_pi("x", m2, Var(0))))
local env = environment() local N = Const("N") local p = Const("p") local q = Const("q") local a = Const("a") local b = Const("b") local f = Const("f") local H1 = Const("H1") local H2 = Const("H2") local And = Const("and") local and_intro = Const("and_intro") local A = Local("A", Bool) local B = Local("B", Bool) local C = Local("C", Bool) env = add_decl(env, mk_var_decl("N", Type)) env = add_decl(env, mk_var_decl("p", mk_arrow(N, N, Bool))) env = add_decl(env, mk_var_decl("q", mk_arrow(N, Bool))) env = add_decl(env, mk_var_decl("f", mk_arrow(N, N))) env = add_decl(env, mk_var_decl("a", N)) env = add_decl(env, mk_var_decl("b", N)) env = add_decl(env, mk_var_decl("and", mk_arrow(Bool, Bool, Bool))) env = add_decl(env, mk_var_decl("and_intro", Pi({A, B}, mk_arrow(A, B, And(A, B))))) env = add_decl(env, mk_var_decl("foo_intro", Pi({A, B, C}, mk_arrow(B, B)))) env = add_decl(env, mk_var_decl("foo_intro2", Pi({A, B, C}, mk_arrow(B, B)))) env = add_decl(env, mk_axiom("Ax1", q(a))) env = add_decl(env, mk_axiom("Ax2", q(a))) env = add_decl(env, mk_axiom("Ax3", q(b))) local Ax1 = Const("Ax1") local Ax2 = Const("Ax2") local Ax3 = Const("Ax3") local foo_intro = Const("foo_intro") local foo_intro2 = Const("foo_intro2") local cs = {} local ng = name_generator("foo") local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) local m1 = mk_metavar("m1", Bool) print("before is_def_eq") assert(not tc:is_def_eq(and_intro(m1, q(a)), and_intro(q(a), q(b)))) assert(#cs == 0) local cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) assert(tc:is_def_eq(foo_intro(m1, q(a), q(a), Ax1), foo_intro(q(a), q(a), q(a), Ax2))) assert(#cs == 1) -- constraint is used, but there is an alternative that does not use it assert(cs[1]:lhs() == m1) assert(cs[1]:rhs() == q(a)) cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) assert(#cs == 0) print(tostring(foo_intro) .. " : " .. tostring(tc:check(foo_intro))) print(tostring(foo_intro2) .. " : " .. tostring(tc:check(foo_intro2))) assert(tc:is_def_eq(foo_intro, foo_intro2)) print("before is_def_eq2") assert(tc:is_def_eq(foo_intro(m1, q(a), q(b), Ax1), foo_intro2(q(a), q(a), q(a), Ax2))) assert(#cs == 0) -- constraint should be ignored since we have shown definitional equality using proof irrelevance cs = {} local tc = type_checker(env, ng, function (c) print(c); cs[#cs+1] = c end) print("before failure") assert(not pcall(function() print(tc:check(and_intro(m1, q(a), Ax1, Ax3))) end)) assert(#cs == 0) -- the check failed, so the constraints should be preserved cs = {} print("before success") print(tc:check(and_intro(m1, q(a), Ax1, Ax2))) assert(#cs == 1) -- the check succeeded, and we must get one constraint -- Demo: infer method may generate constraints -- local m2 = mk_metavar("m2", mk_metavar("ty_m2", mk_sort(mk_meta_univ("s_m2")))) -- print(tc:infer(mk_pi("x", m2, Var(0))))
fix(tests/lua/tc_bug1): update test to reflect recent changes
fix(tests/lua/tc_bug1): update test to reflect recent changes Signed-off-by: Leonardo de Moura <7610bae85f2b530654cc716772f1fe653373e892@microsoft.com>
Lua
apache-2.0
javra/lean,rlewis1988/lean,javra/lean,rlewis1988/lean,sp3ctum/lean,sp3ctum/lean,soonhokong/lean-windows,avigad/lean,soonhokong/lean-osx,htzh/lean,fgdorais/lean,sp3ctum/lean,UlrikBuchholtz/lean,digama0/lean,levnach/lean,fgdorais/lean,eigengrau/lean,avigad/lean,leodemoura/lean,levnach/lean,fpvandoorn/lean,soonhokong/lean-osx,UlrikBuchholtz/lean,eigengrau/lean,avigad/lean,fpvandoorn/lean,htzh/lean,johoelzl/lean,javra/lean,c-cube/lean,digama0/lean,dselsam/lean,leanprover-community/lean,dselsam/lean,fpvandoorn/lean,leanprover-community/lean,soonhokong/lean-windows,digama0/lean,c-cube/lean,soonhokong/lean,Kha/lean,dselsam/lean,levnach/lean,soonhokong/lean-windows,htzh/lean,javra/lean,fpvandoorn/lean2,fpvandoorn/lean,fpvandoorn/lean,c-cube/lean,UlrikBuchholtz/lean,leodemoura/lean,fpvandoorn/lean2,digama0/lean,leanprover-community/lean,leanprover/lean,fpvandoorn/lean2,levnach/lean,leanprover/lean,UlrikBuchholtz/lean,leanprover/lean,eigengrau/lean,soonhokong/lean-windows,fpvandoorn/lean2,avigad/lean,rlewis1988/lean,leodemoura/lean,Kha/lean,leanprover-community/lean,soonhokong/lean,fgdorais/lean,dselsam/lean,Kha/lean,leanprover-community/lean,fpvandoorn/lean2,javra/lean,leanprover/lean,avigad/lean,htzh/lean,Kha/lean,dselsam/lean,eigengrau/lean,fgdorais/lean,rlewis1988/lean,sp3ctum/lean,johoelzl/lean,avigad/lean,c-cube/lean,rlewis1988/lean,johoelzl/lean,digama0/lean,leodemoura/lean,sp3ctum/lean,soonhokong/lean,digama0/lean,levnach/lean,Kha/lean,johoelzl/lean,UlrikBuchholtz/lean,soonhokong/lean-osx,leodemoura/lean,johoelzl/lean,leanprover-community/lean,rlewis1988/lean,soonhokong/lean-osx,leodemoura/lean,soonhokong/lean,Kha/lean,soonhokong/lean,soonhokong/lean-osx,fpvandoorn/lean,leanprover/lean,c-cube/lean,leanprover/lean,fgdorais/lean,dselsam/lean,soonhokong/lean-windows,eigengrau/lean,htzh/lean,johoelzl/lean,fgdorais/lean
a701a4eb62ceaea938451e65f52029e3e3b07832
src/game.lua
src/game.lua
-- vendor libs require 'vendor/AnAL' local PrettyPrint = require 'vendor/lua-pretty-print/PrettyPrint' local gamestate = require 'vendor/hump/gamestate' local Camera = require 'vendor/hump/camera' local Grid = require 'vendor/Jumper/jumper.grid' local Pathfinder = require 'vendor/Jumper/jumper.pathfinder' -- game modules local utils = require 'utils' local Scv = require 'units/scv' local ux = require 'ux' -- locals local cam = nil local map = nil local game = {} local entities = {} local pather = nil -- selection local selx, sely = 0, 0 local selw, selh = 0, 0 local selection = {} function game:init() end local function doTestPathfind( pather ) local sx, sy = 1, 1 local dx, dy = 1, 3 local path, length = pather:getPath( sx, sy, dx, dy ) if path then for node, count in path:nodes() do print( ('Step: %d - x: %d , y: %d'):format( count, node:getX(), node:getY() ) ) end else print( "no path found!" ) end end function game:enter() -- just the same map every time for now map = utils.buildMap( "art/maps/standard" ) cam = Camera( 0, 0 ) pather = Pathfinder( Grid( utils.buildCollisionMap( map ) ), 'ASTAR', 0 ) pather:setMode( 'ORTHOGONAL' ) doTestPathfind( pather ) math.randomseed( os.time() ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) end function game:mousepressed( x, y, button ) selx, sely = x, y end function game:mousereleased( x, y, button ) selw, selh = x - selx, y - sely local min = 5 -- any selection rect smaller than this will be ignored if math.abs( selw ) < min or math.abs( selh ) < min then return end -- flip if selw < 0 then selw = selx - x selx = x end if selh < 0 then selh = sely - y sely = y end selx, sely = cam:worldCoords( selx, sely ) selection = ux.select( selx, sely, selw, selh, entities, map ) print( table.getn( selection ) ) end function game:draw() cam:attach() -- draw map for y = 1, map.height do for x = 1, map.width do love.graphics.draw( map.tileset, map.tiles[ ( y - 1 ) * map.width + x ], ( x - 1 ) * map.tilewidth, ( y - 1 ) * map.tileheight ) end end -- draw entities for i, entity in ipairs( entities ) do entity.anim:draw( ( entity.x - 1 ) * map.tilewidth, ( entity.y - 1 ) * map.tileheight ) end cam:detach() end function game:update( dt ) -- update camera local margin = 30 local speed = 10 if love.mouse.getX() - margin <= 0 then cam:move( -speed, 0 ) elseif love.mouse.getX() + margin >= 800 then cam:move( speed, 0 ) elseif love.mouse.getY() - margin <= 0 then cam:move( 0, -speed ) elseif love.mouse.getY() + margin >= 600 then cam:move( 0, speed ) end local cx, cy = cam:pos() if cx < 0 then cam:lookAt( 0, cy ) end if cy < 0 then cam:lookAt( cx, 0 ) end if cx > map.tilewidth * map.width then cam:lookAt( map.tilewidth * map.width, cy ) end if cy > map.tileheight * map.height then cam:lookAt( cx, map.tileheight * map.height ) end -- update entity anims for i, entity in ipairs( entities ) do entity.anim:update( dt ) entity:updateAnim( 0, 0 ) end end return game
-- vendor libs require 'vendor/AnAL' local PrettyPrint = require 'vendor/lua-pretty-print/PrettyPrint' local gamestate = require 'vendor/hump/gamestate' local Camera = require 'vendor/hump/camera' local Grid = require 'vendor/Jumper/jumper.grid' local Pathfinder = require 'vendor/Jumper/jumper.pathfinder' -- hack std function math.clamp(x, min, max) if x < min then return min elseif x > max then return max else return x end end -- game modules local utils = require 'utils' local Scv = require 'units/scv' local ux = require 'ux' -- locals local cam = nil local map = nil local game = {} local entities = {} local pather = nil -- selection local selx, sely = 0, 0 local selw, selh = 0, 0 local selection = {} function game:init() end local function doTestPathfind( pather ) local sx, sy = 1, 1 local dx, dy = 1, 3 local path, length = pather:getPath( sx, sy, dx, dy ) if path then for node, count in path:nodes() do print( ('Step: %d - x: %d , y: %d'):format( count, node:getX(), node:getY() ) ) end else print( "no path found!" ) end end function game:enter() -- just the same map every time for now map = utils.buildMap( "art/maps/standard" ) cam = Camera( 0, 0 ) pather = Pathfinder( Grid( utils.buildCollisionMap( map ) ), 'ASTAR', 0 ) pather:setMode( 'ORTHOGONAL' ) doTestPathfind( pather ) math.randomseed( os.time() ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) table.insert( entities, Scv:new( math.random( map.width ), math.random( map.height ) ) ) end function game:mousepressed( x, y, button ) selx, sely = x, y end function game:mousereleased( x, y, button ) selw, selh = x - selx, y - sely local min = 5 -- any selection rect smaller than this will be ignored if math.abs( selw ) < min or math.abs( selh ) < min then return end -- flip if selw < 0 then selw = selx - x selx = x end if selh < 0 then selh = sely - y sely = y end selx, sely = cam:worldCoords( selx, sely ) selection = ux.select( selx, sely, selw, selh, entities, map ) print( table.getn( selection ) ) end function game:draw() cam:attach() -- draw map for y = 1, map.height do for x = 1, map.width do love.graphics.draw( map.tileset, map.tiles[ ( y - 1 ) * map.width + x ], ( x - 1 ) * map.tilewidth, ( y - 1 ) * map.tileheight ) end end -- draw entities for i, entity in ipairs( entities ) do entity.anim:draw( ( entity.x - 1 ) * map.tilewidth, ( entity.y - 1 ) * map.tileheight ) end cam:detach() end function game:update( dt ) -- update camera local margin = 30 local speed = 10 if love.mouse.getX() - margin <= 0 then cam:move( -speed, 0 ) elseif love.mouse.getX() + margin >= 800 then cam:move( speed, 0 ) end if love.mouse.getY() - margin <= 0 then cam:move( 0, -speed ) elseif love.mouse.getY() + margin >= 600 then cam:move( 0, speed ) end -- clamp camera so it doesn't go off map local cx, cy = cam:pos() cx = math.clamp( cx, 400, map.tilewidth * map.width - 400 ) cy = math.clamp( cy, 300, map.tileheight * map.height - 300 ) cam:lookAt( cx, cy ) -- update entity anims for i, entity in ipairs( entities ) do entity.anim:update( dt ) entity:updateAnim( 0, 0 ) end end return game
fix camera pan clamps
fix camera pan clamps
Lua
mit
davidyu/mld50
12852bc9d866f1429a57691aaa1ec77886abe9d9
lualib/sys/json.lua
lualib/sys/json.lua
local next = next local type = type local pcall = pcall local pairs = pairs local ipairs = ipairs local assert = assert local tostring = tostring local tonumber = tonumber local tconcat = table.concat local format = string.format local find = string.find local sub = string.sub local gsub = string.gsub local byte = string.byte local json = {} ---------encode local encode_func local function encodebool(b) return b and "true" or "false" end local function encodenumber(n) return tostring(n) end local function encodestring(s) s = gsub(s, '"', '\\"') return format('"%s"', s) end local function encodeobj(obj) if obj[1] ~= nil or next(obj) == nil then --array local str = {} for _, v in ipairs(obj) do v = encode_func[type(v)](v) str[#str + 1] = v end return format("[%s]", tconcat(str, ",")) else --object local str = {} for k, v in pairs(obj) do v = encode_func[type(v)](v) str[#str + 1] = format("%s:%s", encodestring(k), v) end return format("{%s}", tconcat(str, ",")) end end encode_func = { ['table'] = encodeobj, ['boolean'] = encodebool, ['number'] = encodenumber, ['string'] = encodestring, } ----------decode -- { -> 0x7b , } -> 0x7D, [ -> 0x5B, ] -> 0x5D, : -> 0x3A, " -> 0x22 local decode_func local function skipspace(str, i) return find(str, "[^%s]", i) end local function decodestr(str, i) local _, n = find(str, '[^\\]"', i) local s = sub(str, i + 1, n - 1) return gsub(s, '\\"', '"'), n + 1 end local function decodebool(str, i) local n = find(str, "[%s,}]", i) local k = sub(str, i, n - 1) if k == "true" then return true, n elseif k == "false" then return false, n else assert(false, k) end end local function decodenumber(str, i) local n = find(str, "[%s,}]", i) local k = sub(str, i, n - 1) return tonumber(k), n end local function decodeobj(str, i) local len = #str local obj = {} i = skipspace(str, i) if byte(str, i) ~= 0x7b then -- '{' assert(false, [[need '{']]) end i = i + 1 while true do local k, v i = skipspace(str, i) local ch = byte(str, i) if ch == 0x7D then -- '}' break end if ch ~= 0x22 then -- '"' assert(false, [[need '"']]) end k, i = decodestr(str, i) i = skipspace(str, i) if byte(str, i) ~= 0x3A then assert(false, [[need ':']]) end i = skipspace(str, i + 1) local n = byte(str, i) v, i = assert(decode_func[n], n)(str, i) obj[k] = v i = skipspace(str, i) if byte(str, i) == 0x2C then -- ',' i = i + 1 end end return obj, i + 1 end local function decodearr(str, i) local ai = 0 local arr = {} i = i + 1 while true do i = skipspace(str, i) local ch = byte(str, i) if ch == 0x5D then -- ']' break end ai = ai + 1 arr[ai], i = assert(decode_func[ch], ch)(str, i) i = skipspace(str, i) if byte(str, i) == 0x2C then -- ',' i = i + 1 end end return arr, i + 1 end decode_func = { [0x7b] = decodeobj, [0x5b] = decodearr, [0x22] = decodestr, [0x66] = decodebool, [0x74] = decodebool, } for i = 0x30, 0x39 do decode_func[i] = decodenumber end ---------interface function json.encode(obj) return encodeobj(obj) end function json.decode(str) local ok, obj, i = pcall(decodeobj, str, 1) if not ok then return nil, obj end return obj, i end return json
local next = next local type = type local pcall = pcall local pairs = pairs local ipairs = ipairs local assert = assert local tostring = tostring local tonumber = tonumber local tconcat = table.concat local format = string.format local find = string.find local sub = string.sub local gsub = string.gsub local byte = string.byte local json = {} ---------encode local encode_func local function encodebool(b) return b and "true" or "false" end local function encodenumber(n) return tostring(n) end local escape = { ['"'] = '\\"', ['\\'] = '\\\\', ['/'] = '\\/', } local unescape = {} do for k, v in pairs(escape) do unescape[v] = k end end local function encodestring(s) s = gsub(s, '["\\/]', escape) return format('"%s"', s) end local function encodeobj(obj) if obj[1] ~= nil or next(obj) == nil then --array local str = {} for _, v in ipairs(obj) do v = encode_func[type(v)](v) str[#str + 1] = v end return format("[%s]", tconcat(str, ",")) else --object local str = {} for k, v in pairs(obj) do v = encode_func[type(v)](v) str[#str + 1] = format("%s:%s", encodestring(k), v) end return format("{%s}", tconcat(str, ",")) end end encode_func = { ['table'] = encodeobj, ['boolean'] = encodebool, ['number'] = encodenumber, ['string'] = encodestring, } ----------decode -- { -> 0x7b , } -> 0x7D, [ -> 0x5B, ] -> 0x5D, : -> 0x3A, " -> 0x22 local decode_func local function skipspace(str, i) return find(str, "[^%s]", i) end local function decodestr(str, i) local _, n = find(str, '[^\\]"', i) local s = sub(str, i + 1, n - 1) return gsub(s, '(\\["\\/])', unescape), n + 1 end local function decodebool(str, i) local n = find(str, "[%s,}]", i) local k = sub(str, i, n - 1) if k == "true" then return true, n elseif k == "false" then return false, n else assert(false, k) end end local function decodenumber(str, i) local n = find(str, "[%s,}]", i) local k = sub(str, i, n - 1) return tonumber(k), n end local function decodeobj(str, i) local len = #str local obj = {} i = skipspace(str, i) if byte(str, i) ~= 0x7b then -- '{' assert(false, [[need '{']]) end i = i + 1 while true do local k, v i = skipspace(str, i) local ch = byte(str, i) if ch == 0x7D then -- '}' break end if ch ~= 0x22 then -- '"' assert(false, [[need '"']]) end k, i = decodestr(str, i) i = skipspace(str, i) if byte(str, i) ~= 0x3A then assert(false, [[need ':']]) end i = skipspace(str, i + 1) local n = byte(str, i) v, i = assert(decode_func[n], n)(str, i) obj[k] = v i = skipspace(str, i) if byte(str, i) == 0x2C then -- ',' i = i + 1 end end return obj, i + 1 end local function decodearr(str, i) local ai = 0 local arr = {} i = i + 1 while true do i = skipspace(str, i) local ch = byte(str, i) if ch == 0x5D then -- ']' break end ai = ai + 1 arr[ai], i = assert(decode_func[ch], ch)(str, i) i = skipspace(str, i) if byte(str, i) == 0x2C then -- ',' i = i + 1 end end return arr, i + 1 end decode_func = { [0x7b] = decodeobj, [0x5b] = decodearr, [0x22] = decodestr, [0x66] = decodebool, [0x74] = decodebool, } for i = 0x30, 0x39 do decode_func[i] = decodenumber end ---------interface function json.encode(obj) return encodeobj(obj) end function json.decode(str) local ok, obj, i = pcall(decodeobj, str, 1) if not ok then return nil, obj end return obj, i end return json
bugfix json escape character
bugfix json escape character
Lua
mit
findstr/silly
a1b6bd90ecccc73e2f97cb1f0b9cad0f3b75a1f1
l2l/itertools.lua
l2l/itertools.lua
local function resolve(str, t) local obj = t or _G for name in str:gmatch("[^.]+") do if obj then obj = obj[name] end end return obj end local function pack(...) return {...}, select("#", ...) end local function dict(...) local count = select('#', ...) if count % 2 ~= 0 then error("dict takes an even number of arguments. Received "..tostring(count)) end local t = {} for i=1, count, 2 do t[select(i, ...)] = select(i+1, ...) end return t end local function vector(...) return {...} end local function bind(f, ...) local count = select("#", ...) local parameters = {...} return function(...) local count2 = select("#", ...) local all = {} for i=1, count do all[i] = parameters[i] end for i=1, count2 do all[count + i] = select(i, ...) end return f(table.unpack(all, 1, count + count2)) end end local function show(obj) if type(obj) == "table" and getmetatable(obj) == nil then local t = {} for name, value in pairs(obj) do table.insert(t, show(name)) table.insert(t, show(value)) end return "{" .. table.concat(t, " ") .. "}" elseif type(obj) ~= 'string' then obj = tostring(obj) else obj = '"' .. obj:gsub('"', '\\"'):gsub("\n", "\\n") .. '"' end return obj end local function fold(f, initial, objs) if objs == nil then return end for _, v in ipairs(objs or {}) do initial = f(initial, v) end return initial end local function foreach(f, objs) local orig = {} for i, v in pairs(objs or {}) do orig[i] = f(v, i) end return orig end local list, pair list = setmetatable({ unpack = function(self) if self then return self[1], list.unpack(self[2]) end end, push = function(self, obj, ...) if not ... then return pair({obj, self}) else return list.push(pair({obj, self}), ...) end end, contains = function(self, obj) if not self then return false end for _, v in ipairs(self) do if v == obj then return true end end return false end, concat = function(self, separator) if self == nil then return "" end local str = tostring(self[1]) if self[2] then str = str .. separator .. self[2]:concat(separator) end return str end, __eq = function(self, other) if self == nil and other == nil then return true end if self == nil and other ~= nil or self ~= nil and other == nil then return false end return self[1] == other[1] and self[2] == other[2] end, __ipairs = function(self) local i = 0 return function() if self then local obj = self[1] self = self[2] i = i + 1 return i, obj end end end, __tostring = function(self) local str = "(" repeat str = str .. show(self[1]) self = self[2] if getmetatable(self) == list then str = str .. " " elseif self ~= nil then str = str .. " . " .. tostring(self) end until not self return str .. ")" end }, {__call = function(_, ...) local orig = setmetatable({}, list) local last = orig for i=1, select('#', ...) do last[2] = setmetatable({select(i, ...), nil}, list) last = last[2] end return orig[2] end}) list.__index = list local function id(...) return ... end local function tolist(t) local orig = setmetatable({}, list) local last = orig local maxn = table.maxn or function(tb) return #tb end for i=1, maxn(t) do last[2] = setmetatable({t[i], nil}, list) last = last[2] end return orig[2] end local function zip(...) local parameters = {} local smallest for i=1, select("#", ...) do local collection = select(i, ...) local count = 0 for j, obj in ipairs(collection) do if smallest and j > smallest then break end if i == 1 then parameters[j] = {} end parameters[j][i] = obj count = count + 1 end smallest = math.min(smallest or count, count) end local trimmed = {} for i = 1, smallest do trimmed[i] = parameters[i] end return tolist(trimmed) end pair = function(t) return setmetatable(t, list) end local function cons(a, b) return pair({a, b}) end local function map(f, objs, ...) if objs == nil then return nil end local orig = pair({nil}) local last = orig for i, v in ipairs(objs or {}) do last[2] = pair({f(v), nil}) last=last[2] end return orig[2] end local function each(f, objs, ...) if objs == nil then return nil end local orig = pair({nil}) local last = orig for i, v in ipairs(objs or {}) do last[2] = pair({f(v, i), nil}) last=last[2] end return orig[2] end local function contains(objs, target) for _, v in pairs(objs or {}) do if v == target then return target end end return false end --- Returns array inclusive of start and finish indices. -- 1 is first position. 0 is last position. -1 is second last position. -- @objs iterable to slice. -- @start first index. -- @finish second index local function slice(objs, start, finish) if finish <= 0 then finish = #objs + finish end local orig = {} for i, v in ipairs(objs) do if i >= start and i <= finish then table.insert(orig, v) end end return orig end return { vector=vector, dict=dict, pair=pair, cons=cons, list=list, zip=zip, map=map, fold=fold, show=show, foreach=foreach, pack=pack, resolve=resolve, bind=bind, contains=contains, slice=slice, each=each, tolist=tolist, id=id }
local function resolve(str, t) local obj = t or _G for name in str:gmatch("[^.]+") do if obj then obj = obj[name] end end return obj end local function pack(...) return {...}, select("#", ...) end local function dict(...) local count = select('#', ...) if count % 2 ~= 0 then error("dict takes an even number of arguments. Received "..tostring(count)) end local t = {} for i=1, count, 2 do t[select(i, ...)] = select(i+1, ...) end return t end local function vector(...) return {...} end local function bind(f, ...) local count = select("#", ...) local parameters = {...} return function(...) local count2 = select("#", ...) local all = {} for i=1, count do all[i] = parameters[i] end for i=1, count2 do all[count + i] = select(i, ...) end return f(table.unpack(all, 1, count + count2)) end end local function show(obj) if type(obj) == "table" and getmetatable(obj) == nil then local t = {} for name, value in pairs(obj) do table.insert(t, show(name)) table.insert(t, show(value)) end return "{" .. table.concat(t, " ") .. "}" elseif type(obj) ~= 'string' then obj = tostring(obj) else obj = '"' .. obj:gsub('"', '\\"'):gsub("\n", "\\n") .. '"' end return obj end local function fold(f, initial, objs) if objs == nil then return end for _, v in ipairs(objs or {}) do initial = f(initial, v) end return initial end local function foreach(f, objs) local orig = {} for i, v in pairs(objs or {}) do orig[i] = f(v, i) end return orig end local list, pair list = setmetatable({ unpack = function(self) if self then return self[1], list.unpack(self[2]) end end, push = function(self, obj, ...) if not ... then return pair({obj, self}) else return list.push(pair({obj, self}), ...) end end, contains = function(self, obj) if not self then return false end for _, v in ipairs(self) do if v == obj then return true end end return false end, concat = function(self, separator) if self == nil then return "" end local str = tostring(self[1]) if self[2] then str = str .. separator .. self[2]:concat(separator) end return str end, __eq = function(self, other) if self == nil and other == nil then return true end if self == nil and other ~= nil or self ~= nil and other == nil then return false end return self[1] == other[1] and self[2] == other[2] end, __ipairs = function(self) local i = 0 return function() if self then local obj = self[1] self = self[2] i = i + 1 return i, obj end end end, __tostring = function(self) local str = "(" repeat if getmetatable(self) ~= list then return str..")" end str = str .. show(self[1]) self = self[2] if getmetatable(self) == list then str = str .. " " elseif self ~= nil then str = str .. " . " .. tostring(self) end until not self return str .. ")" end }, {__call = function(_, ...) local orig = setmetatable({}, list) local last = orig for i=1, select('#', ...) do last[2] = setmetatable({select(i, ...), nil}, list) last = last[2] end return orig[2] end}) list.__index = list local function id(...) return ... end local function tolist(t) local orig = setmetatable({}, list) local last = orig local maxn = table.maxn or function(tb) return #tb end for i=1, maxn(t) do last[2] = setmetatable({t[i], nil}, list) last = last[2] end return orig[2] end local function zip(...) local parameters = {} local smallest for i=1, select("#", ...) do local collection = select(i, ...) local count = 0 for j, obj in ipairs(collection) do if smallest and j > smallest then break end if i == 1 then parameters[j] = {} end parameters[j][i] = obj count = count + 1 end smallest = math.min(smallest or count, count) end local trimmed = {} for i = 1, smallest do trimmed[i] = parameters[i] end return tolist(trimmed) end pair = function(t) return setmetatable(t, list) end local function cons(a, b) return pair({a, b}) end local function map(f, objs, ...) if objs == nil then return nil end local orig = pair({nil}) local last = orig for i, v in ipairs(objs or {}) do last[2] = pair({f(v), nil}) last=last[2] end return orig[2] end local function each(f, objs, ...) if objs == nil then return nil end local orig = pair({nil}) local last = orig for i, v in ipairs(objs or {}) do last[2] = pair({f(v, i), nil}) last=last[2] end return orig[2] end local function contains(objs, target) for _, v in pairs(objs or {}) do if v == target then return target end end return false end --- Returns array inclusive of start and finish indices. -- 1 is first position. 0 is last position. -1 is second last position. -- @objs iterable to slice. -- @start first index. -- @finish second index local function slice(objs, start, finish) if finish <= 0 then finish = #objs + finish end local orig = {} for i, v in ipairs(objs) do if i >= start and i <= finish then table.insert(orig, v) end end return orig end return { vector=vector, dict=dict, pair=pair, cons=cons, list=list, zip=zip, map=map, fold=fold, show=show, foreach=foreach, pack=pack, resolve=resolve, bind=bind, contains=contains, slice=slice, each=each, tolist=tolist, id=id }
Fix cons cell in list; __tostring. #19
Fix cons cell in list; __tostring. #19
Lua
bsd-2-clause
tst2005/l2l,meric/l2l,carloscm/l2l
e0dfa6311b27e985c00e2495ccd62ecdd4609ff5
src/characters/vicedean.lua
src/characters/vicedean.lua
local anim8 = require 'vendor/anim8' local plyr = {} plyr.name = 'vicedean' plyr.offset = 5 plyr.ow = 8 plyr.costumes = { {name='Vice Dean Laybourne', sheet='images/vicedean.png'}, {name='Ghost', sheet='images/vicedean_ghost.png'}, {name='Going Through Some Stuff', sheet='images/vicedean_stuff.png'}, } local beam = love.graphics.newImage('images/abed_beam.png') function plyr.new(sheet) local new_plyr = {} new_plyr.sheet = sheet new_plyr.sheet:setFilter('nearest', 'nearest') local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(), new_plyr.sheet:getHeight()) local warp = anim8.newGrid(36, 223, beam:getWidth(), beam:getHeight()) new_plyr.hand_offsets = { { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 6,32},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{12,32},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{10, 7},{ 5, 5},{ 5, 5} }, { { 5, 3},{ 5, 5},{ 5, 3},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { {10, 5},{10, 7},{10, 5},{10, 7},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} }, { { 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5},{ 5, 5} } } new_plyr.beam = beam new_plyr.animations = { dead = { right = anim8.newAnimation('once', g('9,13'), 1), left = anim8.newAnimation('once', g('9,14'), 1) }, hold = { right = anim8.newAnimation('once', g(5,5), 1), left = anim8.newAnimation('once', g(5,6), 1), }, holdwalk = { right = anim8.newAnimation('loop', g('1-3,9', '2,9'), 0.16), left = anim8.newAnimation('loop', g('1-3,10', '2,10'), 0.16), }, crouch = { right = anim8.newAnimation('once', g('9,4'), 1), left = anim8.newAnimation('once', g('9,3'), 1) }, crouchwalk = { --state for walking towards the camera left = anim8.newAnimation('loop', g('2-3,3'), 0.16), right = anim8.newAnimation('loop', g('2-3,3'), 0.16), }, gaze = { right = anim8.newAnimation('once', g(8,2), 1), left = anim8.newAnimation('once', g(8,1), 1), }, gazewalk = { --state for walking away from the camera left = anim8.newAnimation('loop', g('2-3,4'), 0.16), right = anim8.newAnimation('loop', g('2-3,4'), 0.16), }, attack = { left = anim8.newAnimation('loop', g('3-4,6'), 0.16), right = anim8.newAnimation('loop', g('3-4,5'), 0.16), }, attackjump = { left = anim8.newAnimation('loop', g('7-8,3'), 0.16), right = anim8.newAnimation('loop', g('7-8,4'), 0.16), }, attackwalk = { left = anim8.newAnimation('loop', g('1,8','5,8','3,8','5,8'), 0.16), right = anim8.newAnimation('loop', g('1,7','5,7','3,7','5,7'), 0.16), }, jump = { right = anim8.newAnimation('once', g('7,2'), 1), left = anim8.newAnimation('once', g('7,1'), 1) }, walk = { right = anim8.newAnimation('loop', g('2-4,2', '3,2'), 0.16), left = anim8.newAnimation('loop', g('2-4,1', '3,1'), 0.16), }, idle = { right = anim8.newAnimation('once', g(1,2), 1), left = anim8.newAnimation('once', g(1,1), 1), }, warp = anim8.newAnimation('once', warp('1-4,1'), 0.08), } return new_plyr end return plyr
local anim8 = require 'vendor/anim8' local plyr = {} plyr.name = 'vicedean' plyr.offset = 5 plyr.ow = 8 plyr.costumes = { {name='Vice Dean Laybourne', sheet='images/vicedean.png'}, {name='Ghost', sheet='images/vicedean_ghost.png'}, {name='Going Through Some Stuff', sheet='images/vicedean_stuff.png'}, } local beam = love.graphics.newImage('images/abed_beam.png') function plyr.new(sheet) local new_plyr = {} new_plyr.sheet = sheet new_plyr.sheet:setFilter('nearest', 'nearest') local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(), new_plyr.sheet:getHeight()) local warp = anim8.newGrid(36, 223, beam:getWidth(), beam:getHeight()) new_plyr.hand_offsets = { { {11,39},{-12,36},{6,36},{16,34},{11,39},{11,39},{-4,37},{11,39},{ 1,31} }, { {14,39},{-15,34},{14,33},{15,33},{14,39},{14,39},{5,37},{14,39},{16,38} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{13,19},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{10,20},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { {13,19},{13,18},{13,19},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { {10,20},{10,19},{10,20},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} }, { { 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0},{ 0, 0} } } new_plyr.beam = beam new_plyr.animations = { dead = { right = anim8.newAnimation('once', g('9,13'), 1), left = anim8.newAnimation('once', g('9,14'), 1) }, hold = { right = anim8.newAnimation('once', g(5,5), 1), left = anim8.newAnimation('once', g(5,6), 1), }, holdwalk = { right = anim8.newAnimation('loop', g('1-3,9', '2,9'), 0.16), left = anim8.newAnimation('loop', g('1-3,10', '2,10'), 0.16), }, crouch = { right = anim8.newAnimation('once', g('9,4'), 1), left = anim8.newAnimation('once', g('9,3'), 1) }, crouchwalk = { --state for walking towards the camera left = anim8.newAnimation('loop', g('2-3,3'), 0.16), right = anim8.newAnimation('loop', g('2-3,3'), 0.16), }, gaze = { right = anim8.newAnimation('once', g(8,2), 1), left = anim8.newAnimation('once', g(8,1), 1), }, gazewalk = { --state for walking away from the camera left = anim8.newAnimation('loop', g('2-3,4'), 0.16), right = anim8.newAnimation('loop', g('2-3,4'), 0.16), }, attack = { left = anim8.newAnimation('loop', g('3-4,6'), 0.16), right = anim8.newAnimation('loop', g('3-4,5'), 0.16), }, attackjump = { left = anim8.newAnimation('loop', g('7-8,3'), 0.16), right = anim8.newAnimation('loop', g('7-8,4'), 0.16), }, attackwalk = { left = anim8.newAnimation('loop', g('1,8','5,8','3,8','5,8'), 0.16), right = anim8.newAnimation('loop', g('1,7','5,7','3,7','5,7'), 0.16), }, jump = { right = anim8.newAnimation('once', g('7,2'), 1), left = anim8.newAnimation('once', g('7,1'), 1) }, walk = { right = anim8.newAnimation('loop', g('2-4,2', '3,2'), 0.16), left = anim8.newAnimation('loop', g('2-4,1', '3,1'), 0.16), }, idle = { right = anim8.newAnimation('once', g(1,2), 1), left = anim8.newAnimation('once', g(1,1), 1), }, warp = anim8.newAnimation('once', warp('1-4,1'), 0.08), } return new_plyr end return plyr
Fixes #166. Vicedean. That's everyone!
Fixes #166. Vicedean. That's everyone!
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
b8ef36445fb4ab2598c1159906990fbf516e2dfc
mod-mpv/config/images/fancy_zoom.lua
mod-mpv/config/images/fancy_zoom.lua
local rotation = 0 local rendering = false local user_fiddled = false math.sign = math.sign or function(x) return x<0 and -1 or x>0 and 1 or 0 end function get(property) return mp.get_property(property) end function set(property, value) mp.set_property(property, value) end function add(property, delta) set(property, get(property) + delta) end function add_rotation(delta) rotation = rotation + delta rotation = rotation + 360 rotation = rotation % 360 if rotation == 0 then mp.command('vf set ""') else mp.command('vf set rotate=' .. rotation) end end function get_real_scale() local video = { width = get('video-params/dw'), height = get('video-params/dh'), } local window = { width = get('osd-width'), height = get('osd-height'), } if video.width == nil or window.width == nil then return nil end video.width = tonumber(video.width) video.height = tonumber(video.height) window.width = tonumber(window.width) window.height = tonumber(window.height) if window.width / window.height < video.width / video.height then return window.width / video.width else return window.height / video.height end end function reset_other_settings() set('video-pan-x', 0) set('video-pan-y', 0) set('video-aspect', 0) end function correct_pan_for_dimension(dimension, delta) value = tonumber(get('video-pan-' .. dimension)) if dimension == 'x' then window_size = tonumber(get('osd-width')) video_size = tonumber(get('video-params/dw')) else window_size = tonumber(get('osd-height')) video_size = tonumber(get('video-params/dh')) end window_scale = get_real_scale() zoom_scale = tonumber(get('video-zoom')) + 1 -- what a bunch of crap actual_canvas_size = video_size * window_scale * zoom_scale if actual_canvas_size < window_size then set('video-pan-' .. dimension, 0) elseif (1 - math.abs(value) * 2) * actual_canvas_size < window_size then value = math.sign(value) * (-(window_size / actual_canvas_size - 1) / 2) set('video-pan-' .. dimension, value) end end function correct_pan() correct_pan_for_dimension('x', 0) correct_pan_for_dimension('y', 0) end function scale_original() local window_scale = get_real_scale() if window_scale == nil then return end local target_scale = (1 / window_scale) - 1 reset_other_settings() set('video-zoom', target_scale) correct_pan() end function scale_arbitrary(multiplier) local window_scale = get_real_scale() if window_scale == nil then return end local target_scale = ((1 / window_scale * multiplier) - 1) reset_other_settings() set('video-zoom', target_scale) correct_pan() end function scale_to_window() reset_other_settings() set('video-zoom', 0) correct_pan() end function fit_to_window() local window_scale = get_real_scale() if window_scale == nil then return end if window_scale > 1 then scale_original() else scale_to_window() end end function file_changed() user_fiddled = false rendering = true end function file_rendered() -- https://github.com/mpv-player/mpv/pull/2936 if rendering then rendering = false fit_to_window() end end function window_size_changed() if not rendering and not user_fiddled then fit_to_window() end end mp.add_hook('on_prerender', 50, file_rendered) mp.observe_property('osd-width', int, window_size_changed) mp.register_event('file-loaded', file_changed) mp.register_event('video-reconfig', window_size_changed) mp.register_script_message('fit-to-window', function() fit_to_window(); user_fiddled = true; end) mp.register_script_message('fit-original', function() scale_original(); user_fiddled = true; end) mp.register_script_message('set-zoom', function(v) scale_arbitrary(v); user_fiddled = true; end) mp.register_script_message('zoom-out', function(d) add('video-zoom', -d); correct_pan(); user_fiddled = true; end) mp.register_script_message('zoom-in', function(d) add('video-zoom', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('pan-x', function(d) add('video-pan-x', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('pan-y', function(d) add('video-pan-y', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('aspect', function(d) add('video-aspect', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('rotate', function(d) add_rotation(d); user_fiddled = true; end)
local rotation = 0 local rendering = false local user_fiddled = false math.sign = math.sign or function(x) return x<0 and -1 or x>0 and 1 or 0 end function add_property(property, delta) mp.set_property_number(property, mp.get_property_number(property) + delta) end function add_rotation(delta) rotation = rotation + delta rotation = rotation + 360 rotation = rotation % 360 if rotation == 0 then mp.command('vf set ""') else mp.command('vf set rotate=' .. rotation) end end function get_real_scale() local video = { width = mp.get_property_number('video-params/dw', nil), height = mp.get_property_number('video-params/dh', nil), } local window = { width = mp.get_property_number('osd-width', nil), height = mp.get_property_number('osd-height', nil), } if video.width == nil or window.width == nil then return nil end if window.width / window.height < video.width / video.height then return window.width / video.width else return window.height / video.height end end function reset_other_settings() mp.set_property_number('video-pan-x', 0) mp.set_property_number('video-pan-y', 0) mp.set_property_number('video-aspect', 0) end function correct_pan_for_dimension(dimension, delta) value = mp.get_property_number('video-pan-' .. dimension) if dimension == 'x' then window_size = mp.get_property_number('osd-width', nil) video_size = mp.get_property_number('video-params/dw', nil) else window_size = mp.get_property_number('osd-height', nil) video_size = mp.get_property_number('video-params/dh', nil) end window_scale = get_real_scale() zoom_scale = mp.get_property_number('video-zoom') + 1 if window_size == nil or video_size == nil or window_scale == nil then return end -- what a bunch of crap actual_canvas_size = video_size * window_scale * zoom_scale if actual_canvas_size < window_size then mp.set_property_number('video-pan-' .. dimension, 0) elseif (1 - math.abs(value) * 2) * actual_canvas_size < window_size then value = math.sign(value) * (-(window_size / actual_canvas_size - 1) / 2) mp.set_property_number('video-pan-' .. dimension, value) end end function correct_pan() correct_pan_for_dimension('x', 0) correct_pan_for_dimension('y', 0) end function scale_original() local window_scale = get_real_scale() if window_scale == nil then return end local target_scale = (1 / window_scale) - 1 reset_other_settings() mp.set_property_number('video-zoom', target_scale) correct_pan() end function scale_arbitrary(multiplier) local window_scale = get_real_scale() if window_scale == nil then return end local target_scale = ((1 / window_scale * multiplier) - 1) reset_other_settings() mp.set_property_number('video-zoom', target_scale) correct_pan() end function scale_to_window() reset_other_settings() mp.set_property_number('video-zoom', 0) correct_pan() end function fit_to_window() local window_scale = get_real_scale() if window_scale == nil then return end if window_scale > 1 then scale_original() else scale_to_window() end end function file_changed() user_fiddled = false rendering = true end function file_rendered() -- https://github.com/mpv-player/mpv/pull/2936 if rendering then rendering = false fit_to_window() end end function window_size_changed() if not rendering and not user_fiddled then fit_to_window() end end mp.add_hook('on_prerender', 50, file_rendered) mp.observe_property('osd-width', int, window_size_changed) mp.register_event('file-loaded', file_changed) mp.register_event('video-reconfig', window_size_changed) mp.register_script_message('fit-to-window', function() fit_to_window(); user_fiddled = true; end) mp.register_script_message('fit-original', function() scale_original(); user_fiddled = true; end) mp.register_script_message('set-zoom', function(v) scale_arbitrary(v); user_fiddled = true; end) mp.register_script_message('zoom-out', function(d) add_property('video-zoom', -d); correct_pan(); user_fiddled = true; end) mp.register_script_message('zoom-in', function(d) add_property('video-zoom', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('pan-x', function(d) add_property('video-pan-x', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('pan-y', function(d) add_property('video-pan-y', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('aspect', function(d) add_property('video-aspect', d); correct_pan(); user_fiddled = true; end) mp.register_script_message('rotate', function(d) add_rotation(d); user_fiddled = true; end)
mod-mpv: fix fancy zoom breaking on certain files
mod-mpv: fix fancy zoom breaking on certain files
Lua
mit
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
a3f8d058ecc0e1653d9c4d6a27c39e4759a80fa1
build/scripts/common.lua
build/scripts/common.lua
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then defines "NAZARA_PLATFORM_x64" libdirs "../extlibs/lib/x64" else libdirs "../extlibs/lib/x86" end targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE", "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } -- Activation du SSE ct GCC configuration { "Release*", "codeblocks or codelite or gmake or xcode3*" } buildoptions "-mfpmath=sse" configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions "-std=c++11" if (_OPTIONS["x64"]) then buildoptions "-m64" end configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden" configuration {} -- Fin du filtre
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then defines "NAZARA_PLATFORM_x64" libdirs "../extlibs/lib/x64" else libdirs "../extlibs/lib/x86" end targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE", "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } -- Activation du SSE ct GCC configuration { "Release*", "codeblocks or codelite or gmake or xcode3*" } buildoptions "-mfpmath=sse" configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions "-std=c++11" if (_OPTIONS["x64"]) then buildoptions "-m64" end configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden" configuration "vs*" defines "_CRT_SECURE_NO_WARNINGS" configuration {} -- Fin du filtre
Fixed some warnings with Visual Studio
Fixed some warnings with Visual Studio Former-commit-id: e783a55f47e9cfd8a08eced14d19e5eb03b864d8
Lua
mit
DigitalPulseSoftware/NazaraEngine
4dd0a7f0ce3f7590e2b1aa0aff7ea50af4c0f6ec
src/plugins/finalcutpro/inspector/show.lua
src/plugins/finalcutpro/inspector/show.lua
--- === plugins.finalcutpro.inspector.show === --- --- Final Cut Pro Inspector Additions. local require = require local log = require "hs.logger".new "inspShow" local fcp = require "cp.apple.finalcutpro" local go = require "cp.rx.go" local i18n = require "cp.i18n" local Do = go.Do local WaitUntil = go.WaitUntil local plugin = { id = "finalcutpro.inspector.show", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Setup Commands: -------------------------------------------------------------------------------- deps.fcpxCmds :add("goToAudioInspector") :whenActivated(function() fcp:inspector():audio():show() end) :titled(i18n("goTo") .. " " .. i18n("audio") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToInfoInspector") :whenActivated(function() fcp:inspector():info():show() end) :titled(i18n("goTo") .. " " .. i18n("info") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTitleInspector") :whenActivated(function() fcp:inspector():title():show() end) :titled(i18n("goTo") .. " " .. i18n("title") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTextInspector") :whenActivated(function() fcp:inspector():text():show() end) :titled(i18n("goTo") .. " " .. i18n("text") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToVideoInspector") :whenActivated(function() fcp:inspector():video():show() end) :titled(i18n("goTo") .. " " .. i18n("video") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToGeneratorInspector") :whenActivated(function() fcp:inspector():generator():show() end) :titled(i18n("goTo") .. " " .. i18n("generator") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToShareInspector") :whenActivated(function() fcp:inspector():share():show() end) :titled(i18n("goTo") .. " " .. i18n("share") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTransitionInspector") :whenActivated(function() fcp:inspector():transition():show() end) :titled(i18n("goTo") .. " " .. i18n("transition") .. " " .. i18n("inspector")) deps.fcpxCmds :add("modifyProject") :whenActivated(function() Do(fcp:inspector():projectInfo():doShow()) :Then(fcp:inspector():projectInfo():modify():doPress()) :Label("plugins.finalcutpro.inspector.show.modifyProject") :Now() end) :titled(i18n("modifyProject")) end return plugin
--- === plugins.finalcutpro.inspector.show === --- --- Final Cut Pro Inspector Additions. local require = require --local log = require "hs.logger".new "inspShow" local fcp = require "cp.apple.finalcutpro" local go = require "cp.rx.go" local i18n = require "cp.i18n" local Do = go.Do local plugin = { id = "finalcutpro.inspector.show", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Setup Commands: -------------------------------------------------------------------------------- deps.fcpxCmds :add("goToAudioInspector") :whenActivated(function() fcp:inspector():audio():show() end) :titled(i18n("goTo") .. " " .. i18n("audio") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToInfoInspector") :whenActivated(function() fcp:inspector():info():show() end) :titled(i18n("goTo") .. " " .. i18n("info") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTitleInspector") :whenActivated(function() fcp:inspector():title():show() end) :titled(i18n("goTo") .. " " .. i18n("title") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTextInspector") :whenActivated(function() fcp:inspector():text():show() end) :titled(i18n("goTo") .. " " .. i18n("text") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToVideoInspector") :whenActivated(function() fcp:inspector():video():show() end) :titled(i18n("goTo") .. " " .. i18n("video") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToGeneratorInspector") :whenActivated(function() fcp:inspector():generator():show() end) :titled(i18n("goTo") .. " " .. i18n("generator") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToShareInspector") :whenActivated(function() fcp:inspector():share():show() end) :titled(i18n("goTo") .. " " .. i18n("share") .. " " .. i18n("inspector")) deps.fcpxCmds :add("goToTransitionInspector") :whenActivated(function() fcp:inspector():transition():show() end) :titled(i18n("goTo") .. " " .. i18n("transition") .. " " .. i18n("inspector")) deps.fcpxCmds :add("modifyProject") :whenActivated(function() Do(fcp:inspector():projectInfo():doShow()) :Then(fcp:inspector():projectInfo():modify():doPress()) :Label("plugins.finalcutpro.inspector.show.modifyProject") :Now() end) :titled(i18n("modifyProject")) end return plugin
#1826
#1826 - Fixed @stickler-ci bugs
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
bd7c8b558d61e6fde43aeb1202a61dc510915091
vi_quickfix.lua
vi_quickfix.lua
-- Implement quickfix-like functionality. local M = {} local lpeg = require('lpeg') local P = lpeg.P local S = lpeg.S local C = lpeg.C local R = lpeg.R local Ct = lpeg.Ct local Cg = lpeg.Cg local Cc = lpeg.Cc local errpat_newdir = Ct(P"make: Entering directory `" * Cg((P(1) - P"'")^0, 'newdir')* P"'") local errpat_leavedir = Ct(P"make: Leaving directory `" * Cg((P(1) - P"'")^0, 'leavedir')* P"'") local errpat_error = Ct((P"In file included from " ^-1) * Cg((P(1) - S":\n") ^ 0, 'path') * P":" * Cg(R"09" ^ 0, 'lineno') * P":" * (S(" \t") ^ 0) * Cg((1 - P"\n") ^ 0, "message")) local errpat_ignore = (P(1) - "\n") ^ 0 local errpat_line = (errpat_newdir + errpat_error)-- + errpat_ignore) local function pretty(x) if type(x) == 'table' then local bits = {'{\n'} for k,v in pairs(x) do bits[#bits+1] = " " bits[#bits+1] = pretty(k) bits[#bits+1] = " = " bits[#bits+1] = pretty(v) bits[#bits+1] = "\n" end bits[#bits+1] = '}\n' return table.concat(bits) elseif type(x) == 'string' then return "'" .. x .. "'" else return tostring(x) end end local function ts(...) local args = {...} local bits = {} for i,v in ipairs(args) do bits[#bits + 1] = pretty(v) bits[#bits + 1] = "," end return table.concat(bits) end function M.quickfix_from_buffer(buffer) local dirs = {} local results = {} for i=0,buffer.line_count-1 do local line = buffer:get_line(i) line = line:match("([^\n]*)") local match = errpat_line:match(line) if match then if match.newdir then dirs[#dirs+1] = match.newdir elseif match.leavedir then if dirs[#dirs] ~= match.leavedir then error("Non-matching leave directory") else dirs[#dirs] = nil end elseif match.path then local path = match.path local lineno = tonumber(match.lineno) local message = match.message if #dirs > 0 then path = dirs[#dirs] .. "/" .. path end local idx = #results + 1 results[idx] = { line, path=path, lineno=lineno, idx=idx, message=message } end end --cme_log("<"..buffer:get_line(i)..">") --cme_log("{"..ts(errpat_newdir:match((buffer:get_line(i)))).."}") --cme_log(ts(errpat_line:match((buffer:get_line(i))))) end return results end return M
-- Implement quickfix-like functionality. local M = {} local lpeg = require('lpeg') local P = lpeg.P local S = lpeg.S local C = lpeg.C local R = lpeg.R local Ct = lpeg.Ct local Cg = lpeg.Cg local Cc = lpeg.Cc local ws = S" \t" local to_nl = (P(1) - P"\n") ^ 0 local errpat_newdir = Ct(P"make: Entering directory `" * Cg((P(1) - P"'")^0, 'newdir')* P"'") local errpat_leavedir = Ct(P"make: Leaving directory `" * Cg((P(1) - P"'")^0, 'leavedir')* P"'") local errpat_error = Ct((P"In file included from " ^-1) * Cg((P(1) - S":\n") ^ 0, 'path') * P":" * Cg(R"09" ^ 0, 'lineno') * P":" * (S(" \t") ^ 0) * Cg(to_nl, "message")) local errpat_error_nofile = Ct((P"error" + P"Error" + P"ERROR") * P":" * ws * Cg(to_nl, "message")) + Ct(Cg(P"make: ***" * to_nl, "message")) local errpat_ignore = (P(1) - "\n") ^ 0 local errpat_line = (errpat_newdir + errpat_error + errpat_error_nofile)-- + errpat_ignore) local function pretty(x) if type(x) == 'table' then local bits = {'{\n'} for k,v in pairs(x) do bits[#bits+1] = " " bits[#bits+1] = pretty(k) bits[#bits+1] = " = " bits[#bits+1] = pretty(v) bits[#bits+1] = "\n" end bits[#bits+1] = '}\n' return table.concat(bits) elseif type(x) == 'string' then return "'" .. x .. "'" else return tostring(x) end end local function ts(...) local args = {...} local bits = {} for i,v in ipairs(args) do bits[#bits + 1] = pretty(v) bits[#bits + 1] = "," end return table.concat(bits) end function M.quickfix_from_buffer(buffer) local dirs = {} local results = {} for i=0,buffer.line_count-1 do local line = buffer:get_line(i) line = line:match("([^\n]*)") local match = errpat_line:match(line) if match then if match.newdir then dirs[#dirs+1] = match.newdir elseif match.leavedir then if dirs[#dirs] ~= match.leavedir then error("Non-matching leave directory") else dirs[#dirs] = nil end elseif match.path or match.message then local path = match.path local lineno = match.lineno and tonumber(match.lineno) or nil local message = match.message if path and #dirs > 0 then path = dirs[#dirs] .. "/" .. path end local idx = #results + 1 results[idx] = { line, path=path, lineno=lineno, idx=idx, message=message } end end --cme_log("<"..buffer:get_line(i)..">") --cme_log("{"..ts(errpat_newdir:match((buffer:get_line(i)))).."}") --cme_log(ts(errpat_line:match((buffer:get_line(i))))) end return results end return M
Improve error matching in quickfix (for errors without a filename).
Improve error matching in quickfix (for errors without a filename).
Lua
mit
jugglerchris/textadept-vi,erig0/textadept-vi,jugglerchris/textadept-vi
6b2c98f38fcf9be11c71a764a28c9289e94bcc89
lua/testdriver.lua
lua/testdriver.lua
require 'libinjection' require 'Test.More' require 'Test.Builder.Tester' function trim(s) return s:find'^%s*$' and '' or s:match'^%s*(.*%S)' end function print_token_string(tok) local out = '' if tok.str_open ~= '\0' then out = out .. tok.str_open end out = out .. tok.val if tok.str_close ~= '\0' then out = out .. tok.str_close end return trim(out) end function print_token(tok) local out = '' out = out .. tok.type out = out .. ' ' if tok.type == 's' then out = out .. print_token_string(tok) elseif tok.type == 'v' then if tok.count == 1 then out = out .. '@' elseif tok.count == 2 then out = out .. '@@' end out = out .. print_token_string(tok) else out = out .. tok.val end return '\n' .. trim(out) end function test_tokens(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI) while (libinjection.sqli_tokenize(sql_state) == 1) do out = out .. print_token(sql_state.current) end return out end function test_tokens_mysql(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_MYSQL) while (libinjection.sqli_tokenize(sql_state) == 1) do out = out .. print_token(sql_state.current) end return out end function test_folding(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), 0) libinjection.sqli_fingerprint(sql_state, libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI) for i = 1, sql_state.fingerprint:len() do out = out .. print_token(libinjection.sqli_get_token(sql_state, i)) end -- hack for when there is no output if out == '' then out = '\n' end return out end function test_fingerprints(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), 0) local issqli = libinjection.is_sqli(sql_state) if issqli == 1 then out = sql_state.fingerprint end return out end
require 'libinjection' require 'Test.More' require 'Test.Builder.Tester' function trim(s) return s:find'^%s*$' and '' or s:match'^%s*(.*%S)' end function print_token_string(tok) local out = '' if tok.str_open ~= '\0' then out = out .. tok.str_open end out = out .. tok.val if tok.str_close ~= '\0' then out = out .. tok.str_close end return trim(out) end function print_token(tok) local out = '' out = out .. tok.type out = out .. ' ' if tok.type == 's' then out = out .. print_token_string(tok) elseif tok.type == 'v' then if tok.count == 1 then out = out .. '@' elseif tok.count == 2 then out = out .. '@@' end out = out .. print_token_string(tok) else out = out .. tok.val end return '\n' .. trim(out) end function test_tokens(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI) while (libinjection.sqli_tokenize(sql_state) == 1) do out = out .. print_token(sql_state.current) end return out end function test_tokens_mysql(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_MYSQL) while (libinjection.sqli_tokenize(sql_state) == 1) do out = out .. print_token(sql_state.current) end return out end function test_folding(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), 0) libinjection.sqli_fingerprint(sql_state, libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI) for i = 1, sql_state.fingerprint:len() do -- c array is still 0 based out = out .. print_token(libinjection.sqli_get_token(sql_state, i-1)) end -- hack for when there is no output if out == '' then out = '\n' end return out end function test_fingerprints(input) local out = '' local sql_state = libinjection.sqli_state() libinjection.sqli_init(sql_state, input, input:len(), 0) local issqli = libinjection.is_sqli(sql_state) if issqli == 1 then out = sql_state.fingerprint end return out end
fix lua testdriver
fix lua testdriver
Lua
bsd-3-clause
dijkstracula/libinjection,ppliu1979/libinjection,dijkstracula/libinjection,fengjian/libinjection,fengjian/libinjection,ppliu1979/libinjection,ppliu1979/libinjection,dijkstracula/libinjection,fengjian/libinjection,ppliu1979/libinjection,dijkstracula/libinjection,dijkstracula/libinjection,fengjian/libinjection,fengjian/libinjection,ppliu1979/libinjection,fengjian/libinjection,dijkstracula/libinjection,ppliu1979/libinjection,fengjian/libinjection
c1d3ba9aa61b8f09f2c0e5576d4ece65330657d9
mod_storage_gdbm/mod_storage_gdbm.lua
mod_storage_gdbm/mod_storage_gdbm.lua
-- mod_storage_gdbm -- Copyright (C) 2014-2015 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- Depends on lgdbm: -- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm local gdbm = require"gdbm"; local path = require"util.paths"; local lfs = require"lfs"; local st = require"util.stanza"; local uuid = require"util.uuid".generate; local serialization = require"util.serialization"; local serialize = serialization.serialize; local deserialize = serialization.deserialize; local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete; local g_first, g_next = gdbm.firstkey, gdbm.nextkey; local t_remove = table.remove; local empty = {}; local function id(v) return v; end local function is_stanza(s) return getmetatable(s) == st.stanza_mt; end local function t(c, a, b) if c then return a; end return b; end local base_path = path.resolve_relative_path(prosody.paths.data, module.host); lfs.mkdir(base_path); local cache = {}; local keyval = {}; local keyval_mt = { __index = keyval, suffix = ".db" }; function keyval:set(user, value) if type(value) == "table" and next(value) == nil then value = nil; end if value ~= nil then value = serialize(value); end local ok, err = (value and g_set or g_del)(self._db, user or "@", value); if not ok then return nil, err; end return true; end function keyval:get(user) local data, err = g_get(self._db, user or "@"); if not data then return nil, err; end return deserialize(data); end local archive = {}; local archive_mt = { __index = archive, suffix = ".adb" }; archive.get = keyval.get; archive.set = keyval.set; function archive:append(username, key, when, with, value) key = key or uuid(); local meta = self:get(username); if not meta then meta = {}; end local i = meta[key] or #meta+1; local type; if is_stanza(value) then type, value = "stanza", st.preserialize(value); end meta[i] = { key = key, when = when, with = with, type = type }; meta[key] = i; local ok, err = self:set(key, value); if not ok then return nil, err; end ok, err = self:set(username, meta); if not ok then return nil, err; end return key; end local deserialize = { stanza = st.deserialize; }; function archive:find(username, query) query = query or empty_query; local meta = self:get(username) or empty; local r = query.reverse; local d = t(r, -1, 1); local s = meta[t(r, query.before, query.after)]; local limit = query.limit; if s then s = s + d; else s = t(r, #meta, 1) end local e = t(r, 1, #meta); local c = 0; return function () if limit and c >= limit then return end local item, value; for i = s, e, d do item = meta[i]; if (not query.with or item.with == query.with) and (not query.start or item.when >= query.start) and (not query["end"] or item.when <= query["end"]) then s = i + d; c = c + 1; value = self:get(item.key); return item.key, (deserialize[item.type] or id)(value), item.when, item.with; end end end end local drivers = { keyval = keyval_mt; archive = archive_mt; } function open(_, store, typ) typ = typ or "keyval"; local driver_mt = drivers[typ]; if not driver_mt then return nil, "unsupported-store"; end local db_path = path.join(base_path, store) .. driver_mt.suffix; local db = cache[db_path]; if not db then db = assert(gdbm.open(db_path, "c")); cache[db_path] = db; end return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt); end function module.unload() for path, db in pairs(cache) do gdbm.sync(db); gdbm.close(db); end end module:provides"storage";
-- mod_storage_gdbm -- Copyright (C) 2014-2015 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- Depends on lgdbm: -- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm local gdbm = require"gdbm"; local path = require"util.paths"; local lfs = require"lfs"; local st = require"util.stanza"; local uuid = require"util.uuid".generate; local serialization = require"util.serialization"; local serialize = serialization.serialize; local deserialize = serialization.deserialize; local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete; local g_first, g_next = gdbm.firstkey, gdbm.nextkey; local t_remove = table.remove; local empty = {}; local function id(v) return v; end local function is_stanza(s) return getmetatable(s) == st.stanza_mt; end local function t(c, a, b) if c then return a; end return b; end local base_path = path.resolve_relative_path(prosody.paths.data, module.host); lfs.mkdir(base_path); local cache = {}; local keyval = {}; local keyval_mt = { __index = keyval, suffix = ".db" }; function keyval:set(user, value) if type(value) == "table" and next(value) == nil then value = nil; end if value ~= nil then value = serialize(value); end local ok, err = (value and g_set or g_del)(self._db, user or "@", value); if not ok then return nil, err; end return true; end function keyval:get(user) local data, err = g_get(self._db, user or "@"); if not data then return nil, err; end return deserialize(data); end local archive = {}; local archive_mt = { __index = archive, suffix = ".adb" }; archive.get = keyval.get; archive.set = keyval.set; function archive:append(username, key, when, with, value) key = key or uuid(); local meta = self:get(username); if not meta then meta = {}; end local i = meta[key] or #meta+1; local type; if is_stanza(value) then type, value = "stanza", st.preserialize(value); end meta[i] = { key = key, when = when, with = with, type = type }; meta[key] = i; local prefix = (username or "@") .. "#"; local ok, err = self:set(prefix..key, value); if not ok then return nil, err; end ok, err = self:set(username, meta); if not ok then return nil, err; end return key; end local deserialize = { stanza = st.deserialize; }; function archive:find(username, query) query = query or empty_query; local meta = self:get(username) or empty; local prefix = (username or "@") .. "#"; local r = query.reverse; local d = t(r, -1, 1); local s = meta[t(r, query.before, query.after)]; local limit = query.limit; if s then s = s + d; else s = t(r, #meta, 1) end local e = t(r, 1, #meta); local c = 0; return function () if limit and c >= limit then return end local item, value; for i = s, e, d do item = meta[i]; if (not query.with or item.with == query.with) and (not query.start or item.when >= query.start) and (not query["end"] or item.when <= query["end"]) then s = i + d; c = c + 1; value = self:get(prefix..item.key); return item.key, (deserialize[item.type] or id)(value), item.when, item.with; end end end end local drivers = { keyval = keyval_mt; archive = archive_mt; } function open(_, store, typ) typ = typ or "keyval"; local driver_mt = drivers[typ]; if not driver_mt then return nil, "unsupported-store"; end local db_path = path.join(base_path, store) .. driver_mt.suffix; local db = cache[db_path]; if not db then db = assert(gdbm.open(db_path, "c")); cache[db_path] = db; end return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt); end function module.unload() for path, db in pairs(cache) do gdbm.sync(db); gdbm.close(db); end end module:provides"storage";
mod_storage_gdbm: Prefix archive item keys with username to prevent collisions
mod_storage_gdbm: Prefix archive item keys with username to prevent collisions
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
39ee0911ccfd4dfc288cc42cdf53e205ab8e69ca
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.model.uci") require("luci.sys") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface:value(section[".name"]) s:depends("interface", section[".name"]) end end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true s:option(Flag, "dynamicdhcp").rmempty = true s:option(Value, "name", translate("name")).optional = true s:option(Flag, "ignore").optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do k, v = line:match("([^ ]+) +([^ ]+)") s:option(Value, "dhcp"..k, v).optional = true end m2 = Map("luci_ethers", translate("luci_ethers")) s = m2:section(TypedSection, "static_lease", "") s.addremove = true s.anonymous = true s.template = "cbi/tblsection" s:option(Value, "macaddr", translate("macaddress")) s:option(Value, "ipaddr", translate("ipaddress")) return m, m2
--[[ 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.model.uci") require("luci.sys") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] iface:value(section[".name"]) s:depends("interface", section[".name"]) end end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true s:option(Flag, "dynamicdhcp").rmempty = true s:option(Value, "name", translate("name")).optional = true s:option(Flag, "ignore").optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do k, v = line:match("([^ ]+) +([^ ]+)") s:option(Value, "dhcp"..k, v).optional = true end m2 = Map("luci_ethers", translate("luci_ethers")) s = m2:section(TypedSection, "static_lease", "") s.addremove = true s.anonymous = true s.template = "cbi/tblsection" s:option(Value, "macaddr", translate("macaddress")) s:option(Value, "ipaddr", translate("ipaddress")) return m, m2
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page
Lua
apache-2.0
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
dfdf3c055d5dc09c7df65408f2a00f2653a3a83c
item/id_61_goldcoins.lua
item/id_61_goldcoins.lua
-- I_61.lua Goldm&uuml;nzen einschmelzen -- UPDATE common SET com_script='item.id_61_goldcoins' WHERE com_itemid IN (61); require("base.common") module("item.id_61_goldcoins", package.seeall) if not InitTime then InitTime=true; TimeList = {}; end function UseItem(User, SourceItem) if ( SourceItem.number == 1 ) then --works only with 1 coin if TimeList[User.id]~=nil then if ( (math.abs(world:getTime("second") - TimeList[User.id]) ) <=3) then --1 Rl. second delay return; end end TimeList[User.id] = world:getTime("second"); if math.random(2) == 1 then gValue = "Kopf"; eValue = "head"; else gValue = "Zahl"; eValue = "tail"; end User:talk(Character.say, "#me wirft eine Mnze in die Luft und fngt sie wieder auf. Sie zeigt "..gValue..".", "#me throws a coin in the air and catches it again. It shows "..eValue..".") end if (User:isAdmin()) then world:createItemFromId(10, 1 ,position (240,732,0),false, 0, 0); world:createItemFromId(10, 1 ,position (240,722,0),false, 0, 0); world:createItemFromId(10, 1 ,position (250,732,0),false, 0, 0); world:createItemFromId(10, 1 ,position (250,722,0),false, 0, 0); User:inform("portale stehen nahe 240,732,0 rum"); world:createItemFromId(434, 1 ,position (220,735,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,737,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,739,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,741,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,743,0),false, 333, 333); world:createItemFromId(434, 1 ,position (33,20,0),false, 333, 333); --elevator test world:createItemFromId(434, 1 ,position (33,10,0),false, 333, 333); User:inform("hebel stehen nahe 220,735,0 rum"); end end
-- I_61.lua Goldm&uuml;nzen einschmelzen -- UPDATE common SET com_script='item.id_61_goldcoins' WHERE com_itemid IN (61); require("base.common") module("item.id_61_goldcoins", package.seeall) if not InitTime then InitTime=true; TimeList = {}; end function UseItem(User, SourceItem) if TimeList[User.id]~=nil then if ( (math.abs(world:getTime("second") - TimeList[User.id]) ) <=3) then --1 Rl. second delay return; end end TimeList[User.id] = world:getTime("second"); if math.random(2) == 1 then gValue = "Kopf"; eValue = "head"; else gValue = "Zahl"; eValue = "tail"; end User:talk(Character.say, "#me wirft eine Mnze in die Luft und fngt sie wieder auf. Sie zeigt "..gValue..".", "#me throws a coin in the air and catches it again. It shows "..eValue..".") if (User:isAdmin()) then world:createItemFromId(10, 1 ,position (240,732,0),false, 0, 0); world:createItemFromId(10, 1 ,position (240,722,0),false, 0, 0); world:createItemFromId(10, 1 ,position (250,732,0),false, 0, 0); world:createItemFromId(10, 1 ,position (250,722,0),false, 0, 0); User:inform("portale stehen nahe 240,732,0 rum"); world:createItemFromId(434, 1 ,position (220,735,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,737,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,739,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,741,0),false, 333, 333); world:createItemFromId(434, 1 ,position (220,743,0),false, 333, 333); world:createItemFromId(434, 1 ,position (33,20,0),false, 333, 333); --elevator test world:createItemFromId(434, 1 ,position (33,10,0),false, 333, 333); User:inform("hebel stehen nahe 220,735,0 rum"); end end
bugfix
bugfix
Lua
agpl-3.0
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
a614e4867e0e118973ed6a01f62e8727926a640a
tools/torch/LRPolicy.lua
tools/torch/LRPolicy.lua
-- Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. local LRPolicy = torch.class('LRPolicy') ---------------------------------------------------------------------------------------- -- This file contains details of learning rate policies that are used in caffe. -- Calculates and returns the current learning rate. The currently implemented learning rate -- policies are as follows: -- - fixed: always return base_lr. -- - step: return base_lr * gamma ^ (floor(iter / step)) -- - exp: return base_lr * gamma ^ iter -- - inv: return base_lr * (1 + gamma * iter) ^ (- power) -- - multistep: similar to step but it allows non uniform steps defined by -- stepvalue -- - poly: the effective learning rate follows a polynomial decay, to be -- zero by the max_iter. return base_lr (1 - iter/max_iter) ^ (power) -- - sigmoid: the effective learning rate follows a sigmod decay -- return base_lr ( 1/(1 + exp(-gamma * (iter - stepsize)))) -------------------------------------------------------------------------------------------------- function LRPolicy:__init(...) local args = dok.unpack( {...}, 'LRPolicy','Initialize a learning rate policy', {arg='policy', type ='string', help='Learning rate policy',req=true}, {arg='baselr', type ='number', help='Base learning rate',req=true}, {arg='gamma', type = 'number', help='parameter to compute learning rate',req=false}, {arg='power', type = 'number', help='parameter to compute learning rate', req = false}, {arg='step_size', type = 'number', help='parameter to compute learning rate', req = false}, {arg='max_iter', type = 'number', help='parameter to compute learning rate', req = false}, {arg='step_values', type = 'table', help='parameter to compute learning rate. Useful only when the learning rate policy is multistep', req = false} ) self.policy = args.policy self.baselr = args.baselr self.gamma = args.gamma self.power = args.power self.step_values = args.step_values self.max_iter = args.max_iter if self.policy == 'step' or self.policy == 'sigmoid' then self.step_size = self.step_values[1] -- if the policy is not multistep, then even though multiple step values are provided as input, we will consider only the first value. elseif self.policy == 'multistep' then self.current_step = 1 -- this counter is important to take arbitary steps self.stepvalue_size = #self.step_values end end function LRPolicy:GetLearningRate(iter) local rate=0 if self.policy == "fixed" then rate = self.baselr elseif self.policy == "step" then local current_step = math.floor(iter/self.step_size) rate = self.baselr * math.pow(self.gamma, current_step) elseif self.policy == "exp" then rate = self.baselr * math.pow(self.gamma, iter) elseif self.policy == "inv" then rate = self.baselr * math.pow(1 + self.gamma * iter, - self.power) elseif self.policy == "multistep" then if (self.current_step <= self.stepvalue_size and iter >= self.step_values[self.current_step]) then self.current_step = self.current_step + 1 end rate = self.baselr * math.pow(self.gamma, self.current_step - 1); elseif self.policy == "poly" then rate = self.baselr * math.pow(1.0 - (iter / self.max_iter), self.power) elseif self.policy == "sigmoid" then rate = self.baselr * (1.0 / (1.0 + exp(-self.gamma * (iter - self.step_size)))); else --have to include additional comments print("Unknown learning rate policy: " .. self.policy) end return rate end
-- Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. local LRPolicy = torch.class('LRPolicy') ---------------------------------------------------------------------------------------- -- This file contains details of learning rate policies that are used in caffe. -- Calculates and returns the current learning rate. The currently implemented learning rate -- policies are as follows: -- - fixed: always return base_lr. -- - step: return base_lr * gamma ^ (floor(iter / step)) -- - exp: return base_lr * gamma ^ iter -- - inv: return base_lr * (1 + gamma * iter) ^ (- power) -- - multistep: similar to step but it allows non uniform steps defined by -- stepvalue -- - poly: the effective learning rate follows a polynomial decay, to be -- zero by the max_iter. return base_lr (1 - iter/max_iter) ^ (power) -- - sigmoid: the effective learning rate follows a sigmod decay -- return base_lr ( 1/(1 + exp(-gamma * (iter - stepsize)))) -------------------------------------------------------------------------------------------------- function LRPolicy:__init(...) local args = dok.unpack( {...}, 'LRPolicy','Initialize a learning rate policy', {arg='policy', type ='string', help='Learning rate policy',req=true}, {arg='baselr', type ='number', help='Base learning rate',req=true}, {arg='gamma', type = 'number', help='parameter to compute learning rate',req=false}, {arg='power', type = 'number', help='parameter to compute learning rate', req = false}, {arg='step_size', type = 'number', help='parameter to compute learning rate', req = false}, {arg='max_iter', type = 'number', help='parameter to compute learning rate', req = false}, {arg='step_values', type = 'table', help='parameter to compute learning rate. Useful only when the learning rate policy is multistep', req = false} ) self.policy = args.policy self.baselr = args.baselr self.gamma = args.gamma self.power = args.power self.step_values = args.step_values self.max_iter = args.max_iter if self.policy == 'step' or self.policy == 'sigmoid' then self.step_size = self.step_values[1] -- if the policy is not multistep, then even though multiple step values are provided as input, we will consider only the first value. elseif self.policy == 'multistep' then self.current_step = 1 -- this counter is important to take arbitary steps self.stepvalue_size = #self.step_values end end function LRPolicy:GetLearningRate(iter) local rate=0 local progress = 100 * (iter / self.max_iter) -- expressed in percent units if self.policy == "fixed" then rate = self.baselr elseif self.policy == "step" then local current_step = math.floor(iter/self.step_size) rate = self.baselr * math.pow(self.gamma, current_step) elseif self.policy == "exp" then rate = self.baselr * math.pow(self.gamma, progress) elseif self.policy == "inv" then rate = self.baselr * math.pow(1 + self.gamma * progress, - self.power) elseif self.policy == "multistep" then if (self.current_step <= self.stepvalue_size and iter >= self.step_values[self.current_step]) then self.current_step = self.current_step + 1 end rate = self.baselr * math.pow(self.gamma, self.current_step - 1); elseif self.policy == "poly" then rate = self.baselr * math.pow(1.0 - (iter / self.max_iter), self.power) elseif self.policy == "sigmoid" then rate = self.baselr * (1.0 / (1.0 + math.exp(self.gamma * (progress - 100*self.step_size/self.max_iter)))); else --have to include additional comments print("Unknown learning rate policy: " .. self.policy) end return rate end
Fix Torch LR policy
Fix Torch LR policy "exp", "inv" and "sigmoid" weren't operating as expected close #662
Lua
bsd-3-clause
ethantang95/DIGITS,jmancewicz/DIGITS,TimZaman/DIGITS,Deepomatic/DIGITS,dongjoon-hyun/DIGITS,jmancewicz/DIGITS,ethantang95/DIGITS,Deepomatic/DIGITS,dongjoon-hyun/DIGITS,Lucaszw/DIGITS,dongjoon-hyun/DIGITS,ethantang95/DIGITS-GAN,TimZaman/DIGITS,Lucaszw/DIGITS,bygreencn/DIGITS,gheinrich/DIGITS-GAN,TimZaman/DIGITS,gheinrich/DIGITS-GAN,brainstorm-ai/DIGITS,TimZaman/DIGITS,bygreencn/DIGITS,Deepomatic/DIGITS,bygreencn/DIGITS,ethantang95/DIGITS-GAN,Lucaszw/DIGITS,ethantang95/DIGITS-GAN,Deepomatic/DIGITS,gheinrich/DIGITS-GAN,ethantang95/DIGITS-GAN,jmancewicz/DIGITS,brainstorm-ai/DIGITS,bygreencn/DIGITS,Lucaszw/DIGITS,dongjoon-hyun/DIGITS,gheinrich/DIGITS-GAN,brainstorm-ai/DIGITS,ethantang95/DIGITS,jmancewicz/DIGITS,ethantang95/DIGITS,brainstorm-ai/DIGITS
e8887b3dc0cddc4be74b6f9237106d47dc438511
libs/web/luasrc/http.lua
libs/web/luasrc/http.lua
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id$ ToDo: - Cookie handling License: 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 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. ]]-- module("luci.http", package.seeall) require("ltn12") require("luci.http.protocol") require("luci.util") context = luci.util.threadlocal() Request = luci.util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""), } setmetatable(self.message.params, {__index = function(tbl, key) setmetatable(tbl, nil) luci.http.protocol.parse_message_body( self.input, self.message, self.filehandler ) return rawget(tbl, key) end }) end function Request.formvalue(self, name, default) if name then return self.message.params[name] and tostring(self.message.params[name]) or default else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.getenv(self, name) return name and self.message.env[name] or self.message.env end function Request.setfilehandler(self, callback) self.filehandler = callback end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function formvalue(...) return context.request:formvalue(...) end function formvaluetable(...) return context.request:formvaluetable(...) end function getvalue(...) return context.request:getvalue(...) end function postvalue(...) return context.request:postvalue(...) end function getenv(...) return context.request:getenv(...) end function setfilehandler(...) return context.request:setfilehandler(...) end function header(key, value) if not context.status then status() end if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) header("Content-Type", mime) end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end function write(content) if not content or #content == 0 then return end if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) end function basic_auth(realm, errorpage) header("Status", "401 Unauthorized") header("WWW-Authenticate", string.format('Basic realm="%s"', realm or "")) if errorpage then errorpage() end close() end function redirect(url) header("Status", "302 Found") header("Location", url) close() end function build_querystring(table) local s="?" for k, v in pairs(table) do s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&" end return s end urldecode = luci.http.protocol.urldecode urlencode = luci.http.protocol.urlencode
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id$ ToDo: - Cookie handling License: 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 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. ]]-- module("luci.http", package.seeall) require("ltn12") require("luci.http.protocol") require("luci.util") context = luci.util.threadlocal() Request = luci.util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""), } setmetatable(self.message.params, {__index = function(tbl, key) setmetatable(tbl, nil) luci.http.protocol.parse_message_body( self.input, self.message, self.filehandler ) return rawget(tbl, key) end }) end function Request.formvalue(self, name, default) if name then return self.message.params[name] and tostring(self.message.params[name]) or default else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function formvalue(...) return context.request:formvalue(...) end function formvaluetable(...) return context.request:formvaluetable(...) end function getvalue(...) return context.request:getvalue(...) end function postvalue(...) return context.request:postvalue(...) end function getenv(...) return context.request:getenv(...) end function setfilehandler(...) return context.request:setfilehandler(...) end function header(key, value) if not context.status then status() end if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) header("Content-Type", mime) end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end function write(content) if not content or #content == 0 then return end if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) end function basic_auth(realm, errorpage) header("Status", "401 Unauthorized") header("WWW-Authenticate", string.format('Basic realm="%s"', realm or "")) if errorpage then errorpage() end close() end function redirect(url) header("Status", "302 Found") header("Location", url) close() end function build_querystring(table) local s="?" for k, v in pairs(table) do s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&" end return s end urldecode = luci.http.protocol.urldecode urlencode = luci.http.protocol.urlencode
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2424 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
phi-psi/luci,8devices/carambola2-luci,stephank/luci,gwlim/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,stephank/luci,zwhfly/openwrt-luci,ch3n2k/luci,gwlim/luci,alxhh/piratenluci,Canaan-Creative/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,zwhfly/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,stephank/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ch3n2k/luci,jschmidlapp/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Flexibity/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,8devices/carambola2-luci,gwlim/luci,projectbismark/luci-bismark,gwlim/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,freifunk-gluon/luci,freifunk-gluon/luci,saraedum/luci-packages-old,Canaan-Creative/luci,phi-psi/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,alxhh/piratenluci,eugenesan/openwrt-luci,jschmidlapp/luci,8devices/carambola2-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,8devices/carambola2-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,zwhfly/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,gwlim/luci,eugenesan/openwrt-luci,ch3n2k/luci,ch3n2k/luci,vhpham80/luci,phi-psi/luci,stephank/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,vhpham80/luci,zwhfly/openwrt-luci,jschmidlapp/luci,alxhh/piratenluci,alxhh/piratenluci,Canaan-Creative/luci,alxhh/piratenluci,yeewang/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,ch3n2k/luci,phi-psi/luci,eugenesan/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,phi-psi/luci,phi-psi/luci,alxhh/piratenluci,projectbismark/luci-bismark,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,gwlim/luci,Flexibity/luci,stephank/luci,8devices/carambola2-luci,Canaan-Creative/luci,ch3n2k/luci,ch3n2k/luci
36eab2616fdf64555832097d40b70076cec155bb
lua/filters/fieldfix.lua
lua/filters/fieldfix.lua
-- From: https://github.com/hynd/heka-tsutils-plugins -- 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/. --[[ Performs some basic mutations on message Fields - add if not present, override, remove, rename and parse. New messages will be emitted with a new Type. The Parse function can be used to extract field data embedded in another field, ie; in a StatsD bucket name. See Config for more information. Config: - msg_type (string, optional, default "fieldfix") String to set as the new message Type (which will also have 'heka.sandbox.' automatically and unavoidably prefixed) - payload_keep (bool, default false) If true, maintain the original Payloads in the new messages. - fields_if_missing (string, optional) Space delimited string of Fields to supplement (ie; add if they're not already present). Field name and value should be delimited with a '='. - fields_override (string, optional) Space delimited string of Fields to always ensure exists, overriding existing values if necessary. Field name and value should be delimited with a '='. - fields_remove (string, optional) Space delimited string of Fields to remove. Only the field name is required. - fields_rename (string, optional) Space delimited string of Fields to rename. Old and new name should be delimited with a '='. - fields_interpolate (string, optional) Space delimited string of Fields to add, and perform string-interpolation on - i.e. replace chunks of the form %{foo} with the value of the field foo. The new field name and custom values should be delimited with a '='. For example, if fields[foo] is 'hello' and fields[bar] is 'world', then the interpolation msg=%{foo}_%{bar} will result in fields[msg] as 'hello_world'. Note that the interpolation will only be done with the original field values, and not any that have been configured to get renamed or inserted. Note: that it's possibly to make any Field value in the above configuration a compound value by wrapping it in double quotes, i.e. fields_override = 'msg="hello world" cluster=wibble' *Example Heka Configuration* .. code-block:: ini [FieldFixFilter] type = "SandboxFilter" filename = "lua/filters/fieldfix.lua" preserve_data = false [FieldFixFilter.config] fields_if_missing = "source=myhost target=remotehost" fields_override = "cluster=wibble" fields_remove = "product" --]] require "string" local msg_type = read_config("msg_type") or "fieldfix" local payload_keep = read_config("payload_keep") local add_str = read_config("fields_if_missing") or "" local override_str = read_config("fields_override") or "" local remove_str = read_config("fields_remove") or "" local rename_str = read_config("fields_rename") or "" local interpolate_str = read_config("fields_interpolate") or "" -- convert a space-delimited string into a table of kv's, -- either splitting each token on '=', or setting the value -- to 'true' local function create_table(str) local t = {} if str:len() > 0 then local fields = {} -- Expressions with quoted strings for f in str:gmatch("[%S]+=\"[^\"]+\"") do fields[#fields+1] = f end -- Expressions without quoted strings for f in str:gmatch("[%S]+=[^\"][%S]*") do fields[#fields+1] = f end for i=1,#fields do -- Also need to remove the quotes from the final value local k, v = fields[i]:match("([%S]+)=\"?([^\"]+)\"?") if k ~= nil then t[k] = v else t[f] = true end end end return t end -- build tables local add = create_table(add_str) local remove = create_table(remove_str) local override = create_table(override_str) local rename = create_table(rename_str) local interpolate = create_table(interpolate_str) -- Used for interpolating message fields into series name. local function interpolate_func(key) local val = read_message("Fields["..key.."]") if val then return val end return "%{"..key.."}" end function process_message () local message = { Timestamp = read_message("Timestamp"), Type = msg_type, EnvVersion = read_message("EnvVersion"), Fields = {} } if payload_keep then message.Payload = read_message("Payload") end while true do local typ, name, value, representation, count = read_next_field() if not typ then break end -- Fields to remove if remove[name] then -- Fields to rename elseif rename[name] then message.Fields[rename[name]] = value -- Add untouched else message.Fields[name] = value end end -- Fields to supplement for k,v in pairs(add) do if not message.Fields[k] then message.Fields[k] = v end end -- Fields to override for k,v in pairs(override) do message.Fields[k] = v end -- Fields to interpolate for k,v in pairs(interpolate) do if string.find(v, "%%{[%w%p]-}") then interpolated = string.gsub(v, "%%{([%w%p]-)}", interpolate_func) end message.Fields[k] = interpolated end inject_message(message) return 0 end function timer_event(ns) end
-- From: https://github.com/hynd/heka-tsutils-plugins -- 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/. --[[ Performs some basic mutations on message Fields - add if not present, override, remove, rename and parse. New messages will be emitted with a new Type. The Parse function can be used to extract field data embedded in another field, ie; in a StatsD bucket name. See Config for more information. Config: - msg_type (string, optional, default "fieldfix") String to set as the new message Type (which will also have 'heka.sandbox.' automatically and unavoidably prefixed) - payload_keep (bool, default false) If true, maintain the original Payloads in the new messages. - payload (string, optional) If payload_keep is false, this allows overrides the Payload's value. Support string-interpolation (see "fields_override", below). - fields_if_missing (string, optional) Space delimited string of Fields to supplement (ie; add if they're not already present). Field name and value should be delimited with a '='. - fields_override (string, optional) Space delimited string of Fields to always ensure exists, overriding existing values if necessary. Field name and value should be delimited with a '='. Supports string-interpolation, i.e. replace chunks of the form %{foo} with the value of the field foo. For example, if fields[foo] is 'hello' and fields[bar] is 'world', then the interpolation msg=%{foo}_%{bar} will result in fields[msg] as 'hello_world'. Note that the interpolation will only be done with the original field values, and not any that have been configured to get renamed or inserted. - fields_remove (string, optional) Space delimited string of Fields to remove. Only the field name is required. - fields_rename (string, optional) Space delimited string of Fields to rename. Old and new name should be delimited with a '='. Note: that it's possibly to make any Field value in the above configuration a compound value by wrapping it in double quotes, i.e. fields_override = 'msg="hello world" cluster=wibble' *Example Heka Configuration* .. code-block:: ini [FieldFixFilter] type = "SandboxFilter" filename = "lua/filters/fieldfix.lua" preserve_data = false [FieldFixFilter.config] fields_if_missing = "source=myhost target=remotehost" fields_override = "cluster=wibble" fields_remove = "product" --]] require "string" local msg_type = read_config("msg_type") or "fieldfix" local payload_keep = read_config("payload_keep") or false local payload = read_config("payload") local add_str = read_config("fields_if_missing") or "" local override_str = read_config("fields_override") or "" local remove_str = read_config("fields_remove") or "" local rename_str = read_config("fields_rename") or "" -- convert a space-delimited string into a table of kv's, -- either splitting each token on '=', or setting the value -- to 'true' local function create_table(str) local t = {} if str:len() > 0 then local fields = {} -- Expressions with quoted strings for f in str:gmatch("[%S]+=\"[^\"]+\"") do fields[#fields+1] = f end -- Expressions without quoted strings for f in str:gmatch("[%S]+=[^\"][%S]*") do fields[#fields+1] = f end for i=1,#fields do -- Also need to remove the quotes from the final value local k, v = fields[i]:match("([%S]+)=\"?([^\"]+)\"?") if k ~= nil then t[k] = v else t[f] = true end end end return t end -- build tables local add = create_table(add_str) local remove = create_table(remove_str) local override = create_table(override_str) local rename = create_table(rename_str) -- For a given value local function interpolate_field_values(v) local out = v if string.find(v, "%%{[%w%p]-}") then out = string.gsub(v, "%%{([%w%p]-)}", interpolate_func) end return out end -- Used for interpolating message fields into series name. local function interpolate_func(key) local val = read_message("Fields["..key.."]") if val then return val end return "%{"..key.."}" end function process_message () local message = { Timestamp = read_message("Timestamp"), Type = msg_type, EnvVersion = read_message("EnvVersion"), Fields = {} } if payload_keep then -- Use existing payload message.Payload = read_message("Payload") else -- Override existing payload if payload then message.Payload = interpolate_field_values(payload) end end while true do local typ, name, value, representation, count = read_next_field() if not typ then break end -- Fields to remove if remove[name] then -- Fields to rename elseif rename[name] then message.Fields[rename[name]] = value -- Add untouched else message.Fields[name] = value end end -- Fields to supplement for k,v in pairs(add) do if not message.Fields[k] then message.Fields[k] = v end end -- Fields to override for k,v in pairs(override) do message.Fields[k] = interpolate_field_values(v) end inject_message(message) return 0 end function timer_event(ns) end
lua/filters: fieldfix- allow over-writing Payload.
lua/filters: fieldfix- allow over-writing Payload. Payload supports field interpolation. Also refactors by combing interpolate and override. Previously, the had the same behavior (overriding existing fields), but interpolate allowed interpolating values. So combined them into just "override", but supporting interpolation.
Lua
apache-2.0
wxdublin/heka-clever-plugins
3b588686089f9762d8210fdd33a4503b233d2d98
lua/mediaplayer/players/components/vote.lua
lua/mediaplayer/players/components/vote.lua
if SERVER then AddCSLuaFile() end --[[-------------------------------------------- Vote object ----------------------------------------------]] local VOTE = {} VOTE.__index = VOTE function VOTE:New( ply, value ) local obj = setmetatable( {}, self ) obj.player = ply obj.value = value or 1 return obj end function VOTE:IsValid() return IsValid(self.player) end function VOTE:GetPlayer() return self.player end function VOTE:GetValue() return self.value end MediaPlayer.VOTE = VOTE --[[-------------------------------------------- Vote Manager ----------------------------------------------]] local VoteManager = {} VoteManager.__index = VoteManager -- -- Initialize the media player object. -- -- @param mp Media player object. -- function VoteManager:New( mp ) local obj = setmetatable({}, self) obj._mp = mp obj._votes = {} return obj end --- -- Clears all votes. -- function VoteManager:Clear() self._votes = {} end --- -- Add vote for a player and media -- -- @param media Media object. -- @param ply Player. -- @param value Vote value. -- function VoteManager:AddVote( media, ply, value ) if not IsValid(ply) then return end local uid = media:UniqueID() local vote = self:GetVoteByPlayer(media, ply) -- Update vote if player has already voted if vote then vote.value = value else local votes if self._votes[uid] then votes = self._votes[uid] else votes = { media = media, count = 0 } self._votes[uid] = votes end vote = VOTE:New(ply, value) end -- player is retracting their vote if value == 0 then for k, v in ipairs(votes) do if v:GetPlayer() == ply then table.remove( votes, k ) break end end else table.insert( votes, vote ) end -- recalculate vote count self:GetVoteCountForMedia( media, true ) end --- -- Remove the player's vote for a media item. -- -- @param media Media object. -- @param ply Player. -- function VoteManager:RemoveVote( media, ply ) self:AddVote( media, ply, 0 ) end --- -- Get whether the player has already voted for the media. -- -- @param media Media object. -- @param ply Player. -- @return Whether the player has voted for the media. -- function VoteManager:HasVoted( media, ply ) local uid = media:UniqueID() local votes = self._votes[uid] if not votes then return false end for k, vote in ipairs(votes) do if vote:GetPlayer() == ply then return true end end return false end --- -- Get the vote count for the given media. -- -- @param media Media object or UID. -- @return Vote count for media. -- function VoteManager:GetVoteCountForMedia( media, forceCalc ) local uid = isstring(media) and media or media:UniqueID() local votes = self._votes[uid] if not votes then return 0 end if not votes.count or forceCalc then local count = 0 for k, vote in ipairs(votes) do count = count + vote:GetValue() end votes.count = count end return votes.count end function VoteManager:GetVoteByPlayer( media, ply ) local uid = media:UniqueID() local votes = self._votes[uid] if not votes then return nil end for _, vote in ipairs(votes) do if vote:GetPlayer() == ply then return vote end end return nil end --- -- Get the top voted media unique ID. VoteManager:Invalidate() should be called -- prior to this in case any players may have disconnected. -- -- @param removeMedia Remove the media from the vote manager. -- @return Top voted media UID. -- function VoteManager:GetTopVote( removeMedia ) local media, topVotes = nil, nil for uid, _ in pairs(self._votes) do local votes = self:GetVoteCountForMedia( uid ) if not topVotes or votes > topVotes then media = self._votes[uid].media topVotes = votes end end if removeMedia and media then self._votes[media:UniqueID()] = nil end return media, topVotes end --- -- Iterate through all votes and determine if they're still valid. This should -- called prior to getting the top vote. -- -- @return Whether any votes were invalid and removed. -- function VoteManager:Invalidate() local changed = false for uid, votes in pairs(self._votes) do local numVotes = 0 for k, vote in ipairs(votes) do -- check for valid player in case they may have disconnected if not (IsValid(vote) and self._mp:HasListener(vote:GetPlayer())) then table.remove( votes, k ) changed = true else numVotes = numVotes + 1 end end if numVotes == 0 then self._votes[uid] = nil end end return changed end MediaPlayer.VoteManager = VoteManager
if SERVER then AddCSLuaFile() end --[[-------------------------------------------- Vote object ----------------------------------------------]] local VOTE = {} VOTE.__index = VOTE function VOTE:New( ply, value ) local obj = setmetatable( {}, self ) obj.player = ply obj.value = value or 1 return obj end function VOTE:IsValid() return IsValid(self.player) end function VOTE:GetPlayer() return self.player end function VOTE:GetValue() return self.value end MediaPlayer.VOTE = VOTE --[[-------------------------------------------- Vote Manager ----------------------------------------------]] local VoteManager = {} VoteManager.__index = VoteManager -- -- Initialize the media player object. -- -- @param mp Media player object. -- function VoteManager:New( mp ) local obj = setmetatable({}, self) obj._mp = mp obj._votes = {} return obj end --- -- Clears all votes. -- function VoteManager:Clear() self._votes = {} end function VoteManager:ClearVotesForMedia( media ) self._votes[media:UniqueID()] = nil end --- -- Add vote for a player and media -- -- @param media Media object. -- @param ply Player. -- @param value Vote value. -- function VoteManager:AddVote( media, ply, value ) if not IsValid(ply) then return end local uid = media:UniqueID() local votes if self._votes[uid] then votes = self._votes[uid] else votes = { media = media, count = 0 } self._votes[uid] = votes end local vote = self:GetVoteByPlayer(media, ply) -- Update vote if player has already voted if vote then vote.value = value else vote = VOTE:New(ply, value) table.insert( votes, vote ) end -- player is retracting their vote if value == 0 then for k, v in ipairs(votes) do if v:GetPlayer() == ply then table.remove( votes, k ) break end end end -- recalculate vote count self:GetVoteCountForMedia( media, true ) end --- -- Remove the player's vote for a media item. -- -- @param media Media object. -- @param ply Player. -- function VoteManager:RemoveVote( media, ply ) self:AddVote( media, ply, 0 ) end --- -- Get whether the player has already voted for the media. -- -- @param media Media object. -- @param ply Player. -- @return Whether the player has voted for the media. -- function VoteManager:HasVoted( media, ply ) local uid = media:UniqueID() local votes = self._votes[uid] if not votes then return false end for k, vote in ipairs(votes) do if vote:GetPlayer() == ply then return true end end return false end --- -- Get the vote count for the given media. -- -- @param media Media object or UID. -- @return Vote count for media. -- function VoteManager:GetVoteCountForMedia( media, forceCalc ) local uid = isstring(media) and media or media:UniqueID() local votes = self._votes[uid] if not votes then return 0 end if not votes.count or forceCalc then local count = 0 for k, vote in ipairs(votes) do count = count + vote:GetValue() end votes.count = count end return votes.count end function VoteManager:GetVoteByPlayer( media, ply ) local uid = media:UniqueID() local votes = self._votes[uid] if not votes then return nil end for _, vote in ipairs(votes) do if vote:GetPlayer() == ply then return vote end end return nil end --- -- Get the top voted media unique ID. VoteManager:Invalidate() should be called -- prior to this in case any players may have disconnected. -- -- @param removeMedia Remove the media from the vote manager. -- @return Top voted media UID. -- function VoteManager:GetTopVote( removeMedia ) local media, topVotes = nil, nil for uid, _ in pairs(self._votes) do local votes = self:GetVoteCountForMedia( uid ) if not topVotes or votes > topVotes then media = self._votes[uid].media topVotes = votes end end if removeMedia and media then self._votes[media:UniqueID()] = nil end return media, topVotes end --- -- Iterate through all votes and determine if they're still valid. This should -- called prior to getting the top vote. -- -- @return Whether any votes were invalid and removed. -- function VoteManager:Invalidate() local changed = false for uid, votes in pairs(self._votes) do local numVotes = 0 for k, vote in ipairs(votes) do -- check for valid player in case they may have disconnected if not (IsValid(vote) and self._mp:HasListener(vote:GetPlayer())) then table.remove( votes, k ) changed = true else numVotes = numVotes + 1 end end if numVotes == 0 then self._votes[uid] = nil end end return changed end MediaPlayer.VoteManager = VoteManager
Fixed issues with adding a vote.
Fixed issues with adding a vote.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
50460896c8e6b451e24eb4fe44c2fa51dc15095d
src/memory.lua
src/memory.lua
module(...,package.seeall) local lib = require("lib") local ffi = require("ffi") local C = ffi.C require("memory_h") --- ### Chunks: Serve small allocations from memory allocated in bulk -- Table of {pointer, physical, size, used}. -- Extended each time a new chunk is allocated. chunks = {} -- Allocate DMA-friendly memory. -- Return virtual memory pointer, physical address, and actual size. function dma_alloc (bytes) assert(bytes <= huge_page_size) bytes = lib.align(bytes, 128) if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then allocate_next_chunk() end local chunk = chunks[#chunks] local where = chunk.used chunk.used = chunk.used + bytes return chunk.pointer + where, chunk.physical + where, bytes end -- Add a new chunk. function allocate_next_chunk () local ptr = allocate_huge_page() chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr), physical = map(ptr), size = huge_page_size, used = 0 } end --- ### HugeTLB: Allocate contiguous memory in bulk from Linux function allocate_huge_page () local attempts = 3 for i = 1,attempts do local page = C.allocate_huge_page(huge_page_size) if page ~= nil then return page else reserve_new_page() end end error("Failed to allocate a huge page.") end function reserve_new_page () set_hugepages(get_hugepages() + 1) end function get_hugepages () return lib.readfile("/proc/sys/vm/nr_hugepages", "*n") end function set_hugepages (n) lib.writefile("/proc/sys/vm/nr_hugepages", tostring(n)) end function get_huge_page_size () local meminfo = lib.readfile("/proc/meminfo", "*a") local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB") return tonumber(hugesize) * 1024 end base_page_size = 4096 huge_page_size = get_huge_page_size() --- ### Physical address translation -- Convert from virtual address (pointer) to physical address (uint64_t). function virtual_to_physical (virt_addr) virt_addr = ffi.cast("uint64_t", virt_addr) local virt_page = tonumber(virt_addr / base_page_size) local offset = tonumber(virt_addr % base_page_size) local phys_page = C.phys_page(virt_page) if phys_page == 0 then error("Failed to resolve physical address of "..tostring(virt_addr)) end return ffi.cast("uint64_t", phys_page * base_page_size + offset) end --- ### selftest function selftest (options) print("selftest: memory") print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) for i = 1, 4 do io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ") io.flush() local dmaptr, physptr, dmalen = dma_alloc(huge_page_size) print("Got "..(dmalen/1024^2).."MB at 0x"..ffi.cast("void*",tonumber(physptr))) ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write assert(dmaptr ~= nil and dmalen == huge_page_size) end print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) print("HugeTLB page allocation OK.") end --- ### module init: `mlock()` at load time -- This module requires a stable virtual-to-physical address mapping. assert(C.lock_memory() == 0)
module(...,package.seeall) local lib = require("lib") local ffi = require("ffi") local C = ffi.C require("memory_h") --- ### Chunks: Serve small allocations from memory allocated in bulk -- Table of {pointer, physical, size, used}. -- Extended each time a new chunk is allocated. chunks = {} -- Allocate DMA-friendly memory. -- Return virtual memory pointer, physical address, and actual size. function dma_alloc (bytes) assert(bytes <= huge_page_size) bytes = lib.align(bytes, 128) if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then allocate_next_chunk() end local chunk = chunks[#chunks] local where = chunk.used chunk.used = chunk.used + bytes return chunk.pointer + where, chunk.physical + where, bytes end -- Add a new chunk. function allocate_next_chunk () local ptr = allocate_huge_page() chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr), physical = virtual_to_physical(ptr), size = huge_page_size, used = 0 } end --- ### HugeTLB: Allocate contiguous memory in bulk from Linux function allocate_huge_page () local attempts = 3 for i = 1,attempts do local page = C.allocate_huge_page(huge_page_size) if page ~= nil then return page else reserve_new_page() end end error("Failed to allocate a huge page.") end function reserve_new_page () set_hugepages(get_hugepages() + 1) end function get_hugepages () return lib.readfile("/proc/sys/vm/nr_hugepages", "*n") end function set_hugepages (n) lib.writefile("/proc/sys/vm/nr_hugepages", tostring(n)) end function get_huge_page_size () local meminfo = lib.readfile("/proc/meminfo", "*a") local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB") return tonumber(hugesize) * 1024 end base_page_size = 4096 huge_page_size = get_huge_page_size() --- ### Physical address translation -- Convert from virtual address (pointer) to physical address (uint64_t). function virtual_to_physical (virt_addr) virt_addr = ffi.cast("uint64_t", virt_addr) local virt_page = tonumber(virt_addr / base_page_size) local offset = tonumber(virt_addr % base_page_size) local phys_page = C.phys_page(virt_page) if phys_page == 0 then error("Failed to resolve physical address of "..tostring(virt_addr)) end return ffi.cast("uint64_t", phys_page * base_page_size + offset) end --- ### selftest function selftest (options) print("selftest: memory") print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) for i = 1, 4 do io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ") io.flush() local dmaptr, physptr, dmalen = dma_alloc(huge_page_size) print("Got "..(dmalen/1024^2).."MB ".. "at 0x"..tostring(ffi.cast("void*",tonumber(physptr)))) ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write assert(dmaptr ~= nil and dmalen == huge_page_size) end print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages()) print("HugeTLB page allocation OK.") end --- ### module init: `mlock()` at load time --- This module requires a stable physical-virtual mapping so this is --- enforced automatically at load-time. assert(C.lock_memory() == 0)
memory.lua: Fixed bugs introduced in editing.
memory.lua: Fixed bugs introduced in editing.
Lua
apache-2.0
xdel/snabbswitch,kbara/snabb,dpino/snabb,heryii/snabb,mixflowtech/logsensor,pavel-odintsov/snabbswitch,kbara/snabb,aperezdc/snabbswitch,lukego/snabbswitch,mixflowtech/logsensor,aperezdc/snabbswitch,dpino/snabb,virtualopensystems/snabbswitch,pirate/snabbswitch,wingo/snabb,pirate/snabbswitch,wingo/snabb,snabbco/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,xdel/snabbswitch,lukego/snabb,kellabyte/snabbswitch,eugeneia/snabb,Igalia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,hb9cwp/snabbswitch,kbara/snabb,plajjan/snabbswitch,Igalia/snabbswitch,hb9cwp/snabbswitch,virtualopensystems/snabbswitch,dpino/snabb,hb9cwp/snabbswitch,heryii/snabb,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,andywingo/snabbswitch,virtualopensystems/snabbswitch,wingo/snabbswitch,wingo/snabb,heryii/snabb,xdel/snabbswitch,Igalia/snabbswitch,snabbnfv-goodies/snabbswitch,snabbnfv-goodies/snabbswitch,eugeneia/snabbswitch,wingo/snabb,heryii/snabb,fhanik/snabbswitch,lukego/snabb,SnabbCo/snabbswitch,aperezdc/snabbswitch,dpino/snabbswitch,javierguerragiraldez/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,snabbco/snabb,wingo/snabb,pavel-odintsov/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,Igalia/snabb,fhanik/snabbswitch,eugeneia/snabb,eugeneia/snabb,mixflowtech/logsensor,dwdm/snabbswitch,andywingo/snabbswitch,justincormack/snabbswitch,pavel-odintsov/snabbswitch,Igalia/snabbswitch,andywingo/snabbswitch,eugeneia/snabbswitch,javierguerragiraldez/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,kbara/snabb,fhanik/snabbswitch,snabbco/snabb,dpino/snabb,SnabbCo/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,justincormack/snabbswitch,snabbco/snabb,wingo/snabbswitch,dpino/snabbswitch,plajjan/snabbswitch,wingo/snabbswitch,aperezdc/snabbswitch,dpino/snabbswitch,plajjan/snabbswitch,justincormack/snabbswitch,kbara/snabb,hb9cwp/snabbswitch,pirate/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,lukego/snabbswitch,plajjan/snabbswitch,Igalia/snabbswitch,heryii/snabb,alexandergall/snabbswitch,dpino/snabb,lukego/snabb,dwdm/snabbswitch,snabbco/snabb,snabbnfv-goodies/snabbswitch,heryii/snabb,Igalia/snabb,wingo/snabbswitch,alexandergall/snabbswitch,andywingo/snabbswitch,Igalia/snabb,lukego/snabb,Igalia/snabb,justincormack/snabbswitch,Igalia/snabb,kbara/snabb,eugeneia/snabbswitch,wingo/snabb,SnabbCo/snabbswitch,lukego/snabbswitch,kellabyte/snabbswitch,kellabyte/snabbswitch,Igalia/snabb,dpino/snabb,lukego/snabbswitch,mixflowtech/logsensor,dpino/snabb,dwdm/snabbswitch,alexandergall/snabbswitch,snabbnfv-goodies/snabbswitch
56a8c478e343042d90ef6f3fc719efd73a73d006
src/npge/block/excludeSelfOverlap.lua
src/npge/block/excludeSelfOverlap.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. return function(block) local slice = require 'npge.block.slice' local hasSelfOverlap = require 'npge.block.hasSelfOverlap' if not hasSelfOverlap(block) then return {block} end local function isGood(length) return hasSelfOverlap(slice(block, 1, length)) end if not isGood(1) then -- even first column of the block has self-overlap return {} end local min = 1 local max = block:length() -- binary search while min < max do local middle = math.floor((min + 1 + max) / 2) if isGood(middle) then min = middle else max = middle end end assert(min == max) assert(1 < min) assert(max < block:length()) return {slice(block, 1, min)} end
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. return function(block) local slice = require 'npge.block.slice' local hasSelfOverlap = require 'npge.block.hasSelfOverlap' if not hasSelfOverlap(block) then return {block} end local function makeSlice(length) return slice(block, 0, length - 1) end local function hasOverlap(length) return hasSelfOverlap(makeSlice(length)) end if hasOverlap(1) then -- even first column of the block has self-overlap return {} end assert(hasOverlap(block:length())) local binary_search = require 'npge.util.binary_search' local first_overlap = binary_search.firstTrue(hasOverlap, 1, block:length()) assert(first_overlap > 1) assert(first_overlap < block:length()) local new_block = makeSlice(first_overlap - 1) assert(not hasSelfOverlap(new_block)) return {new_block} end
fix excludeSelfOverlap and use binary_search
fix excludeSelfOverlap and use binary_search excludeSelfOverlap used to return blocks with self-overlaps
Lua
mit
starius/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge
97690aebfbb082b5c51418f3ceedc6080a4495bc
src/python.lua
src/python.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Python = newclass "Python" function Python:init(loader) self.loader = loader end function Python:yaml2json(yaml) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml)) end function Python:prettifyJSON(json) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json)) end function Python:update() self:conda("config --set always_yes yes --set changeps1 no") self:conda("update --all --yes") end function Python:__call(command) return os.outputoff("%s %s", self:_getPythonExe(), command) end function Python:conda(command) local conda = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("conda")) os.executef("%s %s", conda, command) end function Python:pip(command) local pip = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("pip")) os.executef("%s %s", pip, command) end function Python:_getDirectory() return path.join(zpm.env.getDataDirectory(), "conda") end function Python:_getPythonExe() return path.join(self:_getDirectory(), zpm.util.getExecutable("python")) end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] Python = newclass "Python" function Python:init(loader) self.loader = loader end function Python:yaml2json(yaml) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/yaml2json.py"), yaml)) end function Python:prettifyJSON(json) return self(("%s %s"):format(path.join(zpm.env.getSrcDirectory(), "py/prettifyjson.py"), json)) end function Python:update() self:conda("config --set always_yes yes --set changeps1 no") self:conda("update --all --yes") end function Python:__call(command) return os.outputoff("%s %s", self:_getPythonExe(), command) end function Python:conda(command) local conda = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("conda")) os.executef("%s %s", conda, command) end function Python:pip(command) local pip = path.join(self:_getDirectory(), "Scripts", zpm.util.getExecutable("pip")) os.executef("%s %s", pip, command) end function Python:_getDirectory() return path.join(zpm.env.getDataDirectory(), "conda") end function Python:_getPythonExe() return path.join(self:_getDirectory(), zpm.util.getExecutable(iif(os.is("windows"), "python", "python3"))) end
Fix python path
Fix python path
Lua
mit
Zefiros-Software/ZPM
a78f60462583a108f6ca504bd42ad8392dc6ae41
modules/awesomejapan.lua
modules/awesomejapan.lua
local ev = require'ev' local _FLIGHT = ivar2.config.awesomejapan.flight local getDiff = function() local _END = os.date('*t', _FLIGHT) local _NOW = os.date('*t', os.time()) local flipped if(os.time(_END) < os.time(_NOW)) then flipped = true _END, _NOW = _NOW, _END end local _MAX = {60,60,24,os.date('*t',os.time{year=_NOW.year,month=_NOW.month+1,day=0}).day,12} local diff = {} local order = {'sec','min','hour','day','month','year'} for i, v in ipairs(order) do diff[v] = _END[v] - _NOW[v] + (carry and -1 or 0) carry = diff[v] < 0 if(carry) then diff[v] = diff[v] + _MAX[i] end end return diff, flipped end local isOwner = function(source) if(ivar2.config.owners) then for _, mask in next, ivar2.config.owners do if(mask == source.mask) then return true end end end end do local self = ivar2 if(not ivar2.timers) then ivar2.timers = {} end local name = 'Awesome Japan' if(not self.timers[name]) then local today = os.date('*t', os.time()) local midnight = os.time{year = today.year, month = today.month, day = today.day + 1, hour = 0} local now = os.time() local timer = ev.Timer.new( function(loop, timer, revents) local _NOW = os.time() local days, flipped if(_FLIGHT < _NOW) then flipped = true days = math.floor((_NOW - _FLIGHT) / 86400) else days = math.floor((_FLIGHT - _NOW) / 86400) end if(self.config.awesomejapan.chans) then for k, dest in next, self.config.awesomejapan.chans do local locale = 'dag' if(days > 1) then locale = 'dager' end if(flipped) then self:Privmsg(dest, 'Bare %s %s siden awesome guys dro til Japan! *tease*', days, locale) else self:Privmsg(dest, 'Bare %s %s til the awesome guyz drar til Japan!', days, locale) end end end end, midnight - now, 86400 ) self.timers[name] = timer timer:start(ivar2.Loop) end end return { PRIVMSG = { <<<<<<< HEAD ["^\.awesomejapan%s*$"] = function(self, source, dest) ======= ["^%pawesomejapan%s*$"] = function(self, source, dest) >>>>>>> bfd2093... awesomejapan: Fix pattern. local relative = {} local nor = {'sekund', 'sekunder', 'minutt', 'minutter', 'time', 'timer', 'dag', 'dager', 'måned', 'måneder', 'år', 'år'} local order = {'sec','min','hour','day','month','year'} local diff, flipped = getDiff() for i=#order, 1, -1 do local field = order[i] local d = diff[field] if(d > 0) then local L = (d ~= 1 and i * 2) or (i * 2) - 1 table.insert(relative, string.format('%d %s', d, nor[L])) end end local att = self.config.awesomejapan.guyz local awesome if(att) then local nick = source.nick for _, guy in next, att do if(nick == guy) then awesome = true break end end end if(flipped) then if(awesome) then self:Msg('privmsg', dest, source, 'Bare %s siden DU satt deg på flyet mot Japan. LOL FAIL HOTEL LONER', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Bare %s siden Awesomegjengen satt seg på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end else if(awesome) then self:Msg('privmsg', dest, source, 'Om %s sitter DU og Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Om %s sitter Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end end end, ["^%pawesomejapan stop$"] = function(self, source, dest) if(isOwner(source)) then local name = 'Awesome Japan' self.timers[name]:stop(self.Loop) self.timers[name] = nil end end, } }
local ev = require'ev' local _FLIGHT = ivar2.config.awesomejapan.flight local getDiff = function() local _END = os.date('*t', _FLIGHT) local _NOW = os.date('*t', os.time()) local flipped if(os.time(_END) < os.time(_NOW)) then flipped = true _END, _NOW = _NOW, _END end local _MAX = {60,60,24,os.date('*t',os.time{year=_NOW.year,month=_NOW.month+1,day=0}).day,12} local diff = {} local order = {'sec','min','hour','day','month','year'} for i, v in ipairs(order) do diff[v] = _END[v] - _NOW[v] + (carry and -1 or 0) carry = diff[v] < 0 if(carry) then diff[v] = diff[v] + _MAX[i] end end return diff, flipped end local isOwner = function(source) if(ivar2.config.owners) then for _, mask in next, ivar2.config.owners do if(mask == source.mask) then return true end end end end do local self = ivar2 if(not ivar2.timers) then ivar2.timers = {} end local name = 'Awesome Japan' if(not self.timers[name]) then local today = os.date('*t', os.time()) local midnight = os.time{year = today.year, month = today.month, day = today.day + 1, hour = 0} local now = os.time() local timer = ev.Timer.new( function(loop, timer, revents) local _NOW = os.time() local days, flipped if(_FLIGHT < _NOW) then flipped = true days = math.floor((_NOW - _FLIGHT) / 86400) else days = math.floor((_FLIGHT - _NOW) / 86400) end if(self.config.awesomejapan.chans) then for k, dest in next, self.config.awesomejapan.chans do local locale = 'dag' if(days > 1) then locale = 'dager' end if(flipped) then self:Privmsg(dest, 'Bare %s %s siden awesome guys dro til Japan! *tease*', days, locale) else self:Privmsg(dest, 'Bare %s %s til the awesome guyz drar til Japan!', days, locale) end end end end, midnight - now, 86400 ) self.timers[name] = timer timer:start(ivar2.Loop) end end return { PRIVMSG = { ["^%pawesomejapan%s*$"] = function(self, source, dest) local relative = {} local nor = {'sekund', 'sekunder', 'minutt', 'minutter', 'time', 'timer', 'dag', 'dager', 'måned', 'måneder', 'år', 'år'} local order = {'sec','min','hour','day','month','year'} local diff, flipped = getDiff() for i=#order, 1, -1 do local field = order[i] local d = diff[field] if(d > 0) then local L = (d ~= 1 and i * 2) or (i * 2) - 1 table.insert(relative, string.format('%d %s', d, nor[L])) end end local att = self.config.awesomejapan.guyz local awesome if(att) then local nick = source.nick for _, guy in next, att do if(nick == guy) then awesome = true break end end end if(flipped) then if(awesome) then self:Msg('privmsg', dest, source, 'Bare %s siden DU satt deg på flyet mot Japan. LOL FAIL HOTEL LONER', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Bare %s siden Awesomegjengen satt seg på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end else if(awesome) then self:Msg('privmsg', dest, source, 'Om %s sitter DU og Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) else self:Msg('privmsg', dest, source, 'Om %s sitter Awesomegjengen på flyet mot Japan!', table.concat(relative, ', '):gsub(', ([^,]+)$', ' og %1')) end end end, ["^%pawesomejapan stop$"] = function(self, source, dest) if(isOwner(source)) then local name = 'Awesome Japan' self.timers[name]:stop(self.Loop) self.timers[name] = nil end end, } }
awesomejapan: fix broken merge
awesomejapan: fix broken merge Former-commit-id: c17b5bc7c917846f353658dbfe09a4d887ba72c3 [formerly 19aa9008435513b5f4f7dec87ac50528e4397579] Former-commit-id: f763f979cddb55f45ecfb3494875fc27193bc7d7
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
f26bbca589b44aaba521ccdaf0c2a1032d42c406
kong/core/globalpatches.lua
kong/core/globalpatches.lua
return function(options) options = options or {} if options.cli then ngx.IS_CLI = true ngx.exit = function()end -- force LuaSocket usage to resolve `/etc/hosts` until -- supported by resty-cli. -- See https://github.com/Mashape/kong/issues/1523 for _, namespace in ipairs({"cassandra", "pgmoon-mashape"}) do local socket = require(namespace .. ".socket") socket.force_luasocket(ngx.get_phase(), true) end end if options.rbusted then do -- patch luassert's 'assert' because very often we use the Lua idiom: -- local res = assert(some_method()) -- in our tests. -- luassert's 'assert' would error out in case the assertion fails, and -- if 'some_method()' returns a third return value because we attempt to -- perform arithmetic (+1) to the 'level' argument of 'assert'. -- This error would often supersed the actual error (arg #2) and be painful -- to debug. local assert = require "luassert.assert" local assert_mt = getmetatable(assert) if assert_mt then assert_mt.__call = function(self, bool, message, level, ...) if not bool then local lvl = 2 if type(level) == "number" then lvl = level + 1 end error(message or "assertion failed!", lvl) end return bool, message, level, ... end end end else do local meta = require "kong.meta" _G._KONG = { _NAME = meta._NAME, _VERSION = meta._VERSION } end do local randomseed = math.randomseed local seed --- Seeds the random generator, use with care. -- Once - properly - seeded, this method is replaced with a stub -- one. This is to enforce best-practises for seeding in ngx_lua, -- and prevents third-party modules from overriding our correct seed -- (many modules make a wrong usage of `math.randomseed()` by calling -- it multiple times or do not use unique seed for Nginx workers). -- -- This patched method will create a unique seed per worker process, -- using a combination of both time and the worker's pid. -- luacheck: globals math _G.math.randomseed = function() if not seed then -- If we're in runtime nginx, we have multiple workers so we _only_ -- accept seeding when in the 'init_worker' phase. -- That is because that phase is the earliest one before the -- workers have a chance to process business logic, and because -- if we'd do that in the 'init' phase, the Lua VM is not forked -- yet and all workers would end-up using the same seed. if not options.cli and ngx.get_phase() ~= "init_worker" then error("math.randomseed() must be called in init_worker", 2) end seed = ngx.time() + ngx.worker.pid() ngx.log(ngx.DEBUG, "random seed: ", seed, " for worker nb ", ngx.worker.id(), " (pid: ", ngx.worker.pid(), ")") randomseed(seed) else ngx.log(ngx.DEBUG, "attempt to seed random number generator, but ", "already seeded with ", seed) end return seed end end end end
return function(options) options = options or {} if options.cli then ngx.IS_CLI = true ngx.exit = function()end -- force LuaSocket usage to resolve `/etc/hosts` until -- supported by resty-cli. -- See https://github.com/Mashape/kong/issues/1523 for _, namespace in ipairs({"cassandra", "pgmoon-mashape"}) do local socket = require(namespace .. ".socket") socket.force_luasocket(ngx.get_phase(), true) end end if options.rbusted then do -- patch luassert's 'assert' because very often we use the Lua idiom: -- local res = assert(some_method()) -- in our tests. -- luassert's 'assert' would error out in case the assertion fails, and -- if 'some_method()' returns a third return value because we attempt to -- perform arithmetic (+1) to the 'level' argument of 'assert'. -- This error would often supersed the actual error (arg #2) and be painful -- to debug. local assert = require "luassert.assert" local assert_mt = getmetatable(assert) if assert_mt then assert_mt.__call = function(self, bool, message, level, ...) if not bool then local lvl = 2 if type(level) == "number" then lvl = level + 1 end error(message or "assertion failed!", lvl) end return bool, message, level, ... end end end else do local meta = require "kong.meta" _G._KONG = { _NAME = meta._NAME, _VERSION = meta._VERSION } end do local randomseed = math.randomseed local seed --- Seeds the random generator, use with care. -- Once - properly - seeded, this method is replaced with a stub -- one. This is to enforce best-practises for seeding in ngx_lua, -- and prevents third-party modules from overriding our correct seed -- (many modules make a wrong usage of `math.randomseed()` by calling -- it multiple times or do not use unique seed for Nginx workers). -- -- This patched method will create a unique seed per worker process, -- using a combination of both time and the worker's pid. -- luacheck: globals math _G.math.randomseed = function() if not seed then -- If we're in runtime nginx, we have multiple workers so we _only_ -- accept seeding when in the 'init_worker' phase. -- That is because that phase is the earliest one before the -- workers have a chance to process business logic, and because -- if we'd do that in the 'init' phase, the Lua VM is not forked -- yet and all workers would end-up using the same seed. if not options.cli and ngx.get_phase() ~= "init_worker" then local debug = require "debug" ngx.log(ngx.WARN, "math.randomseed() must be called in init_worker context\n", debug.traceback()) end seed = ngx.time() + ngx.worker.pid() ngx.log(ngx.DEBUG, "random seed: ", seed, " for worker nb ", ngx.worker.id(), " (pid: ", ngx.worker.pid(), ")") randomseed(seed) else ngx.log(ngx.DEBUG, "attempt to seed random number generator, but ", "already seeded with ", seed) end return seed end end end end
fix(globalpatches) wanr log on randomseed attempt
fix(globalpatches) wanr log on randomseed attempt log the issues instead of erroring out to prevent `lua_code_cache=off` from being aborted when math.randomseed is called from defectuous modules. Fix #1716
Lua
apache-2.0
jebenexer/kong,li-wl/kong,icyxp/kong,ccyphers/kong,Kong/kong,akh00/kong,salazar/kong,Kong/kong,Mashape/kong,Kong/kong,shiprabehera/kong
0be32e82f2f2a1a3ea72d9f4f7987c0816809633
kong/tools/wrpc/message.lua
kong/tools/wrpc/message.lua
local pb = require "pb" local tonumber = tonumber local select = select local pb_decode = pb.decode local pb_encode = pb.encode local ngx_log = ngx.log local ERR = ngx.ERR local NOTICE = ngx.NOTICE -- utility functions --- little helper to ease grabbing an unspecified number --- of values after an `ok` flag local function ok_wrapper(ok, ...) return ok, {n = select('#', ...), ...} end local _M = {} local function send_error(wrpc_peer, payload, error) local ok, err = wrpc_peer:send_payload({ mtype = "MESSAGE_TYPE_ERROR", error = error, svc_id = payload.svc_id, rpc_id = payload.rpc_id, ack = payload.seq, }) if not ok then return ok, err end return nil, error.description or "unspecified error" end local function handle_request(wrpc_peer, rpc, payload) if not rpc.handler then return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_INVALID_RPC", -- invalid here, not in the definition description = "Unhandled method", }) end local input_data = pb_decode(rpc.input_type, payload.payloads) local ok, output_data = ok_wrapper(pcall(rpc.handler, wrpc_peer, input_data)) if not ok then local err = tostring(output_data[1]) ngx_log(ERR, ("[wrpc] Error handling %q method: %q"):format(rpc.name, err)) return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_UNSPECIFIED", description = err, }) end return wrpc_peer:send_payload({ mtype = "MESSAGE_TYPE_RPC", -- MESSAGE_TYPE_RPC, svc_id = rpc.svc_id, rpc_id = rpc.rpc_id, ack = payload.seq, payload_encoding = "ENCODING_PROTO3", payloads = pb_encode(rpc.output_type, output_data), }) end local function handle_response(wrpc_peer, rpc, payload,response_future) -- response to a previous call if not response_future then local err = "receiving response for a call expired or not initiated by this peer." ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) pcall(rpc.response_handler, wrpc_peer, pb_decode(rpc.output_type, payload.payloads)) return nil, err end if response_future:is_expire() then response_future:expire() return nil, "timeout" end response_future:done(pb_decode(rpc.output_type, payload.payloads)) return true end --- Handle RPC data (mtype == MESSAGE_TYPE_RPC). --- Could be an incoming method call or the response to a previous one. --- @param payload table decoded payload field from incoming `wrpc.WebsocketPayload` function _M.process_message(wrpc_peer, payload) local rpc = wrpc_peer.service:get_rpc( payload.svc_id .. '.' .. payload.rpc_id) if not rpc then return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_INVALID_SERVICE", description = "Invalid service (or rpc)", }) end local ack = tonumber(payload.ack) or 0 if ack > 0 then local response_future = wrpc_peer.responses[ack] return handle_response(wrpc_peer, rpc, payload,response_future) -- protobuf can not tell 0 from nil so this is best we can do elseif ack == 0 then -- incoming method call return handle_request(wrpc_peer, rpc, payload) else local err = "receiving negative ack number" ngx_log(ERR, err, ":", ack) return nil, err end end --- Handle incoming error message (mtype == MESSAGE_TYPE_ERROR). function _M.handle_error(wrpc_peer, payload) local etype = payload.error and payload.error.etype or "--" local errdesc = payload.error and payload.error.description or "--" ngx_log(NOTICE, string.format( "[wRPC] Received error message, %s.%s:%s (%s: %q)", payload.svc_id, payload.rpc_id, payload.ack, etype, errdesc )) local ack = tonumber(payload.ack) or 0 if ack < 0 then local err = "receiving negative ack number" ngx_log(ERR, err, ":", ack) return nil, err end if ack == 0 then error("unreachable: Handling error response message with type of request") end -- response to a previous call local response_future = wrpc_peer.responses[ack] if not response_future then local err = "receiving error message for a call" .. "expired or not initiated by this peer." ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) local rpc = wrpc_peer.service:get_rpc(payload.svc_id .. payload.rpc_id) if not rpc then err = "receiving error message for unkonwn RPC" ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) return nil, err end -- fall back to rpc error handler if rpc.error_handler then local ok, err = pcall(rpc.error_handler, wrpc_peer, etype, errdesc) if not ok then ngx_log(ERR, "error thrown when handling RPC error: ", err) end end return nil, err end if response_future:is_expire() then response_future:expire() return nil, "receiving error message response for timeouted request" end -- finally, we can handle the error without encountering more errors response_future:error(etype, errdesc) return true end return _M
local pb = require "pb" local tonumber = tonumber local pb_decode = pb.decode local pb_encode = pb.encode local ngx_log = ngx.log local ERR = ngx.ERR local NOTICE = ngx.NOTICE local _M = {} local function send_error(wrpc_peer, payload, error) local ok, err = wrpc_peer:send_payload({ mtype = "MESSAGE_TYPE_ERROR", error = error, svc_id = payload.svc_id, rpc_id = payload.rpc_id, ack = payload.seq, }) if not ok then return ok, err end return nil, error.description or "unspecified error" end local empty_table = {} local function handle_request(wrpc_peer, rpc, payload) if not rpc.handler then return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_INVALID_RPC", -- invalid here, not in the definition description = "Unhandled method", }) end local input_data = pb_decode(rpc.input_type, payload.payloads) local ok, output_data = pcall(rpc.handler, wrpc_peer, input_data) if not ok then local err = output_data ngx_log(ERR, ("[wrpc] Error handling %q method: %q"):format(rpc.name, err)) return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_UNSPECIFIED", description = err, }) end if not output_data then output_data = empty_table end return wrpc_peer:send_payload({ mtype = "MESSAGE_TYPE_RPC", -- MESSAGE_TYPE_RPC, svc_id = rpc.svc_id, rpc_id = rpc.rpc_id, ack = payload.seq, payload_encoding = "ENCODING_PROTO3", payloads = pb_encode(rpc.output_type, output_data), }) end local function handle_response(wrpc_peer, rpc, payload,response_future) -- response to a previous call if not response_future then local err = "receiving response for a call expired or not initiated by this peer." ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) pcall(rpc.response_handler, wrpc_peer, pb_decode(rpc.output_type, payload.payloads)) return nil, err end if response_future:is_expire() then response_future:expire() return nil, "timeout" end response_future:done(pb_decode(rpc.output_type, payload.payloads)) return true end --- Handle RPC data (mtype == MESSAGE_TYPE_RPC). --- Could be an incoming method call or the response to a previous one. --- @param payload table decoded payload field from incoming `wrpc.WebsocketPayload` function _M.process_message(wrpc_peer, payload) local rpc = wrpc_peer.service:get_rpc( payload.svc_id .. '.' .. payload.rpc_id) if not rpc then return send_error(wrpc_peer, payload, { etype = "ERROR_TYPE_INVALID_SERVICE", description = "Invalid service (or rpc)", }) end local ack = tonumber(payload.ack) or 0 if ack > 0 then local response_future = wrpc_peer.responses[ack] return handle_response(wrpc_peer, rpc, payload,response_future) -- protobuf can not tell 0 from nil so this is best we can do elseif ack == 0 then -- incoming method call return handle_request(wrpc_peer, rpc, payload) else local err = "receiving negative ack number" ngx_log(ERR, err, ":", ack) return nil, err end end --- Handle incoming error message (mtype == MESSAGE_TYPE_ERROR). function _M.handle_error(wrpc_peer, payload) local etype = payload.error and payload.error.etype or "--" local errdesc = payload.error and payload.error.description or "--" ngx_log(NOTICE, string.format( "[wRPC] Received error message, %s.%s:%s (%s: %q)", payload.svc_id, payload.rpc_id, payload.ack, etype, errdesc )) local ack = tonumber(payload.ack) or 0 if ack < 0 then local err = "receiving negative ack number" ngx_log(ERR, err, ":", ack) return nil, err end if ack == 0 then error("unreachable: Handling error response message with type of request") end -- response to a previous call local response_future = wrpc_peer.responses[ack] if not response_future then local err = "receiving error message for a call" .. "expired or not initiated by this peer." ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) local rpc = wrpc_peer.service:get_rpc(payload.svc_id .. payload.rpc_id) if not rpc then err = "receiving error message for unkonwn RPC" ngx_log(ERR, err, " Service ID: ", payload.svc_id, " RPC ID: ", payload.rpc_id) return nil, err end -- fall back to rpc error handler if rpc.error_handler then local ok, err = pcall(rpc.error_handler, wrpc_peer, etype, errdesc) if not ok then ngx_log(ERR, "error thrown when handling RPC error: ", err) end end return nil, err end if response_future:is_expire() then response_future:expire() return nil, "receiving error message response for timeouted request" end -- finally, we can handle the error without encountering more errors response_future:error(etype, errdesc) return true end return _M
fix(wrpc) incorrect encoding of response (#8915)
fix(wrpc) incorrect encoding of response (#8915)
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
befbb54ff9bd597724628c14e9ca7b55e5e6d2a0
torch7/imagenet_winners/googlenet.lua
torch7/imagenet_winners/googlenet.lua
-- adapted from nagadomi's CIFAR attempt: https://github.com/nagadomi/kaggle-cifar10-torch7/blob/cuda-convnet2/inception_model.lua local function inception(depth_dim, input_size, config, lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local ReLU = lib[3] local depth_concat = nn.Concat(depth_dim) local conv1 = nn.Sequential() conv1:add(SpatialConvolution(input_size, config[1][1], 1, 1)):add(ReLU(true)) depth_concat:add(conv1) local conv3 = nn.Sequential() conv3:add(SpatialConvolution(input_size, config[2][1], 1, 1)):add(ReLU(true)) conv3:add(SpatialConvolution(config[2][1], config[2][2], 3, 3, 1, 1, 1, 1)):add(ReLU(true)) depth_concat:add(conv3) local conv5 = nn.Sequential() conv5:add(SpatialConvolution(input_size, config[3][1], 1, 1)):add(ReLU(true)) conv5:add(SpatialConvolution(config[3][1], config[3][2], 5, 5, 1, 1, 2, 2)):add(ReLU(true)) depth_concat:add(conv5) local pool = nn.Sequential() pool:add(SpatialMaxPooling(config[4][1], config[4][1], 1, 1, 1, 1)) pool:add(SpatialConvolution(input_size, config[4][2], 1, 1)):add(ReLU(true)) depth_concat:add(pool) return depth_concat end local function googlenet(lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local SpatialAveragePooling = torch.type(lib[2]) == 'nn.SpatialMaxPooling' and nn.SpatialAveragePooling or cudnn.SpatialAveragePooling local ReLU = lib[3] local model = nn.Sequential() model:add(SpatialConvolution(3,64,7,7,2,2,3,3)):add(ReLU(true)) model:add(SpatialMaxPooling(3,3,2,2,1,1)) -- LRN (not added for now) model:add(SpatialConvolution(64,64,1,1,1,1,0,0)):add(ReLU(true)) model:add(SpatialConvolution(64,192,3,3,1,1,1,1)):add(ReLU(true)) -- LRN (not added for now) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 192, {{ 64}, { 96,128}, {16, 32}, {3, 32}},lib)) -- 256 model:add(inception(2, 256, {{128}, {128,192}, {32, 96}, {3, 64}},lib)) -- 480 model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 480, {{192}, { 96,208}, {16, 48}, {3, 64}},lib)) -- 4(a) model:add(inception(2, 512, {{160}, {112,224}, {24, 64}, {3, 64}},lib)) -- 4(b) model:add(inception(2, 512, {{128}, {128,256}, {24, 64}, {3, 64}},lib)) -- 4(c) model:add(inception(2, 512, {{112}, {144,288}, {32, 64}, {3, 64}},lib)) -- 4(d) model:add(inception(2, 528, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 4(e) (14x14x832) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 832, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 5(a) model:add(inception(2, 832, {{384}, {192,384}, {48,128}, {3,128}},lib)) -- 5(b) model:add(SpatialAveragePooling(7,7,1,1)) model:add(nn.View(1024):setNumInputDims(3)) -- model:add(nn.Dropout(0.4)) model:add(nn.Linear(1024,1000)):add(nn.ReLU(true)) -- model:add(nn.LogSoftMax()) return model,'GoogleNet', {128,3,224,224} end return googlenet
-- adapted from nagadomi's CIFAR attempt: https://github.com/nagadomi/kaggle-cifar10-torch7/blob/cuda-convnet2/inception_model.lua local function inception(depth_dim, input_size, config, lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local ReLU = lib[3] local depth_concat = nn.Concat(depth_dim) local conv1 = nn.Sequential() conv1:add(SpatialConvolution(input_size, config[1][1], 1, 1)):add(ReLU(true)) depth_concat:add(conv1) local conv3 = nn.Sequential() conv3:add(SpatialConvolution(input_size, config[2][1], 1, 1)):add(ReLU(true)) conv3:add(SpatialConvolution(config[2][1], config[2][2], 3, 3, 1, 1, 1, 1)):add(ReLU(true)) depth_concat:add(conv3) local conv5 = nn.Sequential() conv5:add(SpatialConvolution(input_size, config[3][1], 1, 1)):add(ReLU(true)) conv5:add(SpatialConvolution(config[3][1], config[3][2], 5, 5, 1, 1, 2, 2)):add(ReLU(true)) depth_concat:add(conv5) local pool = nn.Sequential() pool:add(SpatialMaxPooling(config[4][1], config[4][1], 1, 1, 1, 1)) pool:add(SpatialConvolution(input_size, config[4][2], 1, 1)):add(ReLU(true)) depth_concat:add(pool) return depth_concat end local function googlenet(lib) local SpatialConvolution = lib[1] local SpatialMaxPooling = lib[2] local SpatialAveragePooling = torch.type(lib[2]) == 'nn.SpatialMaxPooling' and nn.SpatialAveragePooling or cudnn.SpatialAveragePooling local ReLU = lib[3] local model = nn.Sequential() model:add(SpatialConvolution(3,64,7,7,2,2,3,3)):add(ReLU(true)) model:add(SpatialMaxPooling(3,3,2,2,1,1)) -- LRN (not added for now) model:add(SpatialConvolution(64,64,1,1,1,1,0,0)):add(ReLU(true)) model:add(SpatialConvolution(64,192,3,3,1,1,1,1)):add(ReLU(true)) -- LRN (not added for now) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 192, {{ 64}, { 96,128}, {16, 32}, {3, 32}},lib)) -- 256 model:add(inception(2, 256, {{128}, {128,192}, {32, 96}, {3, 64}},lib)) -- 480 model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 480, {{192}, { 96,208}, {16, 48}, {3, 64}},lib)) -- 4(a) model:add(inception(2, 512, {{160}, {112,224}, {24, 64}, {3, 64}},lib)) -- 4(b) model:add(inception(2, 512, {{128}, {128,256}, {24, 64}, {3, 64}},lib)) -- 4(c) model:add(inception(2, 512, {{112}, {144,288}, {32, 64}, {3, 64}},lib)) -- 4(d) model:add(inception(2, 528, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 4(e) (14x14x832) model:add(SpatialMaxPooling(3,3,2,2,1,1)) model:add(inception(2, 832, {{256}, {160,320}, {32,128}, {3,128}},lib)) -- 5(a) model:add(inception(2, 832, {{384}, {192,384}, {48,128}, {3,128}},lib)) -- 5(b) model:add(SpatialAveragePooling(7,7,1,1)) model:add(nn.View(1024):setNumInputDims(3)) -- model:add(nn.Dropout(0.4)) model:add(nn.Linear(1024,1000)):add(nn.ReLU(true)) -- model:add(nn.LogSoftMax()) model:get(1).gradInput = nil return model,'GoogleNet', {128,3,224,224} end return googlenet
fix googlenet first layer gradInput
fix googlenet first layer gradInput
Lua
mit
soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks
99495aaed43bb770804b46f2a186c471c79808ee
frontend/ui/font.lua
frontend/ui/font.lua
--[[-- Font module. ]] local is_android = pcall(require, "android") local FontList = require("fontlist") local Freetype = require("ffi/freetype") local Screen = require("device").screen local logger = require("logger") local Font = { fontmap = { -- default font for menu contents cfont = "NotoSans-Regular.ttf", -- default font for title --tfont = "NimbusSanL-BoldItal.cff", tfont = "NotoSans-Bold.ttf", smalltfont = "NotoSans-Bold.ttf", x_smalltfont = "NotoSans-Bold.ttf", -- default font for footer ffont = "NotoSans-Regular.ttf", smallffont = "NotoSans-Regular.ttf", largeffont = "NotoSans-Regular.ttf", -- default font for reading position info rifont = "NotoSans-Regular.ttf", -- default font for pagination display pgfont = "NotoSans-Regular.ttf", -- selectmenu: font for item shortcut scfont = "DroidSansMono.ttf", -- help page: font for displaying keys hpkfont = "DroidSansMono.ttf", -- font for displaying help messages hfont = "NotoSans-Regular.ttf", -- font for displaying input content -- we have to use mono here for better distance controlling infont = "DroidSansMono.ttf", -- small mono font for displaying code smallinfont = "DroidSansMono.ttf", -- font for info messages infofont = "NotoSans-Regular.ttf", -- small font for info messages smallinfofont = "NotoSans-Regular.ttf", -- small bold font for info messages smallinfofontbold = "NotoSans-Bold.ttf", -- extra small font for info messages x_smallinfofont = "NotoSans-Regular.ttf", -- extra extra small font for info messages xx_smallinfofont = "NotoSans-Regular.ttf", }, sizemap = { cfont = 24, tfont = 26, smalltfont = 24, x_smalltfont = 22, ffont = 20, smallffont = 15, largeffont = 25, pgfont = 20, scfont = 20, rifont = 16, hpkfont = 20, hfont = 24, infont = 22, smallinfont = 16, infofont = 24, smallinfofont = 22, smallinfofontbold = 22, x_smallinfofont = 20, xx_smallinfofont = 18, }, fallbacks = { [1] = "NotoSans-Regular.ttf", [2] = "NotoSansCJKsc-Regular.otf", [3] = "freefont/FreeSans.ttf", [4] = "freefont/FreeSerif.ttf", }, -- face table faces = {}, } if is_android then table.insert(Font.fallbacks, 3, "DroidSansFallback.ttf") -- for some ancient pre-4.4 Androids end --- Gets font face object. -- @string font -- @int size optional size -- @treturn table @{FontFaceObj} function Font:getFace(font, size) -- default to content font if not font then font = self.cfont end if not size then size = self.sizemap[font] end -- original size before scaling by screen DPI local orig_size = size size = Screen:scaleBySize(size) local hash = font..size local face_obj = self.faces[hash] -- build face if not found if not face_obj then local realname = self.fontmap[font] if not realname then realname = font end local builtin_font_location = FontList.fontdir.."/"..realname local ok, face = pcall(Freetype.newFace, builtin_font_location, size) -- We don't ship Droid and Noto on Android because they're system fonts. -- This cuts package size in half, but 4.4 and older systems -- might not ship Noto. if not ok and is_android and realname:match("^Noto") then local system_font_location = "/system/fonts" logger.dbg("Font:", realname, "not found. Trying system location.") ok, face = pcall(Freetype.newFace, system_font_location.."/"..realname, size) -- Relevant Noto font not found on this device, fall back to Droid if not ok then if realname:match("Bold") then realname = "DroidSans-Bold.ttf" else realname = "DroidSans.ttf" end end end -- Not all fonts are bundled on all platforms because they come with the system. -- In that case, search through all font folders for the requested font. if not ok then local fonts = FontList:getFontList() local escaped_realname = realname:gsub("[-]", "%%-") for _k, _v in ipairs(fonts) do if _v:find(escaped_realname) then logger.dbg("Found font:", realname, "in", _v) ok, face = pcall(Freetype.newFace, _v, size) if ok then break end end end end if not ok then logger.err("#! Font ", font, " (", realname, ") not supported: ", face) return nil end --- Freetype font face wrapper object -- @table FontFaceObj -- @field orig_font font name requested -- @field size size of the font face (after scaled by screen size) -- @field orig_size raw size of the font face (before scale) -- @field ftface font face object from freetype -- @field hash hash key for this font face face_obj = { orig_font = font, size = size, orig_size = orig_size, ftface = face, hash = hash } self.faces[hash] = face_obj end return face_obj end return Font
--[[-- Font module. ]] local is_android = pcall(require, "android") local FontList = require("fontlist") local Freetype = require("ffi/freetype") local Screen = require("device").screen local logger = require("logger") local Font = { fontmap = { -- default font for menu contents cfont = "NotoSans-Regular.ttf", -- default font for title --tfont = "NimbusSanL-BoldItal.cff", tfont = "NotoSans-Bold.ttf", smalltfont = "NotoSans-Bold.ttf", x_smalltfont = "NotoSans-Bold.ttf", -- default font for footer ffont = "NotoSans-Regular.ttf", smallffont = "NotoSans-Regular.ttf", largeffont = "NotoSans-Regular.ttf", -- default font for reading position info rifont = "NotoSans-Regular.ttf", -- default font for pagination display pgfont = "NotoSans-Regular.ttf", -- selectmenu: font for item shortcut scfont = "DroidSansMono.ttf", -- help page: font for displaying keys hpkfont = "DroidSansMono.ttf", -- font for displaying help messages hfont = "NotoSans-Regular.ttf", -- font for displaying input content -- we have to use mono here for better distance controlling infont = "DroidSansMono.ttf", -- small mono font for displaying code smallinfont = "DroidSansMono.ttf", -- font for info messages infofont = "NotoSans-Regular.ttf", -- small font for info messages smallinfofont = "NotoSans-Regular.ttf", -- small bold font for info messages smallinfofontbold = "NotoSans-Bold.ttf", -- extra small font for info messages x_smallinfofont = "NotoSans-Regular.ttf", -- extra extra small font for info messages xx_smallinfofont = "NotoSans-Regular.ttf", }, sizemap = { cfont = 24, tfont = 26, smalltfont = 24, x_smalltfont = 22, ffont = 20, smallffont = 15, largeffont = 25, pgfont = 20, scfont = 20, rifont = 16, hpkfont = 20, hfont = 24, infont = 22, smallinfont = 16, infofont = 24, smallinfofont = 22, smallinfofontbold = 22, x_smallinfofont = 20, xx_smallinfofont = 18, }, fallbacks = { [1] = "NotoSans-Regular.ttf", [2] = "NotoSansCJKsc-Regular.otf", [3] = "freefont/FreeSans.ttf", [4] = "freefont/FreeSerif.ttf", }, -- face table faces = {}, } if is_android then table.insert(Font.fallbacks, 3, "DroidSansFallback.ttf") -- for some ancient pre-4.4 Androids end --- Gets font face object. -- @string font -- @int size optional size -- @treturn table @{FontFaceObj} function Font:getFace(font, size) -- default to content font if not font then font = self.cfont end if not size then size = self.sizemap[font] end -- original size before scaling by screen DPI local orig_size = size size = Screen:scaleBySize(size) local hash = font..size local face_obj = self.faces[hash] -- build face if not found if not face_obj then local realname = self.fontmap[font] if not realname then realname = font end local builtin_font_location = FontList.fontdir.."/"..realname local ok, face = pcall(Freetype.newFace, builtin_font_location, size) -- Not all fonts are bundled on all platforms because they come with the system. -- In that case, search through all font folders for the requested font. if not ok then local fonts = FontList:getFontList() local escaped_realname = realname:gsub("[-]", "%%-") for _k, _v in ipairs(fonts) do if _v:find(escaped_realname) then logger.dbg("Found font:", realname, "in", _v) ok, face = pcall(Freetype.newFace, _v, size) if ok then break end end end end if not ok then logger.err("#! Font ", font, " (", realname, ") not supported: ", face) return nil end --- Freetype font face wrapper object -- @table FontFaceObj -- @field orig_font font name requested -- @field size size of the font face (after scaled by screen size) -- @field orig_size raw size of the font face (before scale) -- @field ftface font face object from freetype -- @field hash hash key for this font face face_obj = { orig_font = font, size = size, orig_size = orig_size, ftface = face, hash = hash } self.faces[hash] = face_obj end return face_obj end return Font
[Android, fix] Revert slightly more of the Noto business (#5463)
[Android, fix] Revert slightly more of the Noto business (#5463) Follow-up to #5458. Cf. https://github.com/koreader/koreader/issues/5381#issuecomment-539873843.
Lua
agpl-3.0
koreader/koreader,NiLuJe/koreader,mwoz123/koreader,poire-z/koreader,pazos/koreader,Frenzie/koreader,Markismus/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader,mihailim/koreader,Frenzie/koreader,Hzj-jie/koreader
9cec98b7ed619883db9292667447f4afb6cf0869
modules/api_loader.lua
modules/api_loader.lua
local xml = require('xml') local module = { } module.classes = { String = { }, Integer = { }, Float = { }, Boolean = { }, Struct = { }, Enum = { } } module.enum = { } module.struct = { } local function loadEnums(api) local enums = api:xpath("//interface/enum") for _, e in ipairs(enums) do local enum = { } local i = 1 for _, item in ipairs(e:children("element")) do enum[item:attr("name")] = i i = i + 1 end module.enum[e:attr("name")] = enum end end local function loadStructs(api) local structs = api:xpath("//interface/struct") for _, s in ipairs(structs) do local struct = { } for _, item in ipairs(s:children("param")) do struct[item:attr("name")] = item:attributes() end module.struct[s:attr("name")] = struct end for n, s in pairs(module.struct) do for _, p in pairs(s) do if type(p.type) == 'string' then if p.type == "Integer" then p.class = module.classes.Integer elseif p.type == "String" then p.class = module.classes.String elseif p.type == "Float" then p.class = module.classes.Float elseif p.type == "Boolean" then p.class = module.classes.Boolean elseif module.enum[p.type] then p.class = module.classes.Enum p.type = module.enum[p.type] elseif module.struct[p.type] then p.class = module.classes.Struct p.type = module.struct[p.type] end end end end end function module.init(path) local _api = xml.open(path) if not _api then error(path .. " not found") end loadEnums(_api) loadStructs(_api) return module end return module
local xml = require('xml') local module = { } local function loadEnums(api, dest) local enums = api:xpath("//interface/enum") for _, e in ipairs(enums) do local enum = { } local i = 1 for _, item in ipairs(e:children("element")) do enum[item:attr("name")] = i i = i + 1 end dest.enum[e:attr("name")] = enum end end local function loadStructs(api, dest) local structs = api:xpath("//interface/struct") for _, s in ipairs(structs) do local struct = { } for _, item in ipairs(s:children("param")) do struct[item:attr("name")] = item:attributes() end dest.struct[s:attr("name")] = struct end for n, s in pairs(dest.struct) do for _, p in pairs(s) do if type(p.type) == 'string' then if p.type == "Integer" then p.class =dest.classes.Integer elseif p.type == "String" then p.class = dest.classes.String elseif p.type == "Float" then p.class = dest.classes.Float elseif p.type == "Boolean" then p.class = dest.classes.Boolean elseif dest.enum[p.type] then p.class = dest.classes.Enum p.type = dest.enum[p.type] elseif dest.struct[p.type] then p.class = dest.classes.Struct p.type = dest.struct[p.type] end end end end end function module.init(path) local result={} result.classes = { String = { }, Integer = { }, Float = { }, Boolean = { }, Struct = { }, Enum = { } } result.enum = { } result.struct = { } local _api = xml.open(path) if not _api then error(path .. " not found") end loadEnums(_api, result) loadStructs(_api, result) return result end return module
ATF fix: send 'SDL.GetUserFriendlyMessage' via hmiConnection. APPLINK-14546: ATF sometimes doesn't send HMI request.
ATF fix: send 'SDL.GetUserFriendlyMessage' via hmiConnection. APPLINK-14546: ATF sometimes doesn't send HMI request.
Lua
bsd-3-clause
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
328911a2553d576543f5efc221bfee8887580b61
src/tie/src/Shared/Encoding/TieUtils.lua
src/tie/src/Shared/Encoding/TieUtils.lua
--[=[ @class TieUtils ]=] local TieUtils = {} --[=[ Encoding arguments for Tie consumption. Namely this will convert any table into a closure for encoding. @param ... any @return ... any ]=] function TieUtils.encode(...) local results = table.pack(...) for i=1, results.n do if type(results[i]) == "table" then local saved = results[i] results[i] = function() return saved -- Pack into a callback so we can transfer data. end end end return unpack(results, 1, results.n) end --[=[ Encodes a given callback so it can be assigned to a BindableFunction @param callback function ]=] function TieUtils.encodeCallback(callback) assert(type(callback) == "function", "Bad callback") return function(...) return TieUtils.encode(callback(TieUtils.decode(...))) end end --[=[ Encodes a given callback so it can be assigned to a BindableFunction @param bindableFunction BindableFunction @param ... any @return any ]=] function TieUtils.invokeEncodedBindableFunction(bindableFunction, ...) assert(typeof(bindableFunction) == "Instance" and bindableFunction:IsA("BindableFunction"), "Bad bindableFunction") return TieUtils.decode(bindableFunction:Invoke(TieUtils.encode(...))) end --[=[ Decodes arguments for Tie consumption. @param ... any @return ... any ]=] function TieUtils.decode(...) local results = table.pack(...) for i=1, results.n do if type(results[i]) == "function" then results[i] = results[i]() end end return unpack(results, 1, results.n) end return TieUtils
--[=[ @class TieUtils ]=] local TieUtils = {} --[=[ Encoding arguments for Tie consumption. Namely this will convert any table into a closure for encoding. @param ... any @return ... any ]=] function TieUtils.encode(...) local results = table.pack(...) for i=1, results.n do if type(results[i]) == "table" or type(results[i]) == "function" then local saved = results[i] results[i] = function() return saved -- Pack into a callback so we can transfer data. end end end return unpack(results, 1, results.n) end --[=[ Encodes a given callback so it can be assigned to a BindableFunction @param callback function ]=] function TieUtils.encodeCallback(callback) assert(type(callback) == "function", "Bad callback") return function(...) return TieUtils.encode(callback(TieUtils.decode(...))) end end --[=[ Encodes a given callback so it can be assigned to a BindableFunction @param bindableFunction BindableFunction @param ... any @return any ]=] function TieUtils.invokeEncodedBindableFunction(bindableFunction, ...) assert(typeof(bindableFunction) == "Instance" and bindableFunction:IsA("BindableFunction"), "Bad bindableFunction") return TieUtils.decode(bindableFunction:Invoke(TieUtils.encode(...))) end --[=[ Decodes arguments for Tie consumption. @param ... any @return ... any ]=] function TieUtils.decode(...) local results = table.pack(...) for i=1, results.n do if type(results[i]) == "function" then results[i] = results[i]() end end return unpack(results, 1, results.n) end return TieUtils
fix: Fix encoding functions in tie
fix: Fix encoding functions in tie
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
183e7c444df4b08274e7038a34992d18b175bef2
protocols/ipv6/luasrc/model/cbi/admin_network/proto_6in4.lua
protocols/ipv6/luasrc/model/cbi/admin_network/proto_6in4.lua
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This is usually the address of the nearest PoP operated by the tunnel broker")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6addr", translate("Local IPv6 address"), translate("This is the local endpoint address assigned by the tunnel broker, it usually ends with <code>:2</code>")) ip6addr.datatype = "ip6addr" local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("This is the prefix routed to you by the tunnel broker for use by clients")) ip6prefix.datatype = "ip6addr" local update = section:taboption("general", Flag, "_update", translate("Dynamic tunnel"), translate("Enable HE.net dynamic endpoint update")) update.enabled = "1" update.disabled = "0" function update.write() end function update.remove() end function update.cfgvalue(self, section) return (tonumber(m:get(section, "tunnelid")) ~= nil) and self.enabled or self.disabled end tunnelid = section:taboption("general", Value, "tunnelid", translate("Tunnel ID")) tunnelid.datatype = "uinteger" tunnelid:depends("_update", update.enabled) username = section:taboption("general", Value, "username", translate("HE.net user ID"), translate("This is the 32 byte hex encoded user ID, not the login name")) username:depends("_update", update.enabled) updatekey = section:taboption("general", Value, "updatekey", translate("HE.net update key")) updatekey.updatekey = true updatekey:depends("_update", update.enabled) password = section:taboption("general", Value, "password", translate("HE.net password")) password.password = true password:depends("_update", update.enabled) defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This is usually the address of the nearest PoP operated by the tunnel broker")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6addr", translate("Local IPv6 address"), translate("This is the local endpoint address assigned by the tunnel broker, it usually ends with <code>:2</code>")) ip6addr.datatype = "ip6addr" local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"), translate("This is the prefix routed to you by the tunnel broker for use by clients")) ip6prefix.datatype = "ip6addr" local update = section:taboption("general", Flag, "_update", translate("Dynamic tunnel"), translate("Enable HE.net dynamic endpoint update")) update.enabled = "1" update.disabled = "0" function update.write() end function update.remove() end function update.cfgvalue(self, section) return (tonumber(m:get(section, "tunnelid")) ~= nil) and self.enabled or self.disabled end tunnelid = section:taboption("general", Value, "tunnelid", translate("Tunnel ID")) tunnelid.datatype = "uinteger" tunnelid:depends("_update", update.enabled) username = section:taboption("general", Value, "username", translate("HE.net user ID"), translate("HE.net login ID")) username:depends("_update", update.enabled) updatekey = section:taboption("general", Value, "updatekey", translate("HE.net update key")) updatekey.updatekey = true updatekey:depends("_update", update.enabled) password = section:taboption("general", Value, "password", translate("HE.net password")) password.password = true password:depends("_update", update.enabled) defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
Fix the caption for HE.net Login ID
Fix the caption for HE.net Login ID
Lua
apache-2.0
gwlim/luci,gwlim/luci,gwlim/luci,gwlim/luci,gwlim/luci,gwlim/luci,gwlim/luci
7cacc1641ef316688ee92eb84d5d3934e1bbe48d
mstat.lua
mstat.lua
local dkim_space = 0 local from_space = 1 local envfrom_space = 2 local sender_ip_space = 3 local dkim_msgtype_ts_space = 4 local dkim_senderip_space = 5 local field_last = 4 local field_count = 10 local timeout = 0.006 local max_attempts = 5 local function increment_stat3(space, key, subject, timestamp) retry = true count = 0 while retry do status, result = pcall(box.update, space, key, '=p', field_last, timestamp) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple tuple = {} for i = 2, field_last do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = subject tuple[3] = timestamp tuple[4] = timestamp box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end -- BEG deprecated interface function increment_or_insert(space, key, field) retry = true count = 0 while retry do status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function increment_or_insert_2(space, key, field, element1, element2) retry = true count = 0 while retry do status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple tuple = {} for i = 2, field_count + 2 do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 tuple[field_count + 1] = element1 tuple[field_count + 2] = element2 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function update_or_insert(space, key, subject, timestamp) increment_stat3(space, key, subject, timestamp) end -- END deprecated interface local function increment_stat(space, key, users, spam_users, prob_spam_users, inv_users) retry = true count = 0 while retry do status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = users tuple[3] = spam_users tuple[4] = prob_spam_users tuple[5] = inv_users box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end local function increment_stat2(space, key, element1, element2, users, spam_users, prob_spam_users, inv_users) retry = true count = 0 while retry do status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple tuple = {} for i = 2, field_count + 2 do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = users tuple[3] = spam_users tuple[4] = prob_spam_users tuple[5] = inv_users tuple[field_count + 1] = element1 tuple[field_count + 2] = element2 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end function mstat_add( msgtype, sender_ip, from_domain, envfrom_domain, dkim_domain, subject, users, spam_users, prob_spam_users, inv_users, timestamp) users = box.unpack('i', users) spam_users = box.unpack('i', spam_users) prob_spam_users = box.unpack('i', prob_spam_users) inv_users = box.unpack('i', inv_users) timestamp = box.unpack('i', timestamp) local time_str = os.date("_%d_%m_%y", timestamp) if envfrom_domain ~= "" then increment_stat(envfrom_space, envfrom_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if from_domain ~= "" then increment_stat(from_space, from_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" then increment_stat(dkim_space, dkim_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if sender_ip ~= "" then increment_stat(sender_ip_space, sender_ip..time_str, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" and sender_ip ~= "" then increment_stat2(dkim_senderip_space, dkim_domain.."|"..sender_ip..time_str, dkim_domain, sender_ip, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" and msgtype ~= "" then local element = dkim_domain..":"..msgtype..time_str increment_stat(dkim_space, element, users, spam_users, prob_spam_users, inv_users) if subject == "" then subject = " " end increment_stat3(dkim_msgtype_ts_space, element, subject, timestamp) end end
local dkim_space = 0 local from_space = 1 local envfrom_space = 2 local sender_ip_space = 3 local dkim_msgtype_ts_space = 4 local dkim_senderip_space = 5 local field_last = 4 local field_count = 10 local timeout = 0.006 local max_attempts = 5 local function increment_stat3(space, key, subject, timestamp) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '=p', field_last, timestamp) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_last do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = subject tuple[3] = timestamp tuple[4] = timestamp box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end -- BEG deprecated interface function increment_or_insert(space, key, field) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function increment_or_insert_2(space, key, field, element1, element2) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count + 2 do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 tuple[field_count + 1] = element1 tuple[field_count + 2] = element2 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function update_or_insert(space, key, subject, timestamp) increment_stat3(space, key, subject, timestamp) end -- END deprecated interface local function increment_stat(space, key, users, spam_users, prob_spam_users, inv_users) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = users tuple[3] = spam_users tuple[4] = prob_spam_users tuple[5] = inv_users box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end local function increment_stat2(space, key, element1, element2, users, spam_users, prob_spam_users, inv_users) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count + 2 do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = users tuple[3] = spam_users tuple[4] = prob_spam_users tuple[5] = inv_users tuple[field_count + 1] = element1 tuple[field_count + 2] = element2 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end function mstat_add( msgtype, sender_ip, from_domain, envfrom_domain, dkim_domain, subject, users, spam_users, prob_spam_users, inv_users, timestamp) users = box.unpack('i', users) spam_users = box.unpack('i', spam_users) prob_spam_users = box.unpack('i', prob_spam_users) inv_users = box.unpack('i', inv_users) timestamp = box.unpack('i', timestamp) local time_str = os.date("_%d_%m_%y", timestamp) if envfrom_domain ~= "" then increment_stat(envfrom_space, envfrom_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if from_domain ~= "" then increment_stat(from_space, from_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" then increment_stat(dkim_space, dkim_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if sender_ip ~= "" then increment_stat(sender_ip_space, sender_ip..time_str, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" and sender_ip ~= "" then increment_stat2(dkim_senderip_space, dkim_domain.."|"..sender_ip..time_str, dkim_domain, sender_ip, users, spam_users, prob_spam_users, inv_users) end if dkim_domain ~= "" and msgtype ~= "" then local element = dkim_domain..":"..msgtype..time_str increment_stat(dkim_space, element, users, spam_users, prob_spam_users, inv_users) if subject == "" then subject = " " end increment_stat3(dkim_msgtype_ts_space, element, subject, timestamp) end end
fix variable scoping in mstat.lua
fix variable scoping in mstat.lua
Lua
bsd-2-clause
BHYCHIK/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua,mailru/tntlua,derElektrobesen/tntlua
ea15b7b9865b5f927e6fd176eb8202b130962f53
src/cosy/logger.lua
src/cosy/logger.lua
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = {} if _G.js then local logger = _G.window.console function Logger.debug (t) logger:log ("DEBUG: " .. I18n (t)) end function Logger.info (t) logger:log ("INFO: " .. I18n (t)) end function Logger.warning (t) logger:log ("WARNING: " .. I18n (t)) end function Logger.error (t) logger:log ("ERROR: " .. I18n (t)) end elseif Loader.nolog then function Logger.debug () end function Logger.info () end function Logger.warning () end function Logger.error () end elseif Loader.logfile then local logging = require "logging" require "logging.file" local logger = logging.file (Loader.logfile, "%Y-%m-%d") function Logger.debug (t) logger:debug (I18n (t)) end function Logger.info (t) logger:info (I18n (t)) end function Logger.warning (t) logger:warn (I18n (t)) end function Logger.error (t) logger:error (I18n (t)) end else local logging = require "logging" logging.console = require "logging.console" local logger = logging.console "%message\n" local colors = require "ansicolors" function Logger.debug (t) logger:debug (colors ("%{dim cyan}" .. I18n (t))) end function Logger.info (t) logger:info (colors ("%{green}" .. I18n (t))) end function Logger.warning (t) logger:warn (colors ("%{yellow}" .. I18n (t))) end function Logger.error (t) logger:error (colors ("%{white redbg}" .. I18n (t))) end end return Logger
local Loader = require "cosy.loader" local I18n = require "cosy.i18n" local Logger = {} local i18n = I18n.load {} if _G.js then local logger = _G.window.console function Logger.debug (t) logger:log ("DEBUG: " .. i18n (t).message) end function Logger.info (t) logger:log ("INFO: " .. i18n (t).message) end function Logger.warning (t) logger:log ("WARNING: " .. i18n (t).message) end function Logger.error (t) logger:log ("ERROR: " .. i18n (t).message) end elseif Loader.nolog then function Logger.debug () end function Logger.info () end function Logger.warning () end function Logger.error () end elseif Loader.logfile then local logging = require "logging" require "logging.file" local logger = logging.file (Loader.logfile, "%Y-%m-%d") function Logger.debug (t) logger:debug (i18n (t).message) end function Logger.info (t) logger:info (i18n (t).message) end function Logger.warning (t) logger:warn (i18n (t).message) end function Logger.error (t) logger:error (i18n (t).message) end else local logging = require "logging" logging.console = require "logging.console" local logger = logging.console "%message\n" local colors = require "ansicolors" function Logger.debug (t) logger:debug (colors ("%{dim cyan}" .. i18n (t).message)) end function Logger.info (t) logger:info (colors ("%{green}" .. i18n (t).message)) end function Logger.warning (t) logger:warn (colors ("%{yellow}" .. i18n (t).message)) end function Logger.error (t) logger:error (colors ("%{white redbg}" .. i18n (t).message)) end end return Logger
Fix logger with i18n.
Fix logger with i18n.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
f9ec9980b56d7165d83f048b928e5665f281bae3
Quadtastic/Window.lua
Quadtastic/Window.lua
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local Layout = require(current_folder .. ".Layout") local imgui = require(current_folder .. ".imgui") local Frame = require(current_folder .. ".Frame") local Window = {} local bordersize = 7 Window.start = function(gui_state, x, y, w, h, options) -- Store the window's bounds in the gui state gui_state.window_bounds = {x = x, y = y, w = w, h = h} gui_state.window_transform = gui_state.transform:clone() local active = options and options.active or true if not active then imgui.cover_input(gui_state) end local margin = options and options.margin or 4 if not (options and options.borderless) then Frame.start(gui_state, x, y, w, h, {margin = 0, quads = gui_state.style.quads.window_border, bordersize = bordersize}) end -- Enclose the window's content in a Layout Layout.start(gui_state, margin, margin, w - 2*margin, h - 2*margin) end Window.finish = function(gui_state, x, y, dragging, options) local active = options and options.active or true -- Finish the layout that encloses the content Layout.finish(gui_state) local w = gui_state.layout.adv_x + (options and options.margin or 4) * 2 local h = gui_state.layout.adv_y + (options and options.margin or 4) * 2 local dx, dy if not (options and options.borderless) then Frame.finish(gui_state, nil, nil, {margin = options and options.margin or 4}) if active then -- Check if the user moved the window if imgui.was_mouse_pressed(gui_state, x, y, w, bordersize) then dragging = true elseif dragging and not (gui_state.input and gui_state.input.mouse.buttons and gui_state.input.mouse.buttons[1] and gui_state.input.mouse.buttons[1].pressed) then dragging = false end if dragging and gui_state.input then local mdx, mdy = gui_state.input.mouse.dx, gui_state.input.mouse.dy dx, dy = gui_state.transform:unproject_dimensions(mdx, mdy) end end else end if not active then imgui.uncover_input(gui_state) end -- Remove the window bounds gui_state.window_bounds = nil gui_state.window_transform = nil return w, h, dx, dy, dragging end return Window
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local Layout = require(current_folder .. ".Layout") local imgui = require(current_folder .. ".imgui") local Frame = require(current_folder .. ".Frame") local Window = {} local bordersize = 7 Window.start = function(gui_state, x, y, w, h, options) -- Store the window's bounds in the gui state gui_state.window_bounds = {x = x, y = y, w = w, h = h} gui_state.window_transform = gui_state.transform:clone() local active = options and options.active or true if not active then imgui.cover_input(gui_state) end if not (options and options.borderless) then Frame.start(gui_state, x, y, w, h, {margin = 0, quads = gui_state.style.quads.window_border, bordersize = bordersize}) end local margin = options and options.margin or 4 -- Enclose the window's content in a Layout Layout.start(gui_state, margin, margin, w - 2*margin, h - 2*margin) if not (options and options.borderless) then -- Shift content past the top border gui_state.layout.adv_y = bordersize Layout.next(gui_state, "|") end end Window.finish = function(gui_state, x, y, dragging, options) local active = options and options.active or true -- Finish the layout that encloses the content Layout.finish(gui_state) local w = gui_state.layout.adv_x + (options and options.margin or 4) * 2 local h = gui_state.layout.adv_y + (options and options.margin or 4) * 2 local dx, dy if not (options and options.borderless) then Frame.finish(gui_state, nil, nil, {margin = options and options.margin or 4}) h = h + bordersize if active then -- Check if the user moved the window if imgui.was_mouse_pressed(gui_state, x, y, w, bordersize) then dragging = true elseif dragging and not (gui_state.input and gui_state.input.mouse.buttons and gui_state.input.mouse.buttons[1] and gui_state.input.mouse.buttons[1].pressed) then dragging = false end if dragging and gui_state.input then local mdx, mdy = gui_state.input.mouse.dx, gui_state.input.mouse.dy dx, dy = gui_state.transform:unproject_dimensions(mdx, mdy) end end else end if not active then imgui.uncover_input(gui_state) end -- Remove the window bounds gui_state.window_bounds = nil gui_state.window_transform = nil return w, h, dx, dy, dragging end return Window
Fix issue in Window where content could be drawn over border
Fix issue in Window where content could be drawn over border
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
a7073f1d81bc28314d48255f0ca94a69f2c3eac9
share/lua/website/vimeo.lua
share/lua/website/vimeo.lua
-- libquvi-scripts -- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- -- NOTE: Vimeo is picky about the user-agent string. -- local Vimeo = {} -- Utility functions unique to this script. -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "vimeo%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/%d+$"}) return r end -- Query available formats. function query_formats(self) local config = Vimeo.get_config(self) local formats = Vimeo.iter_formats(self, config) local t = {} for _,v in pairs(formats) do table.insert(t, Vimeo.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse media URL. function parse(self) self.host_id = "vimeo" local c = Vimeo.get_config(self) self.title = c:match('"title":"(.-)"') or error("no match: media title") self.duration = (tonumber(c:match('"duration":(%d+)')) or 0) * 1000 local U = require 'quvi/util' local s = c:match('"thumbnail":"(.-)"') or '' if #s >0 then self.thumbnail_url = U.slash_unescape(s) end local formats = Vimeo.iter_formats(self, c) local format = U.choose_format(self, formats, Vimeo.choose_best, Vimeo.choose_default, Vimeo.to_s) or error("unable to choose format") self.url = {format.url or error("no match: media URL")} return self end -- -- Utility functions -- function Vimeo.normalize(url) url = url:gsub("player.", "") -- player.vimeo.com url = url:gsub("/video/", "/") -- player.vimeo.com return url end function Vimeo.get_config(self) self.page_url = Vimeo.normalize(self.page_url) self.id = self.page_url:match('vimeo.com/(%d+)') or error("no match: media ID") local c_url = "player.vimeo.com/config/" .. self.id local c = quvi.fetch(c_url, {fetch_type='config'}) if c:match('<error>') then local s = c:match('<message>(.-)[\n<]') error( (not s) and "no match: error message" or s ) end return c end function Vimeo.iter_formats(self, config) local t = {} local qualities = config:match('"qualities":%[(.-)%]') for q in qualities:gmatch('"(.-)"') do Vimeo.add_format(self, config, t, q) end return t end function Vimeo.add_format(self, config, t, quality) table.insert(t, {quality=quality, url=Vimeo.to_url(self, config, quality)}) end function Vimeo.choose_best(t) -- First 'hd', then 'sd' and 'mobile' last. for _,v in pairs(t) do local f = Vimeo.to_s(v) for _,q in pairs({'hd','sd','mobile'}) do if f == q then return v end end end return Vimeo.choose_default(t) end function Vimeo.choose_default(t) for _,v in pairs(t) do if Vimeo.to_s(v) == 'sd' then return v end -- Default to 'sd'. end return t[1] -- Or whatever is the first. end function Vimeo.to_url(self, config, quality) local sign = config:match('"signature":"(.-)"') or error("no match: request signature") local exp = config:match('"timestamp":(%d+)') or error("no match: request timestamp") local s = "http://player.vimeo.com/play_redirect?clip_id=%s" .. "&sig=%s&time=%s&quality=%s&type=moogaloop_local" return string.format(s, self.id, sign, exp, quality) end function Vimeo.to_s(t) return string.format("%s", t.quality) end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- -- NOTE: Vimeo is picky about the user-agent string. -- local Vimeo = {} -- Utility functions unique to this script. -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "vimeo%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/%d+$"}) return r end -- Query available formats. function query_formats(self) local config = Vimeo.get_config(self) local formats = Vimeo.iter_formats(self, config) local t = {} for _,v in pairs(formats) do table.insert(t, Vimeo.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse media URL. function parse(self) self.host_id = "vimeo" local c = Vimeo.get_config(self) local s = c:match('"title":(.-),') or error("no match: media title") local U = require 'quvi/util' self.title = U.slash_unescape(s):gsub('^"',''):gsub('"$','') self.duration = (tonumber(c:match('"duration":(%d+)')) or 0) * 1000 local s = c:match('"thumbnail":"(.-)"') or '' if #s >0 then self.thumbnail_url = U.slash_unescape(s) end local formats = Vimeo.iter_formats(self, c) local format = U.choose_format(self, formats, Vimeo.choose_best, Vimeo.choose_default, Vimeo.to_s) or error("unable to choose format") self.url = {format.url or error("no match: media stream URL")} return self end -- -- Utility functions -- function Vimeo.normalize(url) url = url:gsub("player.", "") -- player.vimeo.com url = url:gsub("/video/", "/") -- player.vimeo.com return url end function Vimeo.get_config(self) self.page_url = Vimeo.normalize(self.page_url) self.id = self.page_url:match('vimeo.com/(%d+)') or error("no match: media ID") local c_url = "player.vimeo.com/config/" .. self.id local c = quvi.fetch(c_url, {fetch_type='config'}) if c:match('<error>') then local s = c:match('<message>(.-)[\n<]') error( (not s) and "no match: error message" or s ) end return c end function Vimeo.iter_formats(self, config) local t = {} local qualities = config:match('"qualities":%[(.-)%]') for q in qualities:gmatch('"(.-)"') do Vimeo.add_format(self, config, t, q) end return t end function Vimeo.add_format(self, config, t, quality) table.insert(t, {quality=quality, url=Vimeo.to_url(self, config, quality)}) end function Vimeo.choose_best(t) -- First 'hd', then 'sd' and 'mobile' last. for _,v in pairs(t) do local f = Vimeo.to_s(v) for _,q in pairs({'hd','sd','mobile'}) do if f == q then return v end end end return Vimeo.choose_default(t) end function Vimeo.choose_default(t) for _,v in pairs(t) do if Vimeo.to_s(v) == 'sd' then return v end -- Default to 'sd'. end return t[1] -- Or whatever is the first. end function Vimeo.to_url(self, config, quality) local sign = config:match('"signature":"(.-)"') or error("no match: request signature") local exp = config:match('"timestamp":(%d+)') or error("no match: request timestamp") local s = "http://player.vimeo.com/play_redirect?clip_id=%s" .. "&sig=%s&time=%s&quality=%s&type=moogaloop_local" return string.format(s, self.id, sign, exp, quality) end function Vimeo.to_s(t) return string.format("%s", t.quality) end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: vimeo.lua: Title parsing
FIX: vimeo.lua: Title parsing JSON may contain escaped characters, e.g. double-quotation marks (").
Lua
agpl-3.0
legatvs/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts
83bd64d36dc5ce2853f236bd394f6375dfc61432
kong/plugins/session/storage/kong.lua
kong/plugins/session/storage/kong.lua
local singletons = require "kong.singletons" local concat = table.concat local tonumber = tonumber local setmetatable = setmetatable local floor = math.floor local now = ngx.now local kong_storage = {} kong_storage.__index = kong_storage function kong_storage.new(config) return setmetatable({ dao = singletons.dao, encode = config.encoder.encode, decode = config.encoder.decode, delimiter = config.cookie.delimiter, lifetime = config.cookie.lifetime, }, kong_storage) end local function load_session(sid) local rows, err = singletons.dao.sessions:find_all { session_id = sid } if not rows then return nil, err end return rows[1] end function kong_storage:get(sid) local cache_key = self.dao.sessions:cache_key(sid) local s, err = singletons.cache:get(cache_key, nil, load_session, sid) if err then ngx.log(ngx.ERR, "Error finding session:", err) end return s, err end function kong_storage:cookie(c) local r, d = {}, self.delimiter local i, p, s, e = 1, 1, c:find(d, 1, true) while s do if i > 2 then return nil end r[i] = c:sub(p, e - 1) i, p = i + 1, e + 1 s, e = c:find(d, p, true) end if i ~= 3 then return nil end r[3] = c:sub(p) return r end function kong_storage:open(cookie, lifetime) local c = self:cookie(cookie) if c and c[1] and c[2] and c[3] then local id, expires, hmac = self.decode(c[1]), tonumber(c[2]), self.decode(c[3]) local data if ngx.get_phase() ~= 'header_filter' then local db_s = self:get(c[1]) if db_s then data = self.decode(db_s.data) expires = db_s.expires end end return id, expires, data, hmac end return nil, "invalid" end function kong_storage:save(id, expires, data, hmac) local life, key = floor(expires - now()), self.encode(id) local value = concat({key, expires, self.encode(hmac)}, self.delimiter) if life > 0 then ngx.timer.at(0, function() local err, _ = self.dao.sessions:insert({ session_id = key, data = self.encode(data), expires = expires, }, { ttl = self.lifetime }) if err then ngx.log(ngx.ERR, "Error inserting session: ", err) end end) return value end return nil, "expired" end function kong_storage:destroy(id) local db_s = self:get(id) if not db_s then return end local _, err = self.dao.sessions:delete({ id = db_s.id }) if err then ngx.log(ngx.ERR, "Error deleting session: ", err) end end -- used by regenerate strategy to expire old sessions during renewal function kong_storage:ttl(id, ttl) local s = self:get(self.encode(id)) if s then local _, err = self.dao.sessions:update({ id = s.id }, {session_id = s.session_id}, { ttl = ttl }) if err then ngx.log(ngx.ERR, "Error updating session: ", err) end end end return kong_storage
local singletons = require "kong.singletons" local concat = table.concat local tonumber = tonumber local setmetatable = setmetatable local floor = math.floor local now = ngx.now local kong_storage = {} kong_storage.__index = kong_storage function kong_storage.new(config) return setmetatable({ dao = singletons.dao, encode = config.encoder.encode, decode = config.encoder.decode, delimiter = config.cookie.delimiter, lifetime = config.cookie.lifetime, }, kong_storage) end local function load_session(sid) local rows, err = singletons.dao.sessions:find_all { session_id = sid } if not rows then return nil, err end return rows[1] end function kong_storage:get(sid) local cache_key = self.dao.sessions:cache_key(sid) local s, err = singletons.cache:get(cache_key, nil, load_session, sid) if err then ngx.log(ngx.ERR, "Error finding session:", err) end return s, err end function kong_storage:cookie(c) local r, d = {}, self.delimiter local i, p, s, e = 1, 1, c:find(d, 1, true) while s do if i > 2 then return nil end r[i] = c:sub(p, e - 1) i, p = i + 1, e + 1 s, e = c:find(d, p, true) end if i ~= 3 then return nil end r[3] = c:sub(p) return r end function kong_storage:open(cookie, lifetime) local c = self:cookie(cookie) if c and c[1] and c[2] and c[3] then local id, expires, hmac = self.decode(c[1]), tonumber(c[2]), self.decode(c[3]) local data if ngx.get_phase() ~= 'header_filter' then local db_s = self:get(c[1]) if db_s then data = self.decode(db_s.data) expires = db_s.expires end end return id, expires, data, hmac end return nil, "invalid" end function kong_storage:insert_session(sid, data, expires) local _, err = self.dao.sessions:insert({ session_id = sid, data = data, expires = expires, }, { ttl = self.lifetime }) if err then ngx.log(ngx.ERR, "Error inserting session: ", err) end end function kong_storage:update_session(sid, options, ttl) local _, err = self.dao.sessions:update({ id = sid }, options, { ttl = ttl }) if err then ngx.log(ngx.ERR, "Error updating session: ", err) end end function kong_storage:save(id, expires, data, hmac) local life, key = floor(expires - now()), self.encode(id) local value = concat({key, expires, self.encode(hmac)}, self.delimiter) if life > 0 then if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() self:insert_session(key, self.encode(data), expires) end) else self:insert_session(key, self.encode(data), expires) end return value end return nil, "expired" end function kong_storage:destroy(id) local db_s = self:get(id) if not db_s then return end local _, err = self.dao.sessions:delete({ id = db_s.id }) if err then ngx.log(ngx.ERR, "Error deleting session: ", err) end end -- used by regenerate strategy to expire old sessions during renewal function kong_storage:ttl(id, ttl) local s = self:get(self.encode(id)) if s then if ngx.get_phase() == 'header_filter' then ngx.timer.at(0, function() self:update_session(s.id, {session_id = s.session_id}, ttl) end) else self:update_session(s.id, {session_id = s.session_id}, ttl) end end end return kong_storage
fix(session) add timers only in header_filter phase
fix(session) add timers only in header_filter phase
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
e0fff0f298e923133c1bbec78353833cd8c2aff0
lua/lualine/themes/hydrangea.lua
lua/lualine/themes/hydrangea.lua
-- Palette (LCH values were measured in GIMP 2.10.4) local base03 = ("#171c26", 235) -- L = 10, C = 8, H = 270 local base02 = ("#232833", 236) -- L = 16, C = 8, H = 270 local base01 = ("#303540", 238) -- L = 22, C = 8, H = 270 local base00 = ("#4b505d", 241) -- L = 28, C = 8, H = 270 local base0 = ("#465166", 252) -- L = 34, C = 14, H = 270 local base1 = ("#8791a9", 252) -- L = 60, C = 14, H = 270 local base2 = ("#cdd8f1", 252) -- L = 86, C = 14, H = 270 local red01 = ("#681c36", 52) -- L = ?, C = ?, H = ? local red1 = ("#e91e63", 161) -- L = ?, C = ?, H = ? local green1 = ("#98bf00", 106) -- L = ?, C = ?, H = ? local teal01 = ("#013435", 23) -- L = ?, C = ?, H = ? local teal2 = ("#019c9c", 44) -- L = ?, C = ?, H = ? local cyan01 = ("#023342", 23) -- L = 19, C = 18, H = 232 local cyan1 = ("#1398bf", 38) -- L = 58, C = 38, H = 232 local cyan3 = ("#9bdffc", 153) -- L = 85, C = 27, H = 232 local blue1 = ("#3a69bf", 68) -- L = ?, C = ?, H = ? local blue2 = ('#8baafe', 111) -- L = ?, C = ?, H = ? local blue3 = ('#c9d4fd', 189) -- L = ?, C = ?, H = ? local violet1 = ("#996ddb", 98) -- L = ?, C = ?, H = ? local violet2 = ("#c398fe", 183) -- L = ?, C = ?, H = ? local violet3 = ("#e2ccfe", 225) -- L = ?, C = ?, H = ? local magenta01 = ("#491f38", 89) -- L = 19, C = 30, H = 343 local magenta1 = ("#c44597", 162) -- L = 50, C = 60, H = 343 local magenta3 = ("#ffc3e4", 218) -- L = 85, C = 27, H = 343 return { normal = { a = { fg = base03, bg = base2, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, insert = { a = { fg = base03, bg = cyan1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, visual = { a = { fg = base03, bg = green1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, replace = { a = { fg = base03, bg = violet1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, inactive = { a = { fg = base03, bg = base1, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, }
-- Palette (LCH values were measured in GIMP 2.10.4) local base03 = '#171c26' -- L = 10, C = 8, H = 270 local base02 = '#232833' -- L = 16, C = 8, H = 270 local base01 = '#303540' -- L = 22, C = 8, H = 270 local base00 = '#4b505d' -- L = 28, C = 8, H = 270 local base0 = '#465166' -- L = 34, C = 14, H = 270 local base1 = '#8791a9' -- L = 60, C = 14, H = 270 local base2 = '#cdd8f1' -- L = 86, C = 14, H = 270 local red01 = '#681c36' -- L = ?, C = ?, H = ? local red1 = '#e91e63' -- L = ?, C = ?, H = ? local green1 = '#98bf00' -- L = ?, C = ?, H = ? local teal01 = '#013435' -- L = ?, C = ?, H = ? local teal2 = '#019c9c' -- L = ?, C = ?, H = ? local cyan01 = '#023342' -- L = 19, C = 18, H = 232 local cyan1 = '#1398bf' -- L = 58, C = 38, H = 232 local cyan3 = '#9bdffc' -- L = 85, C = 27, H = 232 local blue1 = '#3a69bf' -- L = ?, C = ?, H = ? local blue2 = '#8baafe' -- L = ?, C = ?, H = ? local blue3 = '#c9d4fd' -- L = ?, C = ?, H = ? local violet1 = '#996ddb' -- L = ?, C = ?, H = ? local violet2 = '#c398fe' -- L = ?, C = ?, H = ? local violet3 = '#e2ccfe' -- L = ?, C = ?, H = ? local magenta01 = '#491f38' -- L = 19, C = 30, H = 343 local magenta1 = '#c44597' -- L = 50, C = 60, H = 343 local magenta3 = '#ffc3e4' -- L = 85, C = 27, H = 343 return { normal = { a = { fg = base03, bg = base2, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, insert = { a = { fg = base03, bg = cyan1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, visual = { a = { fg = base03, bg = green1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, replace = { a = { fg = base03, bg = violet1, gui = 'bold' }, b = { fg = base03, bg = base1 }, }, inactive = { a = { fg = base03, bg = base1, gui = 'bold' }, b = { fg = base03, bg = base1 }, c = { fg = base03, bg = base0 }, }, }
Fix using Python tuple notation
Fix using Python tuple notation
Lua
mit
yuttie/hydrangea-vim
fc53fed6b2c64490f1f415f910ab96cf9e8cda74
trackedTurtle.lua
trackedTurtle.lua
-- dont let buggy robot escape you maxMoves=5000 local pos,dir function log(s) local file = fs.open("log", "a") local postxt="nopos" if (pos~=nil) then postxt=pos.x..","..pos.y..","..pos.z end local ls = postxt .. " " .. (" "):rep(stackDepthCurrent or 0)..textutils.serialize(s).."\n" write(ls) file.write(ls) file.close() end function ensure_locate() while (dir==nil) do locate() sleep(1) end end function locate_gps_or_manual() local x,y,z=gps.locate(5) if (x==nil) then log("gps.locate failed. nedd manual entry") print("enter coords in form: x y z") local str = read() require("split.lua") local t=split(str," ") return t[1],t[2],t[3] end end function locate() log("finding position...") local x,y,z=locate_gps_or_manual(5) if (x==nil) then log("locate_gps_or_manual failed") return end log("gps located: "..(x or "nil")..","..(y or "nil")..","..(z or "nil")) pos=vector.new(x,y,z) if (pos.x==nil) then log("failed. TODO manual entry of position and/or ask to continue without this") return end log("finding face direction...") if (turtle.forward()) then local x2,y2,z2=locate_gps_or_manual() turtle.back() if (x2==nil) then log("failed. went out of gps range?") return end if (z2<pos.z) then dir=0 log("north") return end if (z2>pos.z) then dir=2 log("south") return end if (x2>pos.x) then dir=1 log("east") return end if (x2<pos.x) then dir=3 log("west") return end log("??? not possible. we moved but possition did not changed?") return else log("failed. TODO try go other directions and/or ask to continue without this") return end end local vectorsByDirPlus1 = { vector.new(0,0,-1), vector.new(1,0,0), vector.new(0,0,1), vector.new(-1,0,0) } function getDirVector() return vectorsByDirPlus1[dir+1] end function getPos() return pos end function myForward() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.forward() if (ret) then pos=pos+getDirVector() end return ret end return false end function myBack() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.back() if (ret) then pos=pos-getDirVector() end return ret end return false end function myUp() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.up() pos.y=pos.y+1 return ret end return false end function myDown() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.down() pos.y=pos.y-1 return ret end return false end function myTurnLeft() ensure_locate() turtle.turnLeft() dir=(dir-1)%4 end function myTurnRight() ensure_locate() turtle.turnRight() dir=(dir+1)%4 end trackedTurtle={ forward=myForward, back=myBack, turnLeft=myTurnLeft, turnRight=myTurnRight, up=myUp, down=myDown, dig=turtle.dig, digUp=turtle.digUp, digDown=turtle.digDown, select=turtle.select, compare=turtle.compare, compareDown=turtle.compareDown, compareUp=turtle.compareUp, compareTo=turtle.compareTo, transferTo=turtle.transferTo, detect=turtle.detect, detectDown=turtle.detectDown, detectUp=turtle.detectUp, getItemCount=turtle.getItemCount, drop=turtle.drop } function setMaxMoves(n) maxMoves=n end log("trackedTurtle api loaded.")
-- dont let buggy robot escape you maxMoves=5000 local pos,dir function log(s) local file = fs.open("log", "a") local postxt="nopos" if (pos~=nil) then postxt=pos.x..","..pos.y..","..pos.z end local ls = postxt .. " " .. (" "):rep(stackDepthCurrent or 0)..textutils.serialize(s).."\n" write(ls) file.write(ls) file.close() end function ensure_locate() while (dir==nil) do locate() sleep(1) end end function locate_gps_or_manual() local x,y,z=gps.locate(5) if (x==nil) then log("gps.locate failed. nedd manual entry") print("enter coords in form: x y z") local str = read() require("split.lua") local t=split(str," ") return t[1],t[2],t[3] else return x,y,z end end function locate() log("finding position...") local x,y,z=locate_gps_or_manual(5) if (x==nil) then log("lua failed") return end log("gps located: "..(x or "nil")..","..(y or "nil")..","..(z or "nil")) pos=vector.new(x,y,z) if (pos.x==nil) then log("failed. TODO manual entry of position and/or ask to continue without this") return end log("finding face direction...") if (turtle.forward()) then local x2,y2,z2=locate_gps_or_manual() turtle.back() if (x2==nil) then log("failed. went out of gps range?") return end if (z2<pos.z) then dir=0 log("north") return end if (z2>pos.z) then dir=2 log("south") return end if (x2>pos.x) then dir=1 log("east") return end if (x2<pos.x) then dir=3 log("west") return end log("??? not possible. we moved but possition did not changed?") return else log("failed. TODO try go other directions and/or ask to continue without this") return end end local vectorsByDirPlus1 = { vector.new(0,0,-1), vector.new(1,0,0), vector.new(0,0,1), vector.new(-1,0,0) } function getDirVector() return vectorsByDirPlus1[dir+1] end function getPos() return pos end function myForward() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.forward() if (ret) then pos=pos+getDirVector() end return ret end return false end function myBack() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.back() if (ret) then pos=pos-getDirVector() end return ret end return false end function myUp() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.up() pos.y=pos.y+1 return ret end return false end function myDown() ensure_locate() maxMoves=maxMoves-1 if (maxMoves>0) then local ret = turtle.down() pos.y=pos.y-1 return ret end return false end function myTurnLeft() ensure_locate() turtle.turnLeft() dir=(dir-1)%4 end function myTurnRight() ensure_locate() turtle.turnRight() dir=(dir+1)%4 end trackedTurtle={ forward=myForward, back=myBack, turnLeft=myTurnLeft, turnRight=myTurnRight, up=myUp, down=myDown, dig=turtle.dig, digUp=turtle.digUp, digDown=turtle.digDown, select=turtle.select, compare=turtle.compare, compareDown=turtle.compareDown, compareUp=turtle.compareUp, compareTo=turtle.compareTo, transferTo=turtle.transferTo, detect=turtle.detect, detectDown=turtle.detectDown, detectUp=turtle.detectUp, getItemCount=turtle.getItemCount, drop=turtle.drop } function setMaxMoves(n) maxMoves=n end log("trackedTurtle api loaded.")
gps locate code fix
gps locate code fix
Lua
mit
keneo/swarm
24487cf47dd161c9a06cfeefd66956bbaa9ae567
lua/conf/cmp.lua
lua/conf/cmp.lua
local ok, cmp, ls ok, cmp = pcall(require, "cmp") if not ok then return end ok, ls = pcall(require, "luasnip") if not ok then return end local utils = require("custom.utils") local function filtered_bufnrs() local ft = vim.bo.filetype local bufs = {} for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do if vim.api.nvim_buf_is_loaded(bufnr) and vim.api.nvim_buf_get_option(bufnr, "filetype") == ft then table.insert(bufs, bufnr) end end -- for _, winid in ipairs(vim.api.nvim_tabpage_list_wins(0)) do -- local win_bufnr = vim.api.nvim_win_get_buf(winid) -- if not vim.tbl_contains(bufs, win_bufnr) then -- table.insert(bufs, win_bufnr) -- end -- end return bufs end local function complete(func) if cmp.visible() then func() else cmp.complete() end end local function complete_or_next() complete(cmp.select_next_item) end local function complete_or_prev() complete(cmp.select_prev_item) end local function jump_forward(fallback) if ls.jumpable(1) then ls.jump(1) else fallback() end end local function jump_backward() if ls.jumpable(-1) then ls.jump(-1) end end local function expand_or_confirm() if cmp.visible() and cmp.get_selected_entry() then cmp.confirm({ select = false }) elseif ls.expandable() then ls.expand() else if vim.fn.pumvisible() then vim.api.nvim_feedkeys(utils.from_keycode("<C-y>"), "n", true) end end end local function expand_or_confirm_cr(fallback) if cmp.visible() and cmp.get_active_entry() then cmp.confirm({ select = false }) else fallback() end end local function open_pum(key) if cmp.visible() then cmp.close() end vim.api.nvim_feedkeys(utils.from_keycode(key), "n", true) end local function scroll_docs(amount, fallback) if cmp.visible() then cmp.scroll_docs(amount) else fallback() end end ls.config.set_config({ history = false, }) -- ls.snippets = { -- all = { -- }, -- } local sdir = vim.fn.stdpath("data") .. "/site/pack/packer/start/friendly-snippets" require "luasnip.loaders.from_vscode".lazy_load({ paths = { sdir } }) -- CMP SETUP cmp.setup({ preselect = cmp.PreselectMode.None, snippet = { expand = function(args) ls.lsp_expand(args.body) end, }, mapping = { ["<C-p>"] = cmp.mapping(function(fallback) scroll_docs(-4, fallback) end), ["<C-n>"] = cmp.mapping(function(fallback) scroll_docs(4, fallback) end), ["<C-j>"] = cmp.mapping(complete_or_next), ["<C-k>"] = cmp.mapping(complete_or_prev), ["<C-i>"] = cmp.mapping(jump_forward, { "i", "s" }), ["<Tab>"] = cmp.mapping(jump_forward, { "i", "s" }), ["<M-i>"] = cmp.mapping(jump_backward, { "i", "s" }), ["<C-y>"] = cmp.config.disable, ["<C-e>"] = cmp.mapping(cmp.mapping.abort()), ["<C-l>"] = cmp.mapping(expand_or_confirm), ["<CR>"] = cmp.mapping(expand_or_confirm_cr), ["<C-x><C-o>"] = cmp.mapping(function() open_pum("<C-x><C-o>") end), ["<C-x><C-l>"] = cmp.mapping(function() open_pum("<C-x><C-l>") end), ["<C-x><C-f>"] = cmp.mapping(function() open_pum("<C-x><C-f>") end), }, sources = cmp.config.sources({ { name = "nvim_lsp" }, { name = "luasnip" }, { name = "buffer", option = { get_bufnrs = filtered_bufnrs } }, { name = "path" }, }) })
local ok, cmp, ls ok, cmp = pcall(require, "cmp") if not ok then return end ok, ls = pcall(require, "luasnip") if not ok then return end local utils = require("custom.utils") local function filtered_bufnrs() local ft = vim.bo.filetype local bufs = {} for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do if vim.api.nvim_buf_is_loaded(bufnr) and vim.api.nvim_buf_get_option(bufnr, "filetype") == ft then table.insert(bufs, bufnr) end end -- for _, winid in ipairs(vim.api.nvim_tabpage_list_wins(0)) do -- local win_bufnr = vim.api.nvim_win_get_buf(winid) -- if not vim.tbl_contains(bufs, win_bufnr) then -- table.insert(bufs, win_bufnr) -- end -- end return bufs end local function complete(func) if cmp.visible() then func() else cmp.complete() end end local function complete_or_next() complete(cmp.select_next_item) end local function complete_or_prev() complete(cmp.select_prev_item) end local function jump_forward(fallback) if ls.jumpable(1) then ls.jump(1) else fallback() end end local function jump_backward() if ls.jumpable(-1) then ls.jump(-1) end end local function expand_or_confirm() if cmp.visible() and cmp.get_selected_entry() then cmp.confirm({ select = false }) elseif ls.expandable() then ls.expand() else if vim.fn.pumvisible() then vim.api.nvim_feedkeys(utils.from_keycode("<C-y>"), "n", true) end end end local function expand_or_confirm_cr(fallback) if cmp.visible() and cmp.get_active_entry() then cmp.confirm({ select = false }) else fallback() end end local function open_pum(key) if cmp.visible() then cmp.close() end vim.api.nvim_feedkeys(utils.from_keycode(key), "n", true) end local function scroll_docs(amount, fallback) if cmp.visible() then cmp.scroll_docs(amount) else fallback() end end ls.config.set_config({ history = false, }) -- ls.snippets = { -- all = { -- }, -- } local sdir = vim.fn.stdpath("data") .. "/site/pack/packer/start/friendly-snippets" require "luasnip.loaders.from_vscode".lazy_load({ paths = { sdir } }) -- CMP SETUP cmp.setup({ preselect = cmp.PreselectMode.None, snippet = { expand = function(args) ls.lsp_expand(args.body) end, }, mapping = { ["<C-p>"] = cmp.mapping(function(fallback) scroll_docs(-4, fallback) end), ["<C-n>"] = cmp.mapping(function(fallback) scroll_docs(4, fallback) end), ["<C-j>"] = cmp.mapping(complete_or_next), ["<C-k>"] = cmp.mapping(complete_or_prev), ["<C-i>"] = cmp.mapping(jump_forward, { "i", "s" }), ["<Tab>"] = cmp.mapping(jump_forward, { "i", "s" }), ["<M-i>"] = cmp.mapping(jump_backward, { "i", "s" }), ["<C-y>"] = cmp.config.disable, ["<C-e>"] = cmp.mapping(cmp.mapping.abort()), ["<C-l>"] = cmp.mapping(expand_or_confirm), ["<CR>"] = cmp.mapping(expand_or_confirm_cr), ["<C-x><C-o>"] = cmp.mapping(function() open_pum("<C-x><C-o>") end), ["<C-x><C-l>"] = cmp.mapping(function() open_pum("<C-x><C-l>") end), ["<C-x><C-f>"] = cmp.mapping(function() open_pum("<C-x><C-f>") end), }, sources = cmp.config.sources({ { name = "nvim_lsp" }, { name = "luasnip" }, { name = "buffer", option = { get_bufnrs = filtered_bufnrs } }, { name = "path" }, }) }) -- lisp local function jump_forward_parinfer() if ls.jumpable(1) then ls.jump(1) else parinfer.tab(true) end end local function jump_backward_parinfer() if ls.jumpable(-1) then ls.jump(-1) else parinfer.tab(false) end end cmp.setup.filetype({ "lisp" }, { mapping = { ["<C-i>"] = cmp.mapping(jump_forward_parinfer, { "i", "s" }), ["<Tab>"] = cmp.mapping(jump_forward_parinfer, { "i", "s" }), ["<M-i>"] = cmp.mapping(jump_backward_parinfer, { "i", "s" }), } })
Fix lisp parinfer mappings
Fix lisp parinfer mappings
Lua
mit
monkoose/neovim-setup
fb3dd69f03eea0c828f6a2dcf91fbc17fb65dfc5
lualib/redis.lua
lualib/redis.lua
local skynet = require "skynet" local socket = require "socket" local config = require "config" local redis_conf = skynet.getenv "redis" local name = config (redis_conf) local readline = socket.readline local readbytes = socket.read local table = table local string = string local redis = {} local command = {} local meta = { __index = command, __gc = function(self) socket.close(self.__handle) end, } function redis.connect(dbname) local db_conf = name[dbname] local fd = assert(socket.open(db_conf.host, db_conf.port or 6379)) local r = setmetatable( { __handle = fd, __mode = false }, meta ) if db_conf.db ~= nil then r:select(db_conf.db) end return r end function command:disconnect() socket.close(self.__handle) setmetatable(self, nil) end local function compose_message(msg) local lines = { "*" .. #msg } for _,v in ipairs(msg) do local t = type(v) if t == "number" then v = tostring(v) elseif t == "userdata" then v = int64.tostring(int64.new(v),10) end table.insert(lines,"$"..#v) table.insert(lines,v) end table.insert(lines,"") local cmd = table.concat(lines,"\r\n") return cmd end local redcmd = {} redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} for i = 1,n do local line = readline(fd,"\r\n") local bytes = tonumber(string.sub(line,2)) if bytes < 0 then table.insert(bulk, nil) else local data = readbytes(fd, bytes + 2) table.insert(bulk, string.sub(data,1,-3)) end end return true, bulk end redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = readbytes(fd, bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, ...) local fd = self.__handle if self.__mode then socket.write(fd, compose_message { cmd, ... }) self.__batch = self.__batch + 1 else socket.lock(fd) socket.write(fd, compose_message { cmd, ... }) local ok, ret = read_response(fd) socket.unlock(fd) assert(ok, ret) return ret end end t[k] = f return f end}) function command:exists(key) assert(not self.__mode, "exists can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "EXISTS", key }) local ok, exists = read_response(fd) socket.unlock(fd) assert(ok, exists) return exists ~= 0 end function command:sismember(key, value) assert(not self.__mode, "sismember can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "SISMEMBER", key, value }) local ok, ismember = read_response(fd) socket.unlock(fd) assert(ok, ismember) return ismember ~= 0 end function command:batch(mode) if mode == "end" then local fd = self.__handle if self.__mode == "read" then local allok = true local allret = {} for i = 1, self.__batch do local ok, ret = read_response(fd) allok = allok and ok allret[i] = ret end socket.unlock(self.__handle) assert(allok, "batch read failed") self.__mode = false return allret else local allok = true for i = 1, self.__batch do local ok = read_response(fd) allok = allok and ok end socket.unlock(self.__handle) self.__mode = false return allok end else assert(mode == "read" or mode == "write") self.__mode = mode self.__batch = 0 socket.lock(self.__handle) end end return redis
local skynet = require "skynet" local socket = require "socket" local config = require "config" local redis_conf = skynet.getenv "redis" local name = config (redis_conf) local readline = socket.readline local readbytes = socket.read local table = table local string = string local redis = {} local command = {} local meta = { __index = command, __gc = function(self) socket.close(self.__handle) end, } function redis.connect(dbname) local db_conf = name[dbname] local fd = assert(socket.open(db_conf.host, db_conf.port or 6379)) local r = setmetatable( { __handle = fd, __mode = false }, meta ) if db_conf.db ~= nil then r:select(db_conf.db) end return r end function command:disconnect() socket.close(self.__handle) setmetatable(self, nil) end local function compose_message(msg) local lines = { "*" .. #msg } for _,v in ipairs(msg) do local t = type(v) if t == "number" then v = tostring(v) elseif t == "userdata" then v = int64.tostring(int64.new(v),10) end table.insert(lines,"$"..#v) table.insert(lines,v) end table.insert(lines,"") local cmd = table.concat(lines,"\r\n") return cmd end local redcmd = {} redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} for i = 1,n do local line = readline(fd,"\r\n") local bytes = tonumber(string.sub(line,2)) if bytes >= 0 then local data = readbytes(fd, bytes + 2) -- bulk[i] = nil when bytes < 0 bulk[i] = string.sub(data,1,-3) end end return true, bulk end redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = readbytes(fd, bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, ...) local fd = self.__handle if self.__mode then socket.write(fd, compose_message { cmd, ... }) self.__batch = self.__batch + 1 else socket.lock(fd) socket.write(fd, compose_message { cmd, ... }) local ok, ret = read_response(fd) socket.unlock(fd) assert(ok, ret) return ret end end t[k] = f return f end}) function command:exists(key) assert(not self.__mode, "exists can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "EXISTS", key }) local ok, exists = read_response(fd) socket.unlock(fd) assert(ok, exists) return exists ~= 0 end function command:sismember(key, value) assert(not self.__mode, "sismember can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "SISMEMBER", key, value }) local ok, ismember = read_response(fd) socket.unlock(fd) assert(ok, ismember) return ismember ~= 0 end function command:batch(mode) if mode == "end" then local fd = self.__handle if self.__mode == "read" then local allok = true local allret = {} for i = 1, self.__batch do local ok, ret = read_response(fd) allok = allok and ok allret[i] = ret end socket.unlock(self.__handle) assert(allok, "batch read failed") self.__mode = false return allret else local allok = true for i = 1, self.__batch do local ok = read_response(fd) allok = allok and ok end socket.unlock(self.__handle) self.__mode = false return allok end else assert(mode == "read" or mode == "write") self.__mode = mode self.__batch = 0 socket.lock(self.__handle) end end return redis
bugfix: don't use table.insert when nil can be insert
bugfix: don't use table.insert when nil can be insert
Lua
mit
sdgdsffdsfff/skynet,korialuo/skynet,togolwb/skynet,letmefly/skynet,iskygame/skynet,chfg007/skynet,KAndQ/skynet,vizewang/skynet,zhoukk/skynet,leezhongshan/skynet,plsytj/skynet,lawnight/skynet,cloudwu/skynet,xjdrew/skynet,catinred2/skynet,gitfancode/skynet,codingabc/skynet,plsytj/skynet,boyuegame/skynet,javachengwc/skynet,cmingjian/skynet,chuenlungwang/skynet,zzh442856860/skynet-Note,gitfancode/skynet,Ding8222/skynet,bttscut/skynet,sanikoyes/skynet,bttscut/skynet,codingabc/skynet,hongling0/skynet,Markal128/skynet,zhouxiaoxiaoxujian/skynet,Zirpon/skynet,ruleless/skynet,javachengwc/skynet,bingo235/skynet,your-gatsby/skynet,sanikoyes/skynet,jiuaiwo1314/skynet,letmefly/skynet,hongling0/skynet,ypengju/skynet_comment,pichina/skynet,czlc/skynet,ilylia/skynet,kyle-wang/skynet,yunGit/skynet,liuxuezhan/skynet,ypengju/skynet_comment,zzh442856860/skynet-Note,zzh442856860/skynet,winglsh/skynet,JiessieDawn/skynet,KAndQ/skynet,KittyCookie/skynet,wangyi0226/skynet,your-gatsby/skynet,LuffyPan/skynet,bigrpg/skynet,microcai/skynet,MRunFoss/skynet,chenjiansnail/skynet,nightcj/mmo,Zirpon/skynet,zhouxiaoxiaoxujian/skynet,Markal128/skynet,lawnight/skynet,felixdae/skynet,KittyCookie/skynet,puXiaoyi/skynet,leezhongshan/skynet,zhoukk/skynet,cuit-zhaxin/skynet,sundream/skynet,LiangMa/skynet,catinred2/skynet,zhangshiqian1214/skynet,czlc/skynet,xjdrew/skynet,JiessieDawn/skynet,samael65535/skynet,longmian/skynet,asanosoyokaze/skynet,sanikoyes/skynet,MoZhonghua/skynet,qyli/test,yunGit/skynet,zzh442856860/skynet-Note,longmian/skynet,your-gatsby/skynet,xcjmine/skynet,ludi1991/skynet,liuxuezhan/skynet,nightcj/mmo,gitfancode/skynet,bigrpg/skynet,fhaoquan/skynet,kyle-wang/skynet,MetSystem/skynet,peimin/skynet_v0.1_with_notes,qyli/test,xinjuncoding/skynet,letmefly/skynet,zhaijialong/skynet,hongling0/skynet,QuiQiJingFeng/skynet,asanosoyokaze/skynet,zhangshiqian1214/skynet,firedtoad/skynet,pigparadise/skynet,yunGit/skynet,jxlczjp77/skynet,ludi1991/skynet,xinjuncoding/skynet,matinJ/skynet,ilylia/skynet,zhangshiqian1214/skynet,wangyi0226/skynet,xinmingyao/skynet,zhaijialong/skynet,longmian/skynet,LiangMa/skynet,cuit-zhaxin/skynet,kebo/skynet,yinjun322/skynet,microcai/skynet,korialuo/skynet,ag6ag/skynet,enulex/skynet,liuxuezhan/skynet,u20024804/skynet,matinJ/skynet,pigparadise/skynet,catinred2/skynet,cdd990/skynet,zhoukk/skynet,cdd990/skynet,cpascal/skynet,wangjunwei01/skynet,jiuaiwo1314/skynet,great90/skynet,asanosoyokaze/skynet,MoZhonghua/skynet,ag6ag/skynet,zzh442856860/skynet,cpascal/skynet,harryzeng/skynet,ruleless/skynet,dymx101/skynet,felixdae/skynet,vizewang/skynet,winglsh/skynet,lc412/skynet,KAndQ/skynet,u20024804/skynet,cuit-zhaxin/skynet,plsytj/skynet,peimin/skynet,kebo/skynet,ilylia/skynet,vizewang/skynet,icetoggle/skynet,chuenlungwang/skynet,peimin/skynet,enulex/skynet,xinjuncoding/skynet,zhangshiqian1214/skynet,javachengwc/skynet,lynx-seu/skynet,helling34/skynet,jxlczjp77/skynet,Ding8222/skynet,lawnight/skynet,fhaoquan/skynet,peimin/skynet_v0.1_with_notes,qyli/test,QuiQiJingFeng/skynet,helling34/skynet,cdd990/skynet,bingo235/skynet,JiessieDawn/skynet,lc412/skynet,xinmingyao/skynet,pigparadise/skynet,great90/skynet,iskygame/skynet,togolwb/skynet,LiangMa/skynet,rainfiel/skynet,rainfiel/skynet,MetSystem/skynet,Markal128/skynet,felixdae/skynet,kyle-wang/skynet,rainfiel/skynet,samael65535/skynet,codingabc/skynet,fztcjjl/skynet,matinJ/skynet,zhouxiaoxiaoxujian/skynet,samael65535/skynet,winglsh/skynet,xubigshu/skynet,lawnight/skynet,ludi1991/skynet,togolwb/skynet,pichina/skynet,zhangshiqian1214/skynet,enulex/skynet,ag6ag/skynet,LuffyPan/skynet,jxlczjp77/skynet,ludi1991/skynet,chenjiansnail/skynet,cloudwu/skynet,MRunFoss/skynet,icetoggle/skynet,fztcjjl/skynet,zzh442856860/skynet,fhaoquan/skynet,zhaijialong/skynet,chuenlungwang/skynet,sdgdsffdsfff/skynet,boyuegame/skynet,czlc/skynet,wangjunwei01/skynet,firedtoad/skynet,liuxuezhan/skynet,Ding8222/skynet,great90/skynet,MetSystem/skynet,MoZhonghua/skynet,iskygame/skynet,bttscut/skynet,xcjmine/skynet,sdgdsffdsfff/skynet,xjdrew/skynet,dymx101/skynet,sundream/skynet,QuiQiJingFeng/skynet,icetoggle/skynet,firedtoad/skynet,harryzeng/skynet,xcjmine/skynet,yinjun322/skynet,wangjunwei01/skynet,wangyi0226/skynet,MRunFoss/skynet,chenjiansnail/skynet,LuffyPan/skynet,bingo235/skynet,ruleless/skynet,lc412/skynet,microcai/skynet,lynx-seu/skynet,u20024804/skynet,zzh442856860/skynet-Note,leezhongshan/skynet,cpascal/skynet,nightcj/mmo,sundream/skynet,helling34/skynet,puXiaoyi/skynet,zhangshiqian1214/skynet,letmefly/skynet,Zirpon/skynet,lynx-seu/skynet,korialuo/skynet,pichina/skynet,boyuegame/skynet,bigrpg/skynet,yinjun322/skynet,chfg007/skynet,cloudwu/skynet,cmingjian/skynet,dymx101/skynet,KittyCookie/skynet,qyli/test,cmingjian/skynet,chfg007/skynet,kebo/skynet,ypengju/skynet_comment,harryzeng/skynet,puXiaoyi/skynet,xubigshu/skynet,fztcjjl/skynet,jiuaiwo1314/skynet
d36f3b6376ffc0f85ad3244ca26d368184dc4572
plugins/mod_groups.lua
plugins/mod_groups.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local groups; local members; local groups_file; local jid, datamanager = require "util.jid", require "util.datamanager"; local jid_bare, jid_prep = jid.bare, jid.prep; local module_host = module:get_host(); function inject_roster_contacts(username, host, roster) module:log("warn", "Injecting group members to roster"); local bare_jid = username.."@"..host; if not members[bare_jid] and not members[false] then return; end -- Not a member of any groups local function import_jids_to_roster(group_name) for jid in pairs(groups[group_name]) do -- Add them to roster --module:log("debug", "processing jid %s in group %s", tostring(jid), tostring(group_name)); if jid ~= bare_jid then if not roster[jid] then roster[jid] = {}; end roster[jid].subscription = "both"; if not roster[jid].groups then roster[jid].groups = { [group_name] = true }; end roster[jid].groups[group_name] = true; roster[jid].persist = false; end end end -- Find groups this JID is a member of if members[bare_jid] then for _, group_name in ipairs(members[bare_jid]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name); end end -- Import public groups if members[false] then for _, group_name in ipairs(members[false]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name); end end end function remove_virtual_contacts(username, host, datastore, data) if host == module_host and datastore == "roster" then local new_roster = {}; for jid, contact in pairs(data) do if contact.persist ~= false then new_roster[jid] = contact; end end return username, host, datastore, new_roster; end return username, host, datastore, data; end function module.load() groups_file = config.get(module:get_host(), "core", "groups_file"); if not groups_file then return; end module:hook("roster-load", inject_roster_contacts); datamanager.add_callback(remove_virtual_contacts); groups = { default = {} }; members = { }; local curr_group = "default"; for line in io.lines(groups_file) do if line:match("^%s*%[.-%]%s*$") then curr_group = line:match("^%s*%[(.-)%]%s*$"); if curr_group:match("^%+") then curr_group = curr_group:gsub("^%+", ""); if not members[false] then members[false] = {}; end members[false][#members[false]+1] = curr_group; -- Is a public group end module:log("debug", "New group: %s", tostring(curr_group)); groups[curr_group] = groups[curr_group] or {}; else -- Add JID local jid = jid_prep(line); if jid then module:log("debug", "New member of %s: %s", tostring(curr_group), tostring(jid)); groups[curr_group][jid] = true; members[jid] = members[jid] or {}; members[jid][#members[jid]+1] = curr_group; end end end module:log("info", "Groups loaded successfully"); end function module.unload() datamanager.remove_callback(remove_virtual_contacts); end
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local groups; local members; local groups_file; local jid, datamanager = require "util.jid", require "util.datamanager"; local jid_bare, jid_prep = jid.bare, jid.prep; local module_host = module:get_host(); function inject_roster_contacts(username, host, roster) module:log("warn", "Injecting group members to roster"); local bare_jid = username.."@"..host; if not members[bare_jid] and not members[false] then return; end -- Not a member of any groups local function import_jids_to_roster(group_name) for jid in pairs(groups[group_name]) do -- Add them to roster --module:log("debug", "processing jid %s in group %s", tostring(jid), tostring(group_name)); if jid ~= bare_jid then if not roster[jid] then roster[jid] = {}; end roster[jid].subscription = "both"; if not roster[jid].groups then roster[jid].groups = { [group_name] = true }; end roster[jid].groups[group_name] = true; roster[jid].persist = false; end end end -- Find groups this JID is a member of if members[bare_jid] then for _, group_name in ipairs(members[bare_jid]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name); end end -- Import public groups if members[false] then for _, group_name in ipairs(members[false]) do module:log("debug", "Importing group %s", group_name); import_jids_to_roster(group_name); end end if roster[false] then roster[false].version = true; end end function remove_virtual_contacts(username, host, datastore, data) if host == module_host and datastore == "roster" then local new_roster = {}; for jid, contact in pairs(data) do if contact.persist ~= false then new_roster[jid] = contact; end end new_roster[false].version = nil; -- Version is void return username, host, datastore, new_roster; end return username, host, datastore, data; end function module.load() groups_file = config.get(module:get_host(), "core", "groups_file"); if not groups_file then return; end module:hook("roster-load", inject_roster_contacts); datamanager.add_callback(remove_virtual_contacts); groups = { default = {} }; members = { }; local curr_group = "default"; for line in io.lines(groups_file) do if line:match("^%s*%[.-%]%s*$") then curr_group = line:match("^%s*%[(.-)%]%s*$"); if curr_group:match("^%+") then curr_group = curr_group:gsub("^%+", ""); if not members[false] then members[false] = {}; end members[false][#members[false]+1] = curr_group; -- Is a public group end module:log("debug", "New group: %s", tostring(curr_group)); groups[curr_group] = groups[curr_group] or {}; else -- Add JID local jid = jid_prep(line); if jid then module:log("debug", "New member of %s: %s", tostring(curr_group), tostring(jid)); groups[curr_group][jid] = true; members[jid] = members[jid] or {}; members[jid][#members[jid]+1] = curr_group; end end end module:log("info", "Groups loaded successfully"); end function module.unload() datamanager.remove_callback(remove_virtual_contacts); end
mod_groups: Fixes to make compatible with roster versioning - set version to 'true' to indicate that the roster is not being versioned
mod_groups: Fixes to make compatible with roster versioning - set version to 'true' to indicate that the roster is not being versioned
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
cadb311a0f9c2a72bd739c5953479d833eb4ad66
scen_edit/view/dialog/new_project_dialog.lua
scen_edit/view/dialog/new_project_dialog.lua
SB.Include(Path.Join(SB_VIEW_DIR, "editor.lua")) NewProjectDialog = Editor:extends{} function NewProjectDialog:init() self:super("init") self:AddField(StringField({ name = "projectName", title = "Project name:", width = 300, })) local items = VFS.GetMaps() table.insert(items, 1, "SB_Blank_Map") local captions = Table.DeepCopy(items) captions[1] = "Blank" self:AddField(ChoiceField({ name = "mapName", title = "Map:", items = items, captions = captions, width = 300, })) self:AddField(GroupField({ NumericField({ name = "sizeX", title = "Size X:", width = 140, minValue = 1, value = 5, maxValue = 32, }), NumericField({ name = "sizeZ", title = "Size Z:", width = 140, minValue = 1, value = 5, maxValue = 32, }) })) local children = { ScrollPanel:New { x = 0, y = 0, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.stackPanel }, }, } self:Finalize(children, { notMainWindow = true, buttons = { "ok", "cancel" }, width = 400, height = 200, }) end function NewProjectDialog:ConfirmDialog() local projectName = self.fields["projectName"].value if String.Trim(projectName) == "" then SB.HintControls(self.fields["projectName"].components) return end SB.project.mutators = { projectName .. " 1.0" } if self.fields["mapName"].value == "SB_Blank_Map" then SB.project.mapName = "blank_" .. projectName .. " 1.0" SB.project.randomMapOptions = { mapSeed = 1, new_map_x = self.fields["sizeX"].value, new_map_z = self.fields["sizeZ"].value, } else SB.project.mapName = self.fields.mapName.value end SB.project:SaveProjectInfo(projectName) local cmd = ReloadIntoProjectCommand(SB.project.path, false) SB.commandManager:execute(cmd, true) end function NewProjectDialog:OnFieldChange(name, value) if name == "mapName" then if value == "SB_Blank_Map" then self:SetInvisibleFields() else self:SetInvisibleFields("sizeX", "sizeZ") end end end
SB.Include(Path.Join(SB_VIEW_DIR, "editor.lua")) NewProjectDialog = Editor:extends{} function NewProjectDialog:init() self:super("init") self:AddField(StringField({ name = "projectName", title = "Project name:", width = 300, })) local items = VFS.GetMaps() table.insert(items, 1, "SB_Blank_Map") local captions = Table.DeepCopy(items) captions[1] = "Blank" self:AddField(ChoiceField({ name = "mapName", title = "Map:", items = items, captions = captions, width = 300, })) self:AddField(GroupField({ NumericField({ name = "sizeX", title = "Size X:", width = 140, minValue = 1, value = 5, maxValue = 32, }), NumericField({ name = "sizeZ", title = "Size Z:", width = 140, minValue = 1, value = 5, maxValue = 32, }) })) local children = { ScrollPanel:New { x = 0, y = 0, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.stackPanel }, }, } self:Finalize(children, { notMainWindow = true, buttons = { "ok", "cancel" }, width = 400, height = 200, }) end function NewProjectDialog:ConfirmDialog() local projectName = self.fields["projectName"].value if String.Trim(projectName) == "" then SB.HintControls(self.fields["projectName"].components) return end SB.project.mutators = { projectName .. " 1.0" } if self.fields["mapName"].value == "SB_Blank_Map" then -- We add a randomly generated name to the project prefix to avoid this bug -- Caching of generated maps: -- 1. Make a project named "test" of size 4x4 -- 2. Delete project while in same Spring -- 3. Make a project named "test" of size 3x5 -- 4. Expected: New project of 3x5 will be loaded. Actual: Project of 4x4 will be loaded. -- A. Quitting Spring after step 3. and loading test will properly load the 3x5 project. SB.project.mapName = "blank_" .. tostring(math.random(1, 1000000)) .. projectName .. " 1.0" SB.project.randomMapOptions = { mapSeed = 1, new_map_x = self.fields["sizeX"].value, new_map_z = self.fields["sizeZ"].value, } else SB.project.mapName = self.fields.mapName.value end local _, path = Project.GenerateNamePath(projectName) if SB.DirExists(path) then SB.HintControls(self.fields["projectName"].components) Log.Error("Project \"" .. tostring(projectName) .. "\" already exists.") return end SB.project:GenerateNewProjectInfo(projectName) local cmd = ReloadIntoProjectCommand(SB.project.path, false) SB.commandManager:execute(cmd, true) end function NewProjectDialog:OnFieldChange(name, value) if name == "mapName" then if value == "SB_Blank_Map" then self:SetInvisibleFields() else self:SetInvisibleFields("sizeX", "sizeZ") end end end
Prevent generating projets over existing ones Fix caching issue with generated maps
Prevent generating projets over existing ones Fix caching issue with generated maps
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
8834ac200a4b8b728b28d958b291eb69014bc06b
scripts/tundra/syntax/native.lua
scripts/tundra/syntax/native.lua
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra 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 3 of the License, or -- (at your option) any later version. -- -- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local util = require "tundra.util" local nodegen = require "tundra.nodegen" local path = require "tundra.path" local _native_mt = nodegen.create_eval_subclass { DeclToEnvMappings = { Libs = "LIBS", Defines = "CPPDEFS", Includes = "CPPPATH", Frameworks = "FRAMEWORKS", LibPaths = "LIBPATH", }, } local _object_mt = nodegen.create_eval_subclass({ Suffix = "$(OBJSUFFIX)", Prefix = "", Action = "$(OBJCOM)", Label = "Object $(@)", }, _native_mt) local _program_mt = nodegen.create_eval_subclass({ Suffix = "$(PROGSUFFIX)", Prefix = "$(PROGPREFIX)", Action = "$(PROGCOM)", Label = "Program $(@)", }, _native_mt) local _staticlib_mt = nodegen.create_eval_subclass({ Suffix = "$(LIBSUFFIX)", Prefix = "$(LIBPREFIX)", Action = "$(LIBCOM)", Label = "StaticLibrary $(@)", }, _native_mt) local _shlib_mt = nodegen.create_eval_subclass({ Suffix = "$(SHLIBSUFFIX)", Prefix = "$(SHLIBPREFIX)", Action = "$(SHLIBCOM)", Label = "SharedLibrary $(@)", }, _native_mt) local _extlib_mt = nodegen.create_eval_subclass({ Suffix = "", Prefix = "", Label = "", }, _native_mt) local _is_native_mt = util.make_lookup_table { _object_mt, _program_mt, _staticlib_mt, _shlib_mt, _extlib_mt } function _native_mt:customize_env(env, raw_data) if env:get('GENERATE_PDB', '0') ~= '0' then env:set('_PDB_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. ".pdb") env:set('_USE_PDB_CC', '$(_USE_PDB_CC_OPT)') env:set('_USE_PDB_LINK', '$(_USE_PDB_LINK_OPT)') end end function _native_mt:create_dag(env, data, input_deps) local build_id = env:get("BUILD_ID") local my_pass = data.Pass local pch = data.PrecompiledHeader local pch_output local gen_pch_node local sources = data.Sources local libsuffix = { env:get("LIBSUFFIX") } -- Link with libraries in dependencies. for _, dep in util.nil_ipairs(data.Depends) do if dep.Keyword == "SharedLibrary" then -- On Win32 toolsets, we need foo.lib -- On UNIX toolsets, we need -lfoo local target = dep.Decl.Target or dep.Decl.Name target = target .. "$(SHLIBLINKSUFFIX)" env:append('LIBS', target) elseif dep.Keyword == "StaticLibrary" then local node = dep:get_dag(env:get_parent()) node:insert_output_files(sources, libsuffix) else --[[ A note about win32 import libraries: It is tempting to add an implicit input dependency on the import library of the linked-to shared library here; but this would be suboptimal: 1. Because there is a dependency between the nodes themselves, the import library generation will always run before this link step is run. Therefore, the import lib will always exist and be updated before this link step runs. 2. Because the import library is regenerated whenever the DLL is relinked we would have to custom-sign it (using a hash of the DLLs export list) to avoid relinking the executable all the time when only the DLL's internals change. 3. The DLL's export list should be available in headers anyway, which is already covered in the compilation of the object files that actually uses those APIs. Therefore the best way right now is to not tell Tundra about the import lib at all and rely on header scanning to pick up API changes. An implicit input dependency would be needed however if someone is doing funky things with their import library (adding non-linker-generated code for example). These cases are so rare that we can safely put them off. ]]-- end end if pch then assert(pch.Source) assert(pch.Header) pch_output = "$(OBJECTDIR)/" .. data.Name .. ".pch" env:set('_PCH_FILE', pch_output) env:set('_USE_PCH', '$(_USE_PCH_OPT)') env:set('_PCH_HEADER', pch.Header) gen_pch_node = env:make_node { Label = "Precompiled header $(@)", Pass = my_pass, Action = "$(PCHCOMPILE)", InputFiles = { pch.Source, pch.Header }, OutputFiles = { pch_output }, } end local aux_outputs = env:get_list("AUX_FILES_" .. self.Label:upper(), {}) if env:get('GENERATE_PDB', '0') ~= '0' then aux_outputs[#aux_outputs + 1] = "$(_PDB_FILE)" end local targets = nil if self.Action then targets = { nodegen.get_target(data, self.Suffix, self.Prefix) } end local deps = {} if gen_pch_node then deps = util.merge_arrays_2(deps, { gen_pch_node }) end deps = util.merge_arrays_2(deps, input_deps) deps = util.uniq(deps) return env:make_node { Label = self.Label, Pass = data.Pass, Action = self.Action, InputFiles = data.Sources, OutputFiles = targets, AuxOutputFiles = aux_outputs, Dependencies = deps, -- Play it safe and delete the output files of this node before re-running it. -- Solves iterative issues with e.g. AR OverwriteOutputs = false, } end local native_blueprint = { Name = { Required = true, Help = "Set output (base) filename", Type = "string", }, Sources = { Required = true, Help = "List of source files", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, Target = { Help = "Override target location", Type = "string", }, PrecompiledHeader = { Help = "Enable precompiled header (if supported)", Type = "table", }, } local external_blueprint = { Name = { Required = true, Help = "Set name of the external library", Type = "string", }, } function _extlib_mt:create_dag(env, data, input_deps) return env:make_node { Label = "Dummy node for " .. data.Name, Pass = data.Pass, Dependencies = input_deps, } end nodegen.add_evaluator("Object", _object_mt, native_blueprint) nodegen.add_evaluator("Program", _program_mt, native_blueprint) nodegen.add_evaluator("StaticLibrary", _staticlib_mt, native_blueprint) nodegen.add_evaluator("SharedLibrary", _shlib_mt, native_blueprint) nodegen.add_evaluator("ExternalLibrary", _extlib_mt, external_blueprint)
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra 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 3 of the License, or -- (at your option) any later version. -- -- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local util = require "tundra.util" local nodegen = require "tundra.nodegen" local path = require "tundra.path" local _native_mt = nodegen.create_eval_subclass { DeclToEnvMappings = { Libs = "LIBS", Defines = "CPPDEFS", Includes = "CPPPATH", Frameworks = "FRAMEWORKS", LibPaths = "LIBPATH", }, } local _object_mt = nodegen.create_eval_subclass({ Suffix = "$(OBJSUFFIX)", Prefix = "", Action = "$(OBJCOM)", Label = "Object $(@)", }, _native_mt) local _program_mt = nodegen.create_eval_subclass({ Suffix = "$(PROGSUFFIX)", Prefix = "$(PROGPREFIX)", Action = "$(PROGCOM)", Label = "Program $(@)", }, _native_mt) local _staticlib_mt = nodegen.create_eval_subclass({ Suffix = "$(LIBSUFFIX)", Prefix = "$(LIBPREFIX)", Action = "$(LIBCOM)", Label = "StaticLibrary $(@)", }, _native_mt) local _shlib_mt = nodegen.create_eval_subclass({ Suffix = "$(SHLIBSUFFIX)", Prefix = "$(SHLIBPREFIX)", Action = "$(SHLIBCOM)", Label = "SharedLibrary $(@)", }, _native_mt) local _extlib_mt = nodegen.create_eval_subclass({ Suffix = "", Prefix = "", Label = "", }, _native_mt) local _is_native_mt = util.make_lookup_table { _object_mt, _program_mt, _staticlib_mt, _shlib_mt, _extlib_mt } function _native_mt:customize_env(env, raw_data) if env:get('GENERATE_PDB', '0') ~= '0' then env:set('_PDB_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. ".pdb") env:set('_USE_PDB_CC', '$(_USE_PDB_CC_OPT)') env:set('_USE_PDB_LINK', '$(_USE_PDB_LINK_OPT)') end local pch = raw_data.PrecompiledHeader if pch then assert(pch.Header) env:set('_PCH_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. ".pch") env:set('_USE_PCH', '$(_USE_PCH_OPT)') env:set('_PCH_HEADER', pch.Header) end end function _native_mt:create_dag(env, data, input_deps) local build_id = env:get("BUILD_ID") local my_pass = data.Pass local pch_output local gen_pch_node local sources = data.Sources local libsuffix = { env:get("LIBSUFFIX") } -- Link with libraries in dependencies. for _, dep in util.nil_ipairs(data.Depends) do if dep.Keyword == "SharedLibrary" then -- On Win32 toolsets, we need foo.lib -- On UNIX toolsets, we need -lfoo local target = dep.Decl.Target or dep.Decl.Name target = target .. "$(SHLIBLINKSUFFIX)" env:append('LIBS', target) elseif dep.Keyword == "StaticLibrary" then local node = dep:get_dag(env:get_parent()) node:insert_output_files(sources, libsuffix) else --[[ A note about win32 import libraries: It is tempting to add an implicit input dependency on the import library of the linked-to shared library here; but this would be suboptimal: 1. Because there is a dependency between the nodes themselves, the import library generation will always run before this link step is run. Therefore, the import lib will always exist and be updated before this link step runs. 2. Because the import library is regenerated whenever the DLL is relinked we would have to custom-sign it (using a hash of the DLLs export list) to avoid relinking the executable all the time when only the DLL's internals change. 3. The DLL's export list should be available in headers anyway, which is already covered in the compilation of the object files that actually uses those APIs. Therefore the best way right now is to not tell Tundra about the import lib at all and rely on header scanning to pick up API changes. An implicit input dependency would be needed however if someone is doing funky things with their import library (adding non-linker-generated code for example). These cases are so rare that we can safely put them off. ]]-- end end local pch = data.PrecompiledHeader if pch then local pch_pass = nil if pch.Pass then pch_pass = nodegen.resolve_pass(pch.Pass) end if not pch_pass then croak("%s: PrecompiledHeader requires a valid Pass", data.Name) end gen_pch_node = env:make_node { Label = "Precompiled header $(@)", Pass = pch_pass, Action = "$(PCHCOMPILE)", InputFiles = { pch.Source, pch.Header }, OutputFiles = { "$(_PCH_FILE)" }, } end local aux_outputs = env:get_list("AUX_FILES_" .. self.Label:upper(), {}) if env:get('GENERATE_PDB', '0') ~= '0' then aux_outputs[#aux_outputs + 1] = "$(_PDB_FILE)" end local targets = nil if self.Action then targets = { nodegen.get_target(data, self.Suffix, self.Prefix) } end local deps = {} if gen_pch_node then deps = util.merge_arrays_2(deps, { gen_pch_node }) end deps = util.merge_arrays_2(deps, input_deps) deps = util.uniq(deps) return env:make_node { Label = self.Label, Pass = data.Pass, Action = self.Action, InputFiles = data.Sources, OutputFiles = targets, AuxOutputFiles = aux_outputs, Dependencies = deps, -- Play it safe and delete the output files of this node before re-running it. -- Solves iterative issues with e.g. AR OverwriteOutputs = false, } end local native_blueprint = { Name = { Required = true, Help = "Set output (base) filename", Type = "string", }, Sources = { Required = true, Help = "List of source files", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, Target = { Help = "Override target location", Type = "string", }, PrecompiledHeader = { Help = "Enable precompiled header (if supported)", Type = "table", }, } local external_blueprint = { Name = { Required = true, Help = "Set name of the external library", Type = "string", }, } function _extlib_mt:create_dag(env, data, input_deps) return env:make_node { Label = "Dummy node for " .. data.Name, Pass = data.Pass, Dependencies = input_deps, } end nodegen.add_evaluator("Object", _object_mt, native_blueprint) nodegen.add_evaluator("Program", _program_mt, native_blueprint) nodegen.add_evaluator("StaticLibrary", _staticlib_mt, native_blueprint) nodegen.add_evaluator("SharedLibrary", _shlib_mt, native_blueprint) nodegen.add_evaluator("ExternalLibrary", _extlib_mt, external_blueprint)
Fixed PCH env data was not propagated.
Fixed PCH env data was not propagated. PCH env data was set up too late, so it had no effect on implicitly built object files as they are already set up before the create_dag function is called. The PCH env setup is now done in the customize_env function which was added for this purpose.. But I forgot to do it back then!
Lua
mit
deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra
d66b08e0863383ec14c35ecc2556ca80054486a6
share/lua/meta/art/10_googleimage.lua
share/lua/meta/art/10_googleimage.lua
--[[ Gets an artwork from images.google.com $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Replace non alphanumeric char by + function get_query( title ) -- If we have a .EXT remove the extension. str = string.gsub( title, "(.*)%....$", "%1" ) return string.gsub( str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) end -- Return the artwork -- This is disabled because we have too much false positive by the inherent -- nature of this script. function fetch_art_disabled() local meta = vlc.item:metas() if meta["artist"] and meta["album"] then title = meta["artist"].." "..meta["album"] elseif meta["title"] and meta["artist"] then title = meta["artist"].." "..meta["title"] elseif meta["title"] then title = meta["title"] elseif meta["filename"] then title = meta["filename"] else vlc.msg.err("No filename") return nil end fd = vlc.stream( "http://images.google.com/images?q=" .. get_query( title ) ) page = fd:read( 65653 ) fd = nil _, _, arturl = string.find( page, "imgurl=([^&]+)" ) return arturl end
--[[ Gets an artwork from images.google.com $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Replace non alphanumeric char by + function get_query( title ) -- If we have a .EXT remove the extension. str = string.gsub( title, "(.*)%....$", "%1" ) return string.gsub( str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) end -- Return the artwork function fetch_art() -- This is disabled because we have too much false positive by the inherent nature of this script. if true then vlc.msg.dbg("10_googleimage.lua is disabled") return nil end if vlc.input == nil then return nil end local item = vlc.input.item() local meta = item:metas() if meta["artist"] and meta["album"] then title = meta["artist"].." "..meta["album"] elseif meta["artist"] and meta["title"] then title = meta["artist"].." "..meta["title"] elseif meta["title"] then title = meta["title"] elseif meta["filename"] then title = meta["filename"] else vlc.msg.err("No filename") return nil end fd = vlc.stream( "http://images.google.com/images?q=" .. get_query( title ) ) page = fd:read( 65653 ) fd = nil _, _, arturl = string.find( page, "imgurl=([^&]+)" ) return arturl end
Fix GoogleImage warning. Close #3311
Fix GoogleImage warning. Close #3311 Patch by ale5000
Lua
lgpl-2.1
vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1
e47a4921faaecbb1e2710e48bcb36c64221ad6a8
service/multicastd.lua
service/multicastd.lua
local skynet = require "skynet" local mc = require "multicast.core" local datacenter = require "datacenter" local harbor_id = skynet.harbor(skynet.self()) local command = {} local channel = {} local channel_n = {} local channel_remote = {} local channel_id = harbor_id local NORET = {} local function get_address(t, id) local v = assert(datacenter.get("multicast", id)) t[id] = v return v end local node_address = setmetatable({}, { __index = get_address }) -- new LOCAL channel , The low 8bit is the same with harbor_id function command.NEW() while channel[channel_id] do channel_id = mc.nextid(channel_id) end channel[channel_id] = {} channel_n[channel_id] = 0 local ret = channel_id channel_id = mc.nextid(channel_id) return ret end -- MUST call by the owner node of channel, delete a remote channel function command.DELR(source, c) channel[c] = nil channel_n[c] = nil return NORET end -- delete a channel, if the channel is remote, forward the command to the owner node -- otherwise, delete the channel, and call all the remote node, DELR function command.DEL(source, c) local node = c % 256 if node ~= harbor_id then skynet.send(node_address[node], "lua", "DEL", c) return NORET end local remote = channel_remote[c] channel[c] = nil channel_n[c] = nil channel_remote[c] = nil if remote then for node in pairs(remote) do skynet.send(node_address[node], "lua", "DELR", c) end end return NORET end -- forward multicast message to a node (channel id use the session field) local function remote_publish(node, channel, source, ...) skynet.redirect(node_address[node], source, "multicast", channel, ...) end -- publish a message, for local node, use the message pointer (call mc.bind to add the reference) -- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string) local function publish(c , source, pack, size) local group = channel[c] if group == nil or next(group) == nil then -- dead channel, delete the pack. mc.bind returns the pointer in pack local pack = mc.bind(pack, 1) mc.close(pack) return end mc.bind(pack, channel_n[c]) local msg = skynet.tostring(pack, size) for k in pairs(group) do -- the msg is a pointer to the real message, publish pointer in local is ok. skynet.redirect(k, source, "multicast", c , msg) end local remote = channel_remote[c] if remote then -- remote publish should unpack the pack, because we should not publish the pointer out. local _, msg, sz = mc.unpack(pack, size) local msg = skynet.tostring(msg,sz) for node in pairs(remote) do remote_publish(node, c, source, msg) end end end skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = function(msg, sz) return mc.packremote(msg, sz) end, dispatch = publish, } -- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish) -- If the caller is local, call publish function command.PUB(source, c, pack, size) assert(skynet.harbor(source) == harbor_id) local node = c % 256 if node ~= harbor_id then -- remote publish remote_publish(node, c, source, mc.remote(pack)) else publish(c, source, pack,size) end end -- the node (source) subscribe a channel -- MUST call by channel owner node (assert source is not local and channel is create by self) -- If channel is not exist, return true -- Else set channel_remote[channel] true function command.SUBR(source, c) local node = skynet.harbor(source) if not channel[c] then -- channel none exist return true end assert(node ~= harbor_id and c % 256 == harbor_id) local group = channel_remote[c] if group == nil then group = {} channel_remote[c] = group end group[node] = true end -- the service (source) subscribe a channel -- If the channel is remote, node subscribe it by send a SUBR to the owner . function command.SUB(source, c) local node = c % 256 if node ~= harbor_id then -- remote group if channel[c] == nil then if skynet.call(node_address[node], "lua", "SUBR", c) then return end if channel[c] == nil then -- double check, because skynet.call whould yield, other SUB may occur. channel[c] = {} channel_n[c] = 0 end end end local group = channel[c] if group and not group[source] then channel_n[c] = channel_n[c] + 1 group[source] = true end end -- MUST call by a node, unsubscribe a channel function command.USUBR(source, c) local node = skynet.harbor(source) assert(node ~= harbor_id) local group = assert(channel_remote[c]) group[node] = nil return NORET end -- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner function command.USUB(source, c) local group = assert(channel[c]) if group[source] then group[source] = nil channel_n[c] = channel_n[c] - 1 if channel_n[c] == 0 then local node = c % 256 if node ~= harbor_id then -- remote group channel[c] = nil channel_n[c] = nil skynet.send(node_address[node], "lua", "USUBR", c) end end end return NORET end skynet.start(function() skynet.dispatch("lua", function(_,source, cmd, ...) local f = assert(command[cmd]) local result = f(source, ...) if result ~= NORET then skynet.ret(skynet.pack(result)) end end) local self = skynet.self() local id = skynet.harbor(self) assert(datacenter.set("multicast", id, self) == nil) end)
local skynet = require "skynet" local mc = require "multicast.core" local datacenter = require "datacenter" local harbor_id = skynet.harbor(skynet.self()) local command = {} local channel = {} local channel_n = {} local channel_remote = {} local channel_id = harbor_id local NORET = {} local function get_address(t, id) local v = assert(datacenter.get("multicast", id)) t[id] = v return v end local node_address = setmetatable({}, { __index = get_address }) -- new LOCAL channel , The low 8bit is the same with harbor_id function command.NEW() while channel[channel_id] do channel_id = mc.nextid(channel_id) end channel[channel_id] = {} channel_n[channel_id] = 0 local ret = channel_id channel_id = mc.nextid(channel_id) return ret end -- MUST call by the owner node of channel, delete a remote channel function command.DELR(source, c) channel[c] = nil channel_n[c] = nil return NORET end -- delete a channel, if the channel is remote, forward the command to the owner node -- otherwise, delete the channel, and call all the remote node, DELR function command.DEL(source, c) local node = c % 256 if node ~= harbor_id then skynet.send(node_address[node], "lua", "DEL", c) return NORET end local remote = channel_remote[c] channel[c] = nil channel_n[c] = nil channel_remote[c] = nil if remote then for node in pairs(remote) do skynet.send(node_address[node], "lua", "DELR", c) end end return NORET end -- forward multicast message to a node (channel id use the session field) local function remote_publish(node, channel, source, ...) skynet.redirect(node_address[node], source, "multicast", channel, ...) end -- publish a message, for local node, use the message pointer (call mc.bind to add the reference) -- for remote node, call remote_publish. (call mc.unpack and skynet.tostring to convert message pointer to string) local function publish(c , source, pack, size) local remote = channel_remote[c] if remote then -- remote publish should unpack the pack, because we should not publish the pointer out. local _, msg, sz = mc.unpack(pack, size) local msg = skynet.tostring(msg,sz) for node in pairs(remote) do remote_publish(node, c, source, msg) end end local group = channel[c] if group == nil or next(group) == nil then -- dead channel, delete the pack. mc.bind returns the pointer in pack local pack = mc.bind(pack, 1) mc.close(pack) return end mc.bind(pack, channel_n[c]) local msg = skynet.tostring(pack, size) for k in pairs(group) do -- the msg is a pointer to the real message, publish pointer in local is ok. skynet.redirect(k, source, "multicast", c , msg) end end skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = function(msg, sz) return mc.packremote(msg, sz) end, dispatch = publish, } -- publish a message, if the caller is remote, forward the message to the owner node (by remote_publish) -- If the caller is local, call publish function command.PUB(source, c, pack, size) assert(skynet.harbor(source) == harbor_id) local node = c % 256 if node ~= harbor_id then -- remote publish remote_publish(node, c, source, mc.remote(pack)) else publish(c, source, pack,size) end end -- the node (source) subscribe a channel -- MUST call by channel owner node (assert source is not local and channel is create by self) -- If channel is not exist, return true -- Else set channel_remote[channel] true function command.SUBR(source, c) local node = skynet.harbor(source) if not channel[c] then -- channel none exist return true end assert(node ~= harbor_id and c % 256 == harbor_id) local group = channel_remote[c] if group == nil then group = {} channel_remote[c] = group end group[node] = true end -- the service (source) subscribe a channel -- If the channel is remote, node subscribe it by send a SUBR to the owner . function command.SUB(source, c) local node = c % 256 if node ~= harbor_id then -- remote group if channel[c] == nil then if skynet.call(node_address[node], "lua", "SUBR", c) then return end if channel[c] == nil then -- double check, because skynet.call whould yield, other SUB may occur. channel[c] = {} channel_n[c] = 0 end end end local group = channel[c] if group and not group[source] then channel_n[c] = channel_n[c] + 1 group[source] = true end end -- MUST call by a node, unsubscribe a channel function command.USUBR(source, c) local node = skynet.harbor(source) assert(node ~= harbor_id) local group = assert(channel_remote[c]) group[node] = nil return NORET end -- Unsubscribe a channel, if the subscriber is empty and the channel is remote, send USUBR to the channel owner function command.USUB(source, c) local group = assert(channel[c]) if group[source] then group[source] = nil channel_n[c] = channel_n[c] - 1 if channel_n[c] == 0 then local node = c % 256 if node ~= harbor_id then -- remote group channel[c] = nil channel_n[c] = nil skynet.send(node_address[node], "lua", "USUBR", c) end end end return NORET end skynet.start(function() skynet.dispatch("lua", function(_,source, cmd, ...) local f = assert(command[cmd]) local result = f(source, ...) if result ~= NORET then skynet.ret(skynet.pack(result)) end end) local self = skynet.self() local id = skynet.harbor(self) assert(datacenter.set("multicast", id, self) == nil) end)
bugfix. remote publish first, see issue #391
bugfix. remote publish first, see issue #391
Lua
mit
sundream/skynet,cloudwu/skynet,bigrpg/skynet,liuxuezhan/skynet,MRunFoss/skynet,wangyi0226/skynet,liuxuezhan/skynet,xcjmine/skynet,sundream/skynet,icetoggle/skynet,bttscut/skynet,cdd990/skynet,fztcjjl/skynet,kyle-wang/skynet,cloudwu/skynet,jxlczjp77/skynet,bttscut/skynet,letmefly/skynet,hongling0/skynet,asanosoyokaze/skynet,nightcj/mmo,gitfancode/skynet,fztcjjl/skynet,samael65535/skynet,pigparadise/skynet,catinred2/skynet,LiangMa/skynet,korialuo/skynet,korialuo/skynet,xcjmine/skynet,nightcj/mmo,iskygame/skynet,xcjmine/skynet,cmingjian/skynet,codingabc/skynet,ag6ag/skynet,catinred2/skynet,hongling0/skynet,gitfancode/skynet,codingabc/skynet,kyle-wang/skynet,zhouxiaoxiaoxujian/skynet,icetoggle/skynet,xjdrew/skynet,nightcj/mmo,samael65535/skynet,pigparadise/skynet,chuenlungwang/skynet,wangyi0226/skynet,cmingjian/skynet,czlc/skynet,fztcjjl/skynet,ag6ag/skynet,zhangshiqian1214/skynet,asanosoyokaze/skynet,chuenlungwang/skynet,lawnight/skynet,liuxuezhan/skynet,jxlczjp77/skynet,lawnight/skynet,cloudwu/skynet,ypengju/skynet_comment,puXiaoyi/skynet,iskygame/skynet,puXiaoyi/skynet,iskygame/skynet,samael65535/skynet,czlc/skynet,zhouxiaoxiaoxujian/skynet,letmefly/skynet,xinjuncoding/skynet,xinjuncoding/skynet,korialuo/skynet,sanikoyes/skynet,firedtoad/skynet,cdd990/skynet,codingabc/skynet,puXiaoyi/skynet,kyle-wang/skynet,gitfancode/skynet,great90/skynet,wangyi0226/skynet,zhangshiqian1214/skynet,bttscut/skynet,letmefly/skynet,great90/skynet,sanikoyes/skynet,Ding8222/skynet,rainfiel/skynet,Ding8222/skynet,liuxuezhan/skynet,lawnight/skynet,firedtoad/skynet,ypengju/skynet_comment,JiessieDawn/skynet,JiessieDawn/skynet,bingo235/skynet,firedtoad/skynet,cmingjian/skynet,chuenlungwang/skynet,bigrpg/skynet,bingo235/skynet,bingo235/skynet,zhangshiqian1214/skynet,xjdrew/skynet,jxlczjp77/skynet,sundream/skynet,catinred2/skynet,JiessieDawn/skynet,rainfiel/skynet,asanosoyokaze/skynet,MRunFoss/skynet,MRunFoss/skynet,zhoukk/skynet,LiangMa/skynet,icetoggle/skynet,bigrpg/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,zhoukk/skynet,QuiQiJingFeng/skynet,zhangshiqian1214/skynet,czlc/skynet,rainfiel/skynet,ag6ag/skynet,ypengju/skynet_comment,zhouxiaoxiaoxujian/skynet,QuiQiJingFeng/skynet,LiangMa/skynet,xjdrew/skynet,Ding8222/skynet,lawnight/skynet,xinjuncoding/skynet,pigparadise/skynet,hongling0/skynet,great90/skynet,cdd990/skynet,letmefly/skynet,QuiQiJingFeng/skynet,zhoukk/skynet,zhangshiqian1214/skynet
8891d3f0c374c461939690a55ee33e1bf137be3b
admin.lua
admin.lua
--[[ This file is part of ClearTables @author Paul Norman <penorman@mac.com> @copyright 2015-2016 Paul Norman, MIT license ]]-- require "common" --- Normalizes admin tags -- @param v Admin tag value -- @return An integer as a string for the layer tag function admin_level (v) return v and string.find(v, "^%d%d?$") and tonumber(v) <=11 and tonumber(v) > 0 and v or nil end function accept_admin_area(tags) return tags["boundary"] == "administrative" and admin_level(tags["admin_level"]) end function transform_admin_area (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) cols.level = admin_level(tags["admin_level"]) return cols end function admin_area_rels (tags, num_keys) if accept_admin_area(tags) then return 0, tags end return 1, {} end --- Administrative area handling -- @param tags OSM tags -- @param member_tags OSM tags of relation members -- @param membercount number of members -- @param accept function that takes osm keys and returns true if the feature should be in the table -- @param transform function that takes osm keys and returns tags for the tables -- @return filter, cols, member_superseded, boundary, polygon, roads function admin_area_rel_members (tags, member_tags, member_roles, membercount) members_superseeded = {} for i = 1, membercount do members_superseeded[i] = 0 end if (accept_admin_area(tags)) then return 0, transform_admin_area(tags), members_superseeded, 0, 1, 0 end return 1, {}, members_superseeded, 0, 0, 0 end function admin_line_rels (tags, num_keys) if accept_admin_area(tags) then print("accepted rel with name="..tags.name) return 0, tags end return 1, {} end -- Administrative line handling -- @param tags OSM tags -- @param member_tags OSM tags of relation members -- @param membercount number of members -- @param accept function that takes osm keys and returns true if the feature should be in the table -- @param transform function that takes osm keys and returns tags for the tables -- @return filter, cols, member_superseded, boundary, polygon, roads function admin_line_rel_members (tags, member_tags, member_roles, membercount) members_superseeded = {} for i = 1, membercount do members_superseeded[i] = 0 end if (accept_admin_area(tags)) then print("accepted rel members with name="..tags.name) return 0, transform_admin_area(tags), members_superseeded, 0, 0, 0 end return 1, {}, members_superseeded, 0, 0, 0 end
--[[ This file is part of ClearTables @author Paul Norman <penorman@mac.com> @copyright 2015-2016 Paul Norman, MIT license ]]-- require "common" --- Normalizes admin tags -- @param v Admin tag value -- @return An integer as a string for the layer tag function admin_level (v) return v and string.find(v, "^%d%d?$") and tonumber(v) <=11 and tonumber(v) > 0 and v or nil end function accept_admin_area(tags) return tags["boundary"] == "administrative" and admin_level(tags["admin_level"]) end function transform_admin_area (tags) local cols = {} cols.name = tags["name"] cols.names = names(tags) cols.level = admin_level(tags["admin_level"]) return cols end function admin_area_rels (tags, num_keys) if accept_admin_area(tags) then return 0, tags end return 1, {} end --- Administrative area handling -- @param tags OSM tags -- @param member_tags OSM tags of relation members -- @param membercount number of members -- @param accept function that takes osm keys and returns true if the feature should be in the table -- @param transform function that takes osm keys and returns tags for the tables -- @return filter, cols, member_superseded, boundary, polygon, roads function admin_area_rel_members (tags, member_tags, member_roles, membercount) members_superseeded = {} for i = 1, membercount do members_superseeded[i] = 0 end if (accept_admin_area(tags)) then return 0, transform_admin_area(tags), members_superseeded, 0, 1, 0 end return 1, {}, members_superseeded, 0, 0, 0 end function admin_line_rels (tags, num_keys) if accept_admin_area(tags) then return 0, tags end return 1, {} end -- Administrative line handling -- @param tags OSM tags -- @param member_tags OSM tags of relation members -- @param membercount number of members -- @param accept function that takes osm keys and returns true if the feature should be in the table -- @param transform function that takes osm keys and returns tags for the tables -- @return filter, cols, member_superseded, boundary, polygon, roads function admin_line_rel_members (tags, member_tags, member_roles, membercount) members_superseeded = {} for i = 1, membercount do members_superseeded[i] = 0 end if (accept_admin_area(tags)) then return 0, transform_admin_area(tags), members_superseeded, 0, 0, 0 end return 1, {}, members_superseeded, 0, 0, 0 end
Remove stray debug statements
Remove stray debug statements Fixes #52
Lua
mit
pnorman/ClearTables,ClearTables/ClearTables
fc1c3914daf83e5fad80f9d41e53c5e1f7109217
lib/zip.lua
lib/zip.lua
local Fs = require('meta-fs') local Path = require('path') local Zlib = require('../zlib') local band = require('bit').band -- -- walk over entries of a zipball read from `stream` -- local function walk(stream, options, callback) -- defaults if not options then options = {} end if not options.prefix then options.prefix = '' end -- data buffer and current position pointers local buffer = '' local pos = 1 local anchor = 1 -- preserved between calls to parse() -- get big-endian number of specified length local function get_number(bytes) local result = 0 local i = pos + bytes - 1 while i >= pos do result = result * 256 + buffer:byte(i) i = i - 1 end pos = pos + bytes return result end -- get string of specified length local function get_string(len) local result = buffer:sub(pos, pos + len - 1) pos = pos + len return result end -- parse collected buffer local function parse() pos = anchor -- wait until header is available if pos + 30 >= #buffer then return end -- ensure header signature is ok local signature = get_string(4) if signature ~= 'PK\003\004' then -- start of central directory? if signature == 'PK\001\002' then -- unzipping is done stream:emit('end') -- signature is not ok else -- report error stream:emit('error', 'File is not a Zip file') end return end -- read entry data local entry = {} local version = get_number(2) local flags = get_number(2) entry.comp_method = get_number(2) entry.mtime = get_number(4) entry.crc = get_number(4) entry.comp_size = get_number(4) entry.size = get_number(4) -- sanity check local err = nil if band(flags, 0x01) == 0x01 then err = 'File contains encrypted entry' elseif band(flags, 0x0800) == 0x0800 then err = 'File is using UTF8' elseif band(flags, 0x0008) == 0x0008 then err = 'File is using bit 3 trailing data descriptor' elseif entry.comp_size == 0xFFFFFFFF or entry.size == 0xFFFFFFFF then err = 'File is using Zip64 (4gb+ file size)' end if err then stream:emit('error', { code = 'ENOTSUPP', message = err, }) end -- wait until compressed data available local name_len = get_number(2) local extra_len = get_number(2) if pos + name_len + extra_len + entry.comp_size >= #buffer then return end -- read entry name and data entry.name = Path.join(options.prefix, get_string(name_len)) entry.extra = get_string(extra_len) -- TODO: stream compressed data too entry.data = get_string(entry.comp_size) -- shift the buffer, to save memory buffer = buffer:sub(pos) anchor = 1 -- fire 'entry' event stream:emit('entry', entry) -- process next entry parse() end -- -- feed data to parser local function ondata(data) buffer = buffer .. data parse() end stream:on('data', ondata) -- end of stream means we're done ok stream:on('end', function() stream:emit('error') end) -- read error means we're done in error stream:once('error', function(err) stream:remove_listener('data', ondata) callback(err) end) return stream end -- -- inflate and save to file specified zip entry -- local function unzip_entry(entry) -- inflate local text local ok -- comp_method == 0 means data is stored as-is if entry.comp_method > 0 then -- TODO: how to stream data? ok, text = pcall(Zlib.inflate(-15), entry.data, 'finish') if not ok then text = '' end else text = entry.data end -- write inflated entry data -- TODO: strip path components? Fs.mkdir_p(Path.dirname(entry.name), '0755', function(err) Fs.write_file(entry.name, text, function(err) end) end) end -- -- unzip -- local function unzip(stream, path, callback) if type(stream) == 'string' then stream = Fs.create_read_stream(stream) end stream:on('entry', unzip_entry) return walk(stream, { prefix = path }, callback) end -- export return { unzip = unzip, }
local Fs = require('meta-fs') local Path = require('path') local Zlib = require('../zlib') local band = require('bit').band -- -- walk over entries of a zipball read from `stream` -- local function walk(stream, options, callback) -- defaults if not options then options = {} end -- data buffer and current position pointers local buffer = '' local pos = 1 local anchor = 1 -- preserved between calls to parse() -- get big-endian number of specified length local function get_number(bytes) local result = 0 local i = pos + bytes - 1 while i >= pos do result = result * 256 + buffer:byte(i) i = i - 1 end pos = pos + bytes return result end -- get string of specified length local function get_string(len) local result = buffer:sub(pos, pos + len - 1) pos = pos + len return result end -- parse collected buffer local function parse() pos = anchor -- wait until header is available if pos + 30 >= #buffer then return end -- ensure header signature is ok local signature = get_string(4) if signature ~= 'PK\003\004' then -- start of central directory? if signature == 'PK\001\002' then -- unzipping is done stream:emit('end') -- signature is not ok else -- report error stream:emit('error', 'File is not a Zip file') end return end -- read entry data local entry = {} local version = get_number(2) local flags = get_number(2) entry.comp_method = get_number(2) entry.mtime = get_number(4) entry.crc = get_number(4) entry.comp_size = get_number(4) entry.size = get_number(4) -- sanity check local err = nil if band(flags, 0x01) == 0x01 then err = 'File contains encrypted entry' elseif band(flags, 0x0800) == 0x0800 then err = 'File is using UTF8' elseif band(flags, 0x0008) == 0x0008 then err = 'File is using bit 3 trailing data descriptor' elseif entry.comp_size == 0xFFFFFFFF or entry.size == 0xFFFFFFFF then err = 'File is using Zip64 (4gb+ file size)' end if err then stream:emit('error', { code = 'ENOTSUPP', message = err, }) end -- wait until compressed data available local name_len = get_number(2) local extra_len = get_number(2) if pos + name_len + extra_len + entry.comp_size >= #buffer then return end -- read entry name and data local name = get_string(name_len) -- strip `options.strip` leading path chunks if options.strip then name = name:gsub('[^/]*/', '', options.strip) end -- prepend entry name with optional prefix if options.prefix then name = Path.join(options.prefix, name) end entry.name = name -- entry.extra = get_string(extra_len) -- TODO: stream compressed data too entry.data = get_string(entry.comp_size) -- shift the buffer, to save memory buffer = buffer:sub(pos) anchor = 1 -- fire 'entry' event stream:emit('entry', entry) -- process next entry parse() end -- -- feed data to parser local function ondata(data) buffer = buffer .. data parse() end stream:on('data', ondata) -- end of stream means we're done ok stream:on('end', function() stream:emit('error') end) -- read error means we're done in error stream:once('error', function(err) stream:remove_listener('data', ondata) callback(err) end) return stream end -- -- inflate and save to file specified zip entry -- local function unzip_entry(entry) -- inflate local text local ok -- comp_method == 0 means data is stored as-is if entry.comp_method > 0 then -- TODO: how to stream data? ok, text = pcall(Zlib.inflate(-15), entry.data, 'finish') if not ok then text = '' end else text = entry.data end -- write inflated entry data --p(entry.name) Fs.mkdir_p(Path.dirname(entry.name), '0755', function(err) Fs.write_file(entry.name, text, function(err) end) end) end -- -- unzip -- local function unzip(stream, options, callback) if not options then options = {} end if type(stream) == 'string' then stream = Fs.create_read_stream(stream) end stream:on('entry', unzip_entry) return walk(stream, { prefix = options.path, strip = options.strip, }, callback) end -- export return { unzip = unzip, }
unzip takes options. supported path prefix and number of path chunks to strip
unzip takes options. supported path prefix and number of path chunks to strip
Lua
mit
dvv/luvit-balls,dvv/luvit-balls
ed5466e5f0a229f40595480fd74a2fcaa75c3d8c
build/premake5.lua
build/premake5.lua
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. include "Helpers.lua" include "Tests.lua" solution "MonoManagedToNative" configurations { "Debug", "Release" } architecture "x86_64" filter "system:macosx" architecture "x86" filter "configurations:Release" flags { "Optimize" } filter {} characterset "Unicode" symbols "On" local action = _ACTION or "" location (action) objdir (path.join("./", action, "obj")) targetdir (path.join("./", action, "lib", "%{cfg.buildcfg}")) startproject "MonoManagedToNative" include ("../binder") include("../CppSharp/src/Core") include("../CppSharp/src/AST") include("../CppSharp/src/CppParser/Bindings/CSharp") include("../CppSharp/src/Parser") include("../CppSharp/src/Generator") include("../CppSharp/src/Runtime") project "IKVM.Reflection" SetupManagedProject() kind "SharedLib" language "C#" files { "../ikvm/reflect/**.cs" } links { "System", "System.Core", "System.Security" } group "Tests" print("Searching for tests projects...") IncludeDir("../tests")
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. include "Helpers.lua" include "Tests.lua" solution "MonoManagedToNative" configurations { "Debug", "Release" } architecture "x86_64" filter "system:windows" architecture "x86" filter "system:macosx" architecture "x86" filter "configurations:Release" flags { "Optimize" } filter {} characterset "Unicode" symbols "On" local action = _ACTION or "" location (action) objdir (path.join("./", action, "obj")) targetdir (path.join("./", action, "lib", "%{cfg.buildcfg}")) startproject "MonoManagedToNative" include ("../binder") include("../CppSharp/src/Core") include("../CppSharp/src/AST") include("../CppSharp/src/CppParser/Bindings/CSharp") include("../CppSharp/src/Parser") include("../CppSharp/src/Generator") include("../CppSharp/src/Runtime") project "IKVM.Reflection" SetupManagedProject() kind "SharedLib" language "C#" files { "../ikvm/reflect/**.cs" } links { "System", "System.Core", "System.Security" } group "Tests" print("Searching for tests projects...") IncludeDir("../tests")
Fixed Windows build to generate x86 project files (since that's what Mono official releases provide).
Fixed Windows build to generate x86 project files (since that's what Mono official releases provide).
Lua
mit
mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,tritao/MonoManagedToNative,tritao/MonoManagedToNative,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,tritao/MonoManagedToNative,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000
80d9304e0a9d56e34333fefba611dedccf17822a
src/nn-modules/BPRLoss.lua
src/nn-modules/BPRLoss.lua
-- -- User: pat -- Date: 1/15/16 -- local BPRLoss, parent = torch.class('nn.BPRLoss', 'nn.Criterion') function BPRLoss:__init() parent.__init(self) self.output = nil end function BPRLoss:updateOutput(input, y) local theta = input[1] - input[2] self.output = self.output and self.output:resizeAs(theta) or theta:clone() self.output = self.output:fill(1):cdiv(torch.exp(-theta):add(1)) local err = torch.log(self.output):mean() * -1.0 return err end function BPRLoss:updateGradInput(input, y) local step = self.output:mul(-1):add(1) self.gradInput = { -step, step } return self.gradInput end
-- -- User: pat -- Date: 1/15/16 -- local BPRLoss, parent = torch.class('nn.BPRLoss', 'nn.Criterion') function BPRLoss:__init() parent.__init(self) self.output = nil self.epsilon = .0001 end function BPRLoss:updateOutput(input, y) local theta = input[1] - input[2] self.output = self.output and self.output:resizeAs(theta) or theta:clone() self.output = self.output:fill(1):cdiv(torch.exp(-theta):add(1)) -- add epsilon so that no log(0) self.output:add(self.epsilon) local err = torch.log(self.output):mean() * -1.0 return err end function BPRLoss:updateGradInput(input, y) local step = self.output:mul(-1):add(1) self.gradInput = { -step, step } return self.gradInput end
fix inf error in bpr loss
fix inf error in bpr loss
Lua
mit
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
47604fcf9b7801bc0f320eb29ed2b8e341a452f4
Tests/Bugs/3/manifest.lua
Tests/Bugs/3/manifest.lua
upper = getUpperLibrary(); id = { group=upper.Group, name= upper.Name .. ".3", version="0.1.0.14", author="Tim Simpson" } dependency {group="Macaroni", name="Boost-smart_ptr", version="1.46.1"} dependency {group="Macaroni", name="CppStd", version="2003"} description= [[ There is something wrong with how Macaroni finds dependencies and writes them into header files, leading to code files with circular includes that don't compile. In this example, there are several classes with dependencies on each other. While there is a way to write this code correctly, Macaroni currently does not. UPDATE: While tracing code I realized what the problem is... and its a big deal! With: class Access; boost::shared_ptr<Access> AccessPtr; is different than std::vector<Access> AccessList; In the later case, you *need* the heavy dependency to Access to define AccessList. But for AccessPtr, you don't, probably because Boost turns it into the type argument into a pointer and makes it possible to use a forward reference since they're smart like that. The issue is I have no idea how to tell Macaroni that in some cases Node used by a Type can be a light dependency. Hmm... ]] cavatappi("cavatappi.lua");
upper = getUpperLibrary(); id = { group=upper.Group, name= upper.Name .. ".3", version="0.1.0.14", author="Tim Simpson" } dependency {group="Macaroni", name="Boost-smart_ptr", version="1.46.1"} dependency {group="Macaroni", name="CppStd", version="2003"} description= [[ There is something wrong with how Macaroni finds dependencies and writes them into header files, leading to code files with circular includes that don't compile. In this example, there are several classes with dependencies on each other. While there is a way to write this code correctly, Macaroni currently does not. UPDATE: While tracing code I realized what the problem is... and its a big deal! With: class Access; boost::shared_ptr<Access> AccessPtr; is different than std::vector<Access> AccessList; In the later case, you *need* the heavy dependency to Access to define AccessList. But for AccessPtr, you don't, probably because Boost turns it into the type argument into a pointer and makes it possible to use a forward reference since they're smart like that. The issue is I have no idea how to tell Macaroni that in some cases Node used by a Type can be a light dependency. If I could somehow tell it that "boost::smart_ptr" can have nothing but light deps that's be cool.' ]] cavatappi("cavatappi.lua");
Added to Bugs-3 manifest.
Added to Bugs-3 manifest.
Lua
apache-2.0
TimSimpson/Macaroni,bowlofstew/Macaroni,TimSimpson/Macaroni,TimSimpson/Macaroni,bowlofstew/Macaroni,TimSimpson/Macaroni,bowlofstew/Macaroni,bowlofstew/Macaroni,TimSimpson/Macaroni,bowlofstew/Macaroni
697f909c0831b6f21b458f4cf68070935f524f87
tier/standard/generators.lua
tier/standard/generators.lua
local generator = require"tier.generator" local primitive = require"tier.primitive" local util = require"tier.util" local tags = require"tier.tags" local custom = require"tier.custom" local tagToLua = { [tags.UINT] = "number", [tags.UINT8] = "number", [tags.UINT16] = "number", [tags.UINT32] = "number", [tags.UINT64] = "number", [tags.SINT] = "number", [tags.SINT8] = "number", [tags.SINT16] = "number", [tags.SINT32] = "number", [tags.SINT64] = "number", [tags.HALF] = "number", [tags.FLOAT] = "number", [tags.DOUBLE] = "number", [tags.QUAD] = "number", [tags.SIGN] = "number", [tags.VARINT] = "number", [tags.VARINTZZ] = "number", [tags.CHAR] = "string", [tags.WCHAR] = "string", [tags.STREAM] = "string", [tags.STRING] = "string", [tags.WSTRING] = "string", [tags.FLAG] = "boolean", [tags.BOOLEAN] = "boolean", [tags.VOID] = "nil", [tags.NULL] = "nil", [tags.LIST] = "table", [tags.SET] = "table", [tags.ARRAY] = "table", [tags.TUPLE] = "table", [tags.MAP] = "table" } --Standard generator functions local function metatypetoluatype(g, metatype) local lua_type = tagToLua[metatype.tag] or "unknown" if lua_type == "unkown" then return metatypetoluatype(generator, metatype[1]) end return lua_type end return function(standard) --Generator functions local function gentuple(g, metatype) local tuple = { } for i=1, #metatype do tuple[i] = { mapping = g:generate(metatype[i]) } end return standard.tuple(tuple) end local function genunion(g, metatype) local union = { } for i=1, #metatype do local sub = metatype[i] local ltype = metatypetoluatype(g, sub) union[i] = { type = ltype, mapping = g:generate(sub) } end return standard.union(union, metatype.sizebits) end local function genlist(g, metatype) return standard.list(g:generate(metatype[1]), metatype.sizebits) end local function genset(g, metatype) return standard.set(g:generate(metatype[1]), metatype.sizebits) end local function genarray(g, metatype) return standard.array(g:generate(metatype[1]), metatype.size) end local function genmap(g, metatype) return standard.map(g:generate(metatype[1]), g:generate(metatype[2]), metatype.sizebits) end local function genobject(g, metatype) return standard.object(g:generate(metatype[1])) end local function genint(g, metatype) return custom.int(metatype.bits) end local function genuint(g, metatype) return custom.uint(metatype.bits) end local semantic_generators = { } local function gensemantic(g, metatype) if semantic_generators[metatype.identifier] then return semantic_generators[metatype.identifier](generator, metatype[1]) else error("Cannot create a mapping for unrecognized semantic type " .. metatype.identifier) end end local function genembedded(generator, metatype) return standard.embedded(generator:generate(metatype[1])) end local function genaligned(generator, metatype) return custom.align(metatype.alignof, generator:generate(metatype[1])) end local g = generator() g:register_generator(tags.TUPLE, gentuple) g:register_generator(tags.UNION, genunion) g:register_generator(tags.LIST, genlist) g:register_generator(tags.SET, genset) g:register_generator(tags.MAP, genmap) g:register_generator(tags.ARRAY, genarray) g:register_generator(tags.OBJECT, genobject) g:register_generator(tags.EMBEDDED, genembedded) g:register_generator(tags.ALIGN, genaligned) g:register_generator(tags.ALIGN1, genaligned) g:register_generator(tags.ALIGN2, genaligned) g:register_generator(tags.ALIGN4, genaligned) g:register_generator(tags.ALIGN8, genaligned) g:register_generator(tags.UINT, genuint) g:register_generator(tags.SINT, genint) --We add all the mappings in the --primitive module to the generator for k, v in pairs(primitive) do if util.ismapping(v) then g:register_mapping(v) end end standard.generator = g end
local generator = require"tier.generator" local primitive = require"tier.primitive" local util = require"tier.util" local tags = require"tier.tags" local custom = require"tier.custom" local tagToLua = { [tags.UINT] = "number", [tags.UINT8] = "number", [tags.UINT16] = "number", [tags.UINT32] = "number", [tags.UINT64] = "number", [tags.SINT] = "number", [tags.SINT8] = "number", [tags.SINT16] = "number", [tags.SINT32] = "number", [tags.SINT64] = "number", [tags.HALF] = "number", [tags.FLOAT] = "number", [tags.DOUBLE] = "number", [tags.QUAD] = "number", [tags.SIGN] = "number", [tags.VARINT] = "number", [tags.VARINTZZ] = "number", [tags.CHAR] = "string", [tags.WCHAR] = "string", [tags.STREAM] = "string", [tags.STRING] = "string", [tags.WSTRING] = "string", [tags.FLAG] = "boolean", [tags.BOOLEAN] = "boolean", [tags.VOID] = "nil", [tags.NULL] = "nil", [tags.LIST] = "table", [tags.SET] = "table", [tags.ARRAY] = "table", [tags.TUPLE] = "table", [tags.MAP] = "table" } --Standard generator functions local function metatypetoluatype(g, metatype) local lua_type = tagToLua[metatype.tag] or "unknown" if lua_type == "unknown" then return metatypetoluatype(generator, metatype[1]) end return lua_type end return function(standard) --Generator functions local function gentuple(g, metatype) local tuple = { } for i=1, #metatype do tuple[i] = { mapping = g:generate(metatype[i]) } end return standard.tuple(tuple) end local function genunion(g, metatype) local union = { } for i=1, #metatype do local sub = metatype[i] local ltype = metatypetoluatype(g, sub) if ltype == "unknown" then ltype = "table" end union[i] = { type = ltype, mapping = g:generate(sub) } end return standard.union(union, metatype.sizebits) end local function genlist(g, metatype) return standard.list(g:generate(metatype[1]), metatype.sizebits) end local function genset(g, metatype) return standard.set(g:generate(metatype[1]), metatype.sizebits) end local function genarray(g, metatype) return standard.array(g:generate(metatype[1]), metatype.size) end local function genmap(g, metatype) return standard.map(g:generate(metatype[1]), g:generate(metatype[2]), metatype.sizebits) end local function genobject(g, metatype) return standard.object(g:generate(metatype[1])) end local function genint(g, metatype) return custom.int(metatype.bits) end local function genuint(g, metatype) return custom.uint(metatype.bits) end local semantic_generators = { } local function gensemantic(g, metatype) if semantic_generators[metatype.identifier] then return semantic_generators[metatype.identifier](generator, metatype[1]) else error("Cannot create a mapping for unrecognized semantic type " .. metatype.identifier) end end local function genembedded(generator, metatype) return standard.embedded(generator:generate(metatype[1])) end local function genaligned(generator, metatype) return custom.align(metatype.alignof, generator:generate(metatype[1])) end local g = generator() g:register_generator(tags.TUPLE, gentuple) g:register_generator(tags.UNION, genunion) g:register_generator(tags.LIST, genlist) g:register_generator(tags.SET, genset) g:register_generator(tags.MAP, genmap) g:register_generator(tags.ARRAY, genarray) g:register_generator(tags.OBJECT, genobject) g:register_generator(tags.EMBEDDED, genembedded) g:register_generator(tags.ALIGN, genaligned) g:register_generator(tags.ALIGN1, genaligned) g:register_generator(tags.ALIGN2, genaligned) g:register_generator(tags.ALIGN4, genaligned) g:register_generator(tags.ALIGN8, genaligned) g:register_generator(tags.UINT, genuint) g:register_generator(tags.SINT, genint) --We add all the mappings in the --primitive module to the generator for k, v in pairs(primitive) do if util.ismapping(v) then g:register_mapping(v) end end standard.generator = g end
Fixed a bug in generating unions.
Fixed a bug in generating unions.
Lua
mit
TheFlyingFiddle/TIER,TheFlyingFiddle/TIER
1fcfc1f8ab6cc972095ba710b01c192ea4ce714e
viewlog.lua
viewlog.lua
local ffi = require('ffi') local lgi = require('lgi') local Gio = lgi.require('Gio') local GLib = lgi.require('GLib') hexchat.register("viewlog", "1.1.0", "Open log file for the current context") --[=[ We would like to use Gio.AppInfo.get_recommended_for_type("text/plain"), but it doesn't work (on Windows). Gio.AppInfo.launch_default_for_uri also launches notepad on Windows, so no help. Instead, we require the user to provide a program (and arguments). The first `nil` occurance will be replaced with the logfile path. Note that on Windows, "notepad.exe" can not handle LF line breaks, which Hexchats writes in recent versions. Example: local DEFAULT_PROGRAM = {[[e:\Program Files\Sublime Text 3\sublime_text.exe]]} ]=] local DEFAULT_PROGRAM = {} -- MODIFY THIS -- --------------------------------------------------------------------------------------------------- -- util.c:rfc_strlower -> -- util.h:rfc_tolower -> util.c:rfc_tolowertab -- https://github.com/hexchat/hexchat/blob/c79ce843f495b913ddafa383e6cf818ac99b4f15/src/common/util.c#L1079-L1081 local function rfc_strlower(str) -- almost according to rfc2812, -- except for ^ -> ~ (should be ~ -> ^) -- https://tools.ietf.org/html/rfc2812 str = str:gsub("[A-Z%[%]\\^]", function (letter) return string.char(letter:byte() + 0x20) end) end -- text.c:log_create_filename local function log_create_filename(channame) if not channame then return channame elseif ffi.os == 'Windows' then return channame:gsub('[\\|/><:"*?]', "_") else return rfc_strlower(channame) end end -- text.c:log_create_pathname local function log_create_pathname(ctx) local network = log_create_filename(ctx:get_info('network')) or "NETWORK" local server = log_create_filename(ctx:get_info('server')) local channel = log_create_filename(ctx:get_info('channel')) -- print(("n: %s, s: %s, c: %s"):format(network, server, channel)) if not server then return nil end if server and hexchat.nickcmp(channel, server) == 0 then channel = 'server'; end local logmask = hexchat.prefs['irc_logmask'] local fname = logmask -- substitute variables after strftime expansion fname = fname:gsub("%%([scn])", "\001%1") fname = os.date(fname) -- strftime -- text.c:log_insert_vars & text.c:log_escape_strcpy -- parentheses are required because gsub returns two values fname = fname:gsub("\001n", (network:gsub("%%", "%%%%"))) fname = fname:gsub("\001s", (server:gsub("%%", "%%%%"))) fname = fname:gsub("\001c", (channel:gsub("%%", "%%%%"))) -- Calling GLib.filename_from_utf8 crashes on Windows -- (https://github.com/hexchat/hexchat/issues/1824) -- local config_dir = GLib.filename_from_utf8(hexchat.get_info('configdir'), -1) -- local log_path = GLib.build_filenamev({config_dir, GLib.filename_from_utf8("logs", -1)}) local log_path = GLib.build_filenamev({hexchat.get_info('configdir'), "logs"}) return Gio.File.new_for_commandline_arg_and_cwd(fname, log_path) end function subprocess(cmd) local launcher = Gio.SubprocessLauncher.new(0) -- Gio.SubprocessFlags.STDOUT_SILENCE return launcher:spawnv(cmd) end local function viewlog_cb(word, word_eol) local program if #word > 1 then program = {word_eol[2]} -- TODO what about arguments? else program = DEFAULT_PROGRAM end if not type(program) == 'table' or #program == 0 then hexchat.command('GUI MSGBOX "You need to specify a program to launch in the source code."') return hexchat.EAT_ALL end local logfile = log_create_pathname(hexchat.get_context()) if logfile == nil then return hexchat.EAT_ALL end -- Build cmd and replace first 'nil' in program. -- This will end up appending if there is no nil in the middle. local cmd = program for i = 1, #program + 1 do if cmd[i] == nil then cmd[i] = logfile:get_path() break end end if logfile:query_exists() then if subprocess(cmd) == nil then hexchat.command('GUI MSGBOX "Unable to launch program."') end else hexchat.command(('GUI MSGBOX "Log file for the current channel/dialog does not seem to ' .. 'exist.\n\n""%s""') :format(logfile:get_path())) end return hexchat.EAT_ALL end hexchat.hook_command("viewlog", viewlog_cb, "Usage: /viewlog [program] - Open log file of the current context in " .. "'program' (path to executable). \n" .. "You should set a program (and arguments) in the script's source code.")
local lgi = require('lgi') local Gio = lgi.require('Gio') local GLib = lgi.require('GLib') hexchat.register("viewlog", "1.2.0", "Open log file for the current context") --[=[ We would like to use Gio.AppInfo.get_recommended_for_type("text/plain"), but it doesn't work (on Windows). Gio.AppInfo.launch_default_for_uri also launches notepad on Windows, so no help. Instead, we require the user to provide a program (and arguments). The first `nil` occurance will be replaced with the logfile path. Note that on Windows, "notepad.exe" can not handle LF line breaks, which Hexchats writes in recent versions. Example: local DEFAULT_PROGRAM = {[[e:\Program Files\Sublime Text 3\sublime_text.exe]]} ]=] local DEFAULT_PROGRAM = {"subl"} -- MODIFY THIS -- --------------------------------------------------------------------------------------------------- -- Relies on window pointer implementation to determine whether we're on Windows or not -- (instead of using ffi.os, which is not available in vanilla lua). local is_windows = hexchat.get_info('win_ptr') ~= hexchat.get_info('gtkwin_ptr') -- util.c:rfc_strlower -> -- util.h:rfc_tolower -> util.c:rfc_tolowertab -- https://github.com/hexchat/hexchat/blob/c79ce843f495b913ddafa383e6cf818ac99b4f15/src/common/util.c#L1079-L1081 local function rfc_strlower(str) -- almost according to rfc2812, -- except for ^ -> ~ (should be ~ -> ^) -- https://tools.ietf.org/html/rfc2812 return str:gsub("[A-Z%[%]\\^]", function (letter) return string.char(letter:byte() + 0x20) end) end -- text.c:log_create_filename local function log_create_filename(channame) if not channame then return channame elseif is_windows then return channame:gsub('[\\|/><:"*?]', "_") else return rfc_strlower(channame) end end -- text.c:log_create_pathname local function log_create_pathname(ctx) local network = log_create_filename(ctx:get_info('network')) or "NETWORK" local server = log_create_filename(ctx:get_info('server')) local channel = log_create_filename(ctx:get_info('channel')) -- print(("n: %s, s: %s, c: %s"):format(network, server, channel)) if not server then return nil end if server and hexchat.nickcmp(channel, server) == 0 then channel = 'server'; end local logmask = hexchat.prefs['irc_logmask'] local fname = logmask -- substitute variables after strftime expansion fname = fname:gsub("%%([scn])", "\001%1") fname = os.date(fname) -- strftime -- text.c:log_insert_vars & text.c:log_escape_strcpy -- parentheses are required because gsub returns two values fname = fname:gsub("\001n", (network:gsub("%%", "%%%%"))) fname = fname:gsub("\001s", (server:gsub("%%", "%%%%"))) fname = fname:gsub("\001c", (channel:gsub("%%", "%%%%"))) -- Calling GLib.filename_from_utf8 crashes on Windows -- (https://github.com/hexchat/hexchat/issues/1824) -- local config_dir = GLib.filename_from_utf8(hexchat.get_info('configdir'), -1) -- local log_path = GLib.build_filenamev({config_dir, GLib.filename_from_utf8("logs", -1)}) local log_path = GLib.build_filenamev({hexchat.get_info('configdir'), "logs"}) return Gio.File.new_for_commandline_arg_and_cwd(fname, log_path) end function subprocess(cmd) local launcher = Gio.SubprocessLauncher.new(0) -- Gio.SubprocessFlags.STDOUT_SILENCE return launcher:spawnv(cmd) end local function viewlog_cb(word, word_eol) local program if #word > 1 then program = {word_eol[2]} -- TODO what about arguments? else program = DEFAULT_PROGRAM end if not type(program) == 'table' or #program == 0 then hexchat.command('GUI MSGBOX "You need to specify a program to launch in the source code."') return hexchat.EAT_ALL end local logfile = log_create_pathname(hexchat.get_context()) if logfile == nil then return hexchat.EAT_ALL end -- Build cmd and replace first 'nil' in program. -- This will end up appending if there is no nil in the middle. local cmd = program for i = 1, #program + 1 do if cmd[i] == nil then cmd[i] = logfile:get_path() break end end if logfile:query_exists() then if subprocess(cmd) == nil then hexchat.command('GUI MSGBOX "Unable to launch program."') end else hexchat.command(('GUI MSGBOX "Log file for the current channel/dialog does not seem to ' .. 'exist.\n\n""%s""') :format(logfile:get_path())) end return hexchat.EAT_ALL end hexchat.hook_command("viewlog", viewlog_cb, "Usage: /viewlog [program] - Open log file of the current context in " .. "'program' (path to executable). \n" .. "You should set a program (and arguments) in the script's source code.")
Fix viewlog for Linux (and Lua 5.3, without ffi)
Fix viewlog for Linux (and Lua 5.3, without ffi)
Lua
mit
FichteFoll/hexchat-addons
9ad89e6942f1e18ce03b89b3cbdaa37dcaf822c7
nvim/nvim/lua/_/telescope.lua
nvim/nvim/lua/_/telescope.lua
local has_telescope, telescope = pcall(require, 'telescope') local M = {} local previewers = require('telescope.previewers') local builtin = require('telescope.builtin') local conf = require('telescope.config') local Job = require('plenary.job') -- Ignore binary files local new_maker = function(filepath, bufnr, opts) opts = opts or {} filepath = vim.fn.expand(filepath) Job:new({ command='file', args={'--mime-type', '-b', filepath}, on_exit=function(j) local mime_types = vim.split(j:result()[1], '/') local mime_type = mime_types[1] local mime_subtype = mime_types[2] if mime_type == 'text' or mime_subtype == 'json' then previewers.buffer_previewer_maker(filepath, bufnr, opts) else -- maybe we want to write something to the buffer here vim.schedule(function() vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {'BINARY'}) end) end end }):sync() end local delta = previewers.new_termopen_previewer { get_command=function(entry) return { 'git', '-c', 'core.pager=delta', '-c', 'delta.side-by-side=false', 'diff', '--merge-base', vim.fn.expand('$REVIEW_BASE'), '--', entry.path } end } local function setup() if not has_telescope then return end telescope.setup({ defaults={ layout_strategy='flex', layout_config={ height=.95, width=.95, horizontal={preview_width=.5}, vertical={preview_height=.7} }, buffer_previewer_maker=new_maker }, extensions={ fzf={ fuzzy=true, override_generic_sorter=true, -- override the generic sorter override_file_sorter=true, -- override the file sorter case_mode='smart_case' -- or "ignore_case" or "respect_case" -- the default case_mode is "smart_case" }, ['ui-select']={ require('telescope.themes').get_dropdown { -- even more opts } -- pseudo code / specification for writing custom displays, like the one -- for "codeactions" -- specific_opts = { -- [kind] = { -- make_indexed = function(items) -> indexed_items, width, -- make_displayer = function(widths) -> displayer -- make_display = function(displayer) -> function(e) -- make_ordinal = function(e) -> string -- }, -- -- for example to disable the custom builtin "codeactions" display -- do the following -- codeactions = false, -- } }, frecency={}, live_grep_raw={ auto_quoting=true -- enable/disable auto-quoting }, file_browser={ theme='ivy', -- disables netrw and use telescope-file-browser in its place hijack_netrw=true, mappings={ ['i']={ -- your custom insert mode mappings }, ['n']={ -- your custom normal mode mappings } } } } }) telescope.load_extension('frecency') telescope.load_extension('fzf') telescope.load_extension('ui-select') telescope.load_extension('live_grep_args') telescope.load_extension('file_browser') -- Key mappings vim.keymap.set('n', '<leader>ff', function() require('telescope.builtin').find_files() end) vim.keymap.set('n', '<leader>fg', function() require('telescope').extensions.live_grep_args.live_grep_args() end) vim.keymap.set('n', '<leader>fb', function() require('telescope.builtin').buffers() end) vim.keymap.set('n', '<leader>fh', function() require('telescope.builtin').help_tags() end) vim.keymap.set('n', '<leader>ft', function() require('telescope.builtin').filetypes() end) vim.keymap.set('n', '<leader>fj', function() require('telescope.builtin').jumplist() end) vim.keymap.set('n', '<leader>fl', function() require('telescope.builtin').loclist() end) vim.keymap.set('n', '<leader>fq', function() require('telescope.builtin').quickfix() end) vim.keymap.set('n', '<leader>fc', function() require('telescope.builtin').command_history() end) vim.keymap.set('n', '<leader>fs', function() require('telescope.builtin').search_history() end) vim.keymap.set('n', '<leader>gc', function() require('telescope.builtin').git_commits() end) vim.keymap.set('n', '<leader>gb', function() require('telescope.builtin').git_branches() end) vim.keymap.set('n', '<leader>gd', function() require('telescope.builtin').git_files({ prompt_title='Git review files', git_command={ 'git', 'diff', '--name-only', '--merge-base', vim.fn.expand('$REVIEW_BASE') }, previewer=delta }) end) vim.keymap.set('n', '<leader>gf', function() require('telescope.builtin').git_status() end) vim.keymap.set('n', '<leader>gp', function() require('telescope.builtin').git_bcommits() end) vim.keymap.set('n', '<leader>zl', function() require('telescope.builtin').spell_suggest() end) vim.keymap.set('n', '<leader><leader>', function() require('telescope.builtin').resume() end) vim.keymap.set('n', '<leader>ee', function() require('telescope').extensions.file_browser.file_browser() end) vim.keymap.set('n', '<leader>eb', function() require('telescope').extensions.file_browser.file_browser({ path='%:p:h', select_buffer=true }) end) end function M.setup() setup() end return M
local has_telescope, telescope = pcall(require, 'telescope') local M = {} local previewers = require('telescope.previewers') local builtin = require('telescope.builtin') local Job = require('plenary.job') -- Ignore binary files local new_maker = function(filepath, bufnr, opts) opts = opts or {} filepath = vim.fn.expand(filepath) Job:new({ command='file', args={'--mime-type', '-b', filepath}, on_exit=function(j) local mime_types = vim.split(j:result()[1], '/') local mime_type = mime_types[1] local mime_subtype = mime_types[2] if mime_type == 'text' or mime_subtype == 'json' then previewers.buffer_previewer_maker(filepath, bufnr, opts) else -- maybe we want to write something to the buffer here vim.schedule(function() vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {'BINARY'}) end) end end }):sync() end local delta_file = previewers.new_termopen_previewer { get_command=function(entry) return { 'git', '-c', 'core.pager=delta', '-c', 'delta.side-by-side=false', 'diff', '--merge-base', vim.fn.expand('$REVIEW_BASE'), '--', entry.path } end } local delta_commit = previewers.new_termopen_previewer { get_command=function(entry) return { 'git', '-c', 'core.pager=delta', '-c', 'delta.side-by-side=false', 'diff', entry.value .. '^!' } end } local function setup() if not has_telescope then return end telescope.setup({ defaults={ layout_strategy='flex', layout_config={ height=.95, width=.95, flex={flip_columns=120, flip_lines=20}, horizontal={preview_width=.5}, vertical={preview_height=.7} }, buffer_previewer_maker=new_maker }, extensions={ fzf={ fuzzy=true, override_generic_sorter=true, -- override the generic sorter override_file_sorter=true, -- override the file sorter case_mode='smart_case' -- or "ignore_case" or "respect_case" -- the default case_mode is "smart_case" }, ['ui-select']={ require('telescope.themes').get_dropdown { -- even more opts } -- pseudo code / specification for writing custom displays, like the one -- for "codeactions" -- specific_opts = { -- [kind] = { -- make_indexed = function(items) -> indexed_items, width, -- make_displayer = function(widths) -> displayer -- make_display = function(displayer) -> function(e) -- make_ordinal = function(e) -> string -- }, -- -- for example to disable the custom builtin "codeactions" display -- do the following -- codeactions = false, -- } }, frecency={}, live_grep_raw={ auto_quoting=true -- enable/disable auto-quoting }, file_browser={ theme='ivy', -- disables netrw and use telescope-file-browser in its place hijack_netrw=true, mappings={ ['i']={ -- your custom insert mode mappings }, ['n']={ -- your custom normal mode mappings } } } } }) telescope.load_extension('frecency') telescope.load_extension('fzf') telescope.load_extension('ui-select') telescope.load_extension('live_grep_args') telescope.load_extension('file_browser') -- Key mappings vim.keymap.set('n', '<leader>ff', function() builtin.find_files() end) vim.keymap.set('n', '<leader>fg', function() require('telescope').extensions.live_grep_args.live_grep_args() end) vim.keymap.set('n', '<leader>fb', function() builtin.buffers() end) vim.keymap.set('n', '<leader>fh', function() builtin.help_tags() end) vim.keymap.set('n', '<leader>ft', function() builtin.filetypes() end) vim.keymap.set('n', '<leader>fj', function() builtin.jumplist() end) vim.keymap.set('n', '<leader>fl', function() builtin.loclist() end) vim.keymap.set('n', '<leader>fq', function() builtin.quickfix() end) vim.keymap.set('n', '<leader>fc', function() builtin.command_history() end) vim.keymap.set('n', '<leader>fs', function() builtin.search_history() end) vim.keymap.set('n', '<leader>gc', function() builtin.git_commits({previewer=delta_commit}) end) vim.keymap.set('n', '<leader>gb', function() builtin.git_branches() end) vim.keymap.set('n', '<leader>gd', function() builtin.git_files({ prompt_title='Git review files', git_command={ 'git', 'diff', '--name-only', '--merge-base', vim.fn.expand('$REVIEW_BASE') }, previewer=delta_file }) end) vim.keymap.set('n', '<leader>gf', function() builtin.git_status() end) vim.keymap.set('n', '<leader>gp', function() builtin.git_bcommits({previewer=delta_commit}) end) vim.keymap.set('n', '<leader>zl', function() builtin.spell_suggest() end) vim.keymap.set('n', '<leader><leader>', function() builtin.resume() end) vim.keymap.set('n', '<leader>ee', function() require('telescope').extensions.file_browser.file_browser() end) vim.keymap.set('n', '<leader>eb', function() require('telescope').extensions.file_browser.file_browser({ path='%:p:h', select_buffer=true }) end) end function M.setup() setup() end return M
chore(nvim): minor adjustment
chore(nvim): minor adjustment diff --git a/nvim/nvim/lua/_/telescope.lua b/nvim/nvim/lua/_/telescope.lua index 161fad7..e2711d2 100644 --- a/nvim/nvim/lua/_/telescope.lua +++ b/nvim/nvim/lua/_/telescope.lua @@ -4,7 +4,6 @@ local M = {} local previewers = require('telescope.previewers') local builtin = require('telescope.builtin') -local conf = require('telescope.config') local Job = require('plenary.job') -- Ignore binary files @@ -33,7 +32,7 @@ local new_maker = function(filepath, bufnr, opts) }):sync() end -local delta = previewers.new_termopen_previewer { +local delta_file = previewers.new_termopen_previewer { get_command=function(entry) return { 'git', @@ -50,6 +49,20 @@ local delta = previewers.new_termopen_previewer { end } +local delta_commit = previewers.new_termopen_previewer { + get_command=function(entry) + return { + 'git', + '-c', + 'core.pager=delta', + '-c', + 'delta.side-by-side=false', + 'diff', + entry.value .. '^!' + } + end +} + local function setup() if not has_telescope then return end @@ -59,6 +72,7 @@ local function setup() layout_config={ height=.95, width=.95, + flex={flip_columns=120, flip_lines=20}, horizontal={preview_width=.5}, vertical={preview_height=.7} }, @@ -119,35 +133,25 @@ local function setup() telescope.load_extension('file_browser') -- Key mappings - vim.keymap.set('n', '<leader>ff', - function() require('telescope.builtin').find_files() end) + vim.keymap.set('n', '<leader>ff', function() builtin.find_files() end) vim.keymap.set('n', '<leader>fg', function() require('telescope').extensions.live_grep_args.live_grep_args() end) - vim.keymap.set('n', '<leader>fb', - function() require('telescope.builtin').buffers() end) - vim.keymap.set('n', '<leader>fh', - function() require('telescope.builtin').help_tags() end) + vim.keymap.set('n', '<leader>fb', function() builtin.buffers() end) + vim.keymap.set('n', '<leader>fh', function() builtin.help_tags() end) - vim.keymap.set('n', '<leader>ft', - function() require('telescope.builtin').filetypes() end) - vim.keymap.set('n', '<leader>fj', - function() require('telescope.builtin').jumplist() end) - vim.keymap.set('n', '<leader>fl', - function() require('telescope.builtin').loclist() end) - vim.keymap.set('n', '<leader>fq', - function() require('telescope.builtin').quickfix() end) - vim.keymap.set('n', '<leader>fc', - function() require('telescope.builtin').command_history() end) - vim.keymap.set('n', '<leader>fs', - function() require('telescope.builtin').search_history() end) + vim.keymap.set('n', '<leader>ft', function() builtin.filetypes() end) + vim.keymap.set('n', '<leader>fj', function() builtin.jumplist() end) + vim.keymap.set('n', '<leader>fl', function() builtin.loclist() end) + vim.keymap.set('n', '<leader>fq', function() builtin.quickfix() end) + vim.keymap.set('n', '<leader>fc', function() builtin.command_history() end) + vim.keymap.set('n', '<leader>fs', function() builtin.search_history() end) vim.keymap.set('n', '<leader>gc', - function() require('telescope.builtin').git_commits() end) - vim.keymap.set('n', '<leader>gb', - function() require('telescope.builtin').git_branches() end) + function() builtin.git_commits({previewer=delta_commit}) end) + vim.keymap.set('n', '<leader>gb', function() builtin.git_branches() end) vim.keymap.set('n', '<leader>gd', function() - require('telescope.builtin').git_files({ + builtin.git_files({ prompt_title='Git review files', git_command={ 'git', @@ -156,19 +160,16 @@ local function setup() '--merge-base', vim.fn.expand('$REVIEW_BASE') }, - previewer=delta + previewer=delta_file }) end) - vim.keymap.set('n', '<leader>gf', - function() require('telescope.builtin').git_status() end) + vim.keymap.set('n', '<leader>gf', function() builtin.git_status() end) vim.keymap.set('n', '<leader>gp', - function() require('telescope.builtin').git_bcommits() end) + function() builtin.git_bcommits({previewer=delta_commit}) end) - vim.keymap.set('n', '<leader>zl', - function() require('telescope.builtin').spell_suggest() end) + vim.keymap.set('n', '<leader>zl', function() builtin.spell_suggest() end) - vim.keymap.set('n', '<leader><leader>', - function() require('telescope.builtin').resume() end) + vim.keymap.set('n', '<leader><leader>', function() builtin.resume() end) vim.keymap.set('n', '<leader>ee', function() require('telescope').extensions.file_browser.file_browser() end)
Lua
mit
skyuplam/dotfiles,skyuplam/dotfiles
185c1fc400256458603e7d2734a5ea3742985495
premake/bgfx.lua
premake/bgfx.lua
-- -- Copyright 2010-2014 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- project "bgfx" uuid "2dc7fd80-ed76-11e0-be50-0800200c9a66" kind "StaticLib" includedirs { BGFX_DIR .. "../bx/include", } defines { -- "BGFX_CONFIG_RENDERER_OPENGL=1", } configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "windows" } includedirs { "$(DXSDK_DIR)/include", } configuration { "osx or ios*" } files { BGFX_DIR .. "src/**.mm", } configuration { "vs* or linux or mingw or osx or ios*" } includedirs { --nacl has GLES2 headers modified... BGFX_DIR .. "3rdparty/khronos", } configuration {} includedirs { BGFX_DIR .. "include", } files { BGFX_DIR .. "include/**.h", BGFX_DIR .. "src/**.cpp", BGFX_DIR .. "src/**.h", } excludes { BGFX_DIR .. "src/**.bin.h", } copyLib() project "bgfx-shared-lib" uuid "09986168-e9d9-11e3-9c8e-f2aef940a72a" kind "SharedLib" includedirs { BGFX_DIR .. "../bx/include", } defines { "BGFX_SHARED_LIB_BUILD=1", -- "BGFX_CONFIG_RENDERER_OPENGL=1", } configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "windows" } includedirs { "$(DXSDK_DIR)/include", } configuration { "osx or ios*" } files { BGFX_DIR .. "src/**.mm", } configuration { "osx" } links { "Cocoa.framework", } configuration { "vs* or linux or mingw or osx or ios*" } includedirs { --nacl has GLES2 headers modified... BGFX_DIR .. "3rdparty/khronos", } configuration {} includedirs { BGFX_DIR .. "include", } files { BGFX_DIR .. "include/**.h", BGFX_DIR .. "src/**.cpp", BGFX_DIR .. "src/**.h", } excludes { BGFX_DIR .. "src/**.bin.h", } copyLib()
-- -- Copyright 2010-2014 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- project "bgfx" uuid "2dc7fd80-ed76-11e0-be50-0800200c9a66" kind "StaticLib" includedirs { BGFX_DIR .. "../bx/include", } defines { -- "BGFX_CONFIG_RENDERER_OPENGL=1", } configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "windows" } includedirs { "$(DXSDK_DIR)/include", } configuration { "osx or ios*" } files { BGFX_DIR .. "src/**.mm", } configuration { "vs* or linux or mingw or osx or ios*" } includedirs { --nacl has GLES2 headers modified... BGFX_DIR .. "3rdparty/khronos", } configuration {} includedirs { BGFX_DIR .. "include", } files { BGFX_DIR .. "include/**.h", BGFX_DIR .. "src/**.cpp", BGFX_DIR .. "src/**.h", } excludes { BGFX_DIR .. "src/**.bin.h", } copyLib() project "bgfx-shared-lib" uuid "09986168-e9d9-11e3-9c8e-f2aef940a72a" kind "SharedLib" includedirs { BGFX_DIR .. "../bx/include", } defines { "BGFX_SHARED_LIB_BUILD=1", -- "BGFX_CONFIG_RENDERER_OPENGL=1", } configuration { "Debug" } defines { "BGFX_CONFIG_DEBUG=1", } configuration { "android*" } links { "EGL", "GLESv2", } configuration { "windows" } includedirs { "$(DXSDK_DIR)/include", } configuration { "osx or ios*" } files { BGFX_DIR .. "src/**.mm", } configuration { "osx" } links { "Cocoa.framework", } configuration { "vs* or linux or mingw or osx or ios*" } includedirs { --nacl has GLES2 headers modified... BGFX_DIR .. "3rdparty/khronos", } configuration {} includedirs { BGFX_DIR .. "include", } files { BGFX_DIR .. "include/**.h", BGFX_DIR .. "src/**.cpp", BGFX_DIR .. "src/**.h", } excludes { BGFX_DIR .. "src/**.bin.h", } copyLib()
Android: Fixed missing link dependencies when building shared library.
Android: Fixed missing link dependencies when building shared library.
Lua
bsd-2-clause
fluffyfreak/bgfx,elmindreda/bgfx,BlueCrystalLabs/bgfx,bkaradzic/bgfx,jpcy/bgfx,marco-we/bgfx,ocornut/bgfx,0-wiz-0/bgfx,jpcy/bgfx,mendsley/bgfx,ming4883/bgfx,cyndis/bgfx,bkaradzic/bgfx,mmicko/bgfx,MikePopoloski/bgfx,septag/bgfx,LSBOSS/bgfx,fluffyfreak/bgfx,0-wiz-0/bgfx,jpcy/bgfx,jdryg/bgfx,aonorin/bgfx,ktotheoz/bgfx,cuavas/bgfx,Synxis/bgfx,darkimage/bgfx,janstk/bgfx,andr3wmac/bgfx,sergeScherbakov/bgfx,Vertexwahn/bgfx,LWJGL-CI/bgfx,fluffyfreak/bgfx,mcanthony/bgfx,sergeScherbakov/bgfx,janstk/bgfx,jdryg/bgfx,kondrak/bgfx,aonorin/bgfx,marco-we/bgfx,0-wiz-0/bgfx,mendsley/bgfx,MikePopoloski/bgfx,MikePopoloski/bgfx,cuavas/bgfx,marco-we/bgfx,LWJGL-CI/bgfx,ming4883/bgfx,Synxis/bgfx,andr3wmac/bgfx,fluffyfreak/bgfx,v3n/bgfx,septag/bgfx,v3n/bgfx,kondrak/bgfx,attilaz/bgfx,elmindreda/bgfx,emoon/bgfx,kondrak/bgfx,BlueCrystalLabs/bgfx,Extrawurst/bgfx,Synxis/bgfx,andr3wmac/bgfx,attilaz/bgfx,cyndis/bgfx,Extrawurst/bgfx,mmicko/bgfx,septag/bgfx,Vertexwahn/bgfx,mendsley/bgfx,bkaradzic/bgfx,darkimage/bgfx,ktotheoz/bgfx,aonorin/bgfx,elmindreda/bgfx,sergeScherbakov/bgfx,LSBOSS/bgfx,bkaradzic/bgfx,ming4883/bgfx,ocornut/bgfx,LWJGL-CI/bgfx,attilaz/bgfx,LSBOSS/bgfx,emoon/bgfx,BlueCrystalLabs/bgfx,mmicko/bgfx,LWJGL-CI/bgfx,ktotheoz/bgfx,ocornut/bgfx,cyndis/bgfx,emoon/bgfx,jpcy/bgfx,cuavas/bgfx,darkimage/bgfx,v3n/bgfx,jdryg/bgfx,janstk/bgfx,jdryg/bgfx,mcanthony/bgfx,Vertexwahn/bgfx,mcanthony/bgfx,Extrawurst/bgfx
7a0c905dce9e470462ad07733dad1eacbbb473f6
kernel/turtle/ttl2flr.lua
kernel/turtle/ttl2flr.lua
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI -- prefix index necessary to expand Qnames with a prefix only and no -- name local __PREFIXES = {} local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else __PREFIXES[p.name] = p.uri print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- prefix only and no name if n == "" then assert(__PREFIXES[r.prefix], "Prefix must be defined: " .. r.prefix) return string.format("\"%s\"^^\\iri", __PREFIXES[r.prefix]) -- dcterms has "dcterms:ISO639-2" elseif n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:gsub('"', '\\"') .. '"' elseif o.type == "TypedString" then local t if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end return string.format("\"%s\"^^%s", o.value, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/nepomuk/v1.1.ttl", "r") local f = io.open("/home/jbalint/sw/stardog-2.1.3/export-2014-06-06-3.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) __dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI -- prefix index necessary to expand Qnames with a prefix only and no -- name local __PREFIXES = {} local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else __PREFIXES[p.name] = p.uri print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- prefix only and no name if n == "" then assert(__PREFIXES[r.prefix], "Prefix must be defined: " .. r.prefix) return string.format("\"%s\"^^\\iri", __PREFIXES[r.prefix]) -- dcterms has "dcterms:ISO639-2" elseif n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) elseif r.type == "Blank" then -- TODO change this -- just use them as oids for now -- note, this is currently acceptable because we are translating -- one stardog export with unique bnode ids --return string.format("\\#[bnodeId->%s]", r.nodeID) return r.nodeID else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:gsub('"', '\\"') .. '"' elseif o.type == "TypedString" then local t if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end return string.format("\"%s\"^^%s", o.value:gsub('"', '\\"'), t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/nepomuk/v1.1.ttl", "r") local f = io.open("/home/jbalint/sw/stardog-2.1.3/export-2014-06-24.ttl", "r") --local f = io.open("/home/jbalint/sw/stardog-2.1.3/bnode_test.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) --__dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
hacky bnode support in ttl2flr and fix one part of string escaping
hacky bnode support in ttl2flr and fix one part of string escaping
Lua
mit
jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico
0804a0a91d76fed01db296f8a22771752ee5771a
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = entry({"lm"}, template("linkmeter/index"), nil, 10) page.sysauth = { "anon", "root" } page.sysauth_authenticator = function (validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) sdat = sdat() if sdat.token == luci.dispatcher.context.urltoken then user = sdat.user end end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end entry({"lm", "set"}, call("set")).sysauth = "root" entry({"lm", "login"}, call("rootredirect")).sysauth = "root" end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then -- remove /set? or set? if supplied rawset = rawset:gsub("^/?set%?","") vals = require "luci.http.protocol".urldecode_params(rawset) end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end require("lmclient") local lm = LmClient() http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end local result, err = lm:query("$LMST,%s,%s" % {k,v}, true) http.write("%s to %s = %s\n" % {k,v, result or err}) if err then break end end lm:close() http.write("Done!") end
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = entry({"lm"}, template("linkmeter/index"), nil, 10) page.sysauth = { "anon", "root" } page.sysauth_authenticator = function (validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) sdat = sdat() if sdat.token == luci.dispatcher.context.urltoken then user = sdat.user end end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end entry({"lm", "set"}, call("set")).sysauth = "root" entry({"lm", "login"}, call("rootredirect")).sysauth = "root" end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then -- remove /set? or set? if supplied rawset = rawset:gsub("^/?set%?","") vals = {} for pair in rawset:gmatch( "[^&;]+" ) do local key = pair:match("^([^=]+)") local val = pair:match("^[^=]+=(.+)$") if key and val then vals[key] = val end end end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end require("lmclient") local lm = LmClient() http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end local result, err = lm:query("$LMST,%s,%s" % {k,v}, true) http.write("%s to %s = %s\n" % {k,v, result or err}) if err then break end end lm:close() http.write("Done!") end
[lm] Fix config's rawset double urldecoding values
[lm] Fix config's rawset double urldecoding values
Lua
mit
shmick/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter
4895b7db7014afa1c1e25718248260a4c9455c8f
lua/plugins/telescope.lua
lua/plugins/telescope.lua
local nvim = require'nvim' local utils = require'utils' local executable = require'utils.files'.executable local load_module = require'utils.helpers'.load_module local set_autocmd = require'nvim.autocmds'.set_autocmd local set_mapping = require'nvim.mappings'.set_mapping local set_command = require'nvim.commands'.set_command local telescope = load_module'telescope' if not telescope then return false end -- local lsp_langs = require'plugins.lsp' local ts_langs = require'plugins.treesitter' local actions = require'telescope.actions' telescope.setup{ defaults = { vimgrep_arguments = require'utils.helpers'.select_grep(false, 'grepprg', true), mappings = { i = { ["<ESC>"] = actions.close, -- ["<CR>"] = actions.goto_file_selection_edit + actions.center, }, n = { ["<ESC>"] = actions.close }, }, prompt_position = "bottom", prompt_prefix = ">", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", -- file_ignore_patterns = {}, file_sorter = require'telescope.sorters'.get_fzy_sorter , generic_sorter = require'telescope.sorters'.get_fzy_sorter, -- shorten_path = true, winblend = 0, -- width = 0.75, -- preview_cutoff = 120, -- results_height = 1, -- results_width = 0.8, -- border = {}, -- borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, -- color_devicons = true, -- use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- file_previewer = require'telescope.previewers'.cat.new, -- grep_previewer = require'telescope.previewers'.vimgrep.new, -- qflist_previewer = require'telescope.previewers'.qflist.new, -- Developer configurations: Not meant for general override -- buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker }, } -- *** Builtins *** -- builtin.planets -- builtin.builtin -- builtin.find_files -- builtin.git_files -- builtin.buffers -- builtin.oldfiles -- builtin.commands -- builtin.tags -- builtin.command_history -- builtin.help_tags -- builtin.man_pages -- builtin.marks -- builtin.colorscheme -- builtin.treesitter -- builtin.live_grep -- builtin.current_buffer_fuzzy_find -- builtin.current_buffer_tags -- builtin.grep_string -- builtin.quickfix -- builtin.loclist -- builtin.reloader -- builtin.vim_options -- builtin.registers -- builtin.keymaps -- builtin.filetypes -- builtin.highlights -- builtin.git_commits -- builtin.git_bcommits -- builtin.git_branches -- builtin.git_status local noremap = {noremap = true} set_command{ lhs = 'LuaReloaded', rhs = [[lua require'telescope.builtin'.reloader()]], args = {force=true} } set_command{ lhs = 'HelpTags', rhs = function() require'telescope.builtin'.help_tags{} end, args = {force=true} } set_mapping{ mode = 'n', lhs = '<C-p>', rhs = function() require'telescope.builtin'.find_files{} -- local is_git = vim.b.project_root and vim.b.project_root.is_git or false -- require'telescope.builtin'.find_files { -- find_command = require'utils.helpers'.select_filelist(is_git, true) -- } end, args = {noremap = true} } set_mapping{ mode = 'n', lhs = '<C-b>', rhs = [[<cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>g', rhs = [[<cmd>lua require'telescope.builtin'.live_grep{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<C-q>', rhs = [[<cmd>lua require'telescope.builtin'.quickfix{}<CR>]], args = noremap, } set_command{ lhs = 'Oldfiles', rhs = [[lua require'telescope.builtin'.oldfiles{}]], args = {force=true} } set_command{ lhs = 'Registers', rhs = [[lua require'telescope.builtin'.registers{}]], args = {force=true} } set_command{ lhs = 'Marks', rhs = [[lua require'telescope.builtin'.marks{}]], args = {force=true} } set_command{ lhs = 'Manpages', rhs = [[lua require'telescope.builtin'.man_pages{}]], args = {force=true} } set_command{ lhs = 'GetVimFiles', rhs = function() require'telescope.builtin'.find_files{ cwd = require'sys'.base, find_command = require'utils.helpers'.select_filelist(false, true) } end, args = {force=true} } if executable('git') then -- set_mapping{ -- mode = 'n', -- lhs = '<leader>s', -- rhs = [[<cmd>lua require'telescope.builtin'.git_status{}<CR>]], -- args = noremap, -- } set_mapping{ mode = 'n', lhs = '<leader>c', rhs = [[<cmd>lua require'telescope.builtin'.git_bcommits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>C', rhs = [[<cmd>lua require'telescope.builtin'.git_commits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>b', rhs = [[<cmd>lua require'telescope.builtin'.git_branches{}<CR>]], args = noremap, } end if ts_langs then set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[nnoremap <A-s> <cmd>lua require'telescope.builtin'.treesitter{}<CR>]], group = 'TreesitterAutocmds' } set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[command! -buffer TSSymbols lua require'telescope.builtin'.treesitter{}]], group = 'TreesitterAutocmds' } end return true
local nvim = require'nvim' local utils = require'utils' local executable = require'utils.files'.executable local load_module = require'utils.helpers'.load_module local set_autocmd = require'nvim.autocmds'.set_autocmd local set_mapping = require'nvim.mappings'.set_mapping local set_command = require'nvim.commands'.set_command local telescope = load_module'telescope' if not telescope then return false end -- local lsp_langs = require'plugins.lsp' local ts_langs = require'plugins.treesitter' local actions = require'telescope.actions' telescope.setup{ defaults = { vimgrep_arguments = require'utils.helpers'.select_grep(false, 'grepprg', true), mappings = { i = { ["<ESC>"] = actions.close, -- ["<CR>"] = actions.goto_file_selection_edit + actions.center, }, n = { ["<ESC>"] = actions.close }, }, prompt_position = "bottom", prompt_prefix = ">", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", -- file_ignore_patterns = {}, file_sorter = require'telescope.sorters'.get_fzy_sorter , generic_sorter = require'telescope.sorters'.get_fzy_sorter, -- shorten_path = true, winblend = 0, -- width = 0.75, -- preview_cutoff = 120, -- results_height = 1, -- results_width = 0.8, -- border = {}, -- borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, -- color_devicons = true, -- use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- file_previewer = require'telescope.previewers'.cat.new, -- grep_previewer = require'telescope.previewers'.vimgrep.new, -- qflist_previewer = require'telescope.previewers'.qflist.new, -- Developer configurations: Not meant for general override -- buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker }, } -- *** Builtins *** -- builtin.planets -- builtin.builtin -- builtin.find_files -- builtin.git_files -- builtin.buffers -- builtin.oldfiles -- builtin.commands -- builtin.tags -- builtin.command_history -- builtin.help_tags -- builtin.man_pages -- builtin.marks -- builtin.colorscheme -- builtin.treesitter -- builtin.live_grep -- builtin.current_buffer_fuzzy_find -- builtin.current_buffer_tags -- builtin.grep_string -- builtin.quickfix -- builtin.loclist -- builtin.reloader -- builtin.vim_options -- builtin.registers -- builtin.keymaps -- builtin.filetypes -- builtin.highlights -- builtin.git_commits -- builtin.git_bcommits -- builtin.git_branches -- builtin.git_status local noremap = {noremap = true} set_command{ lhs = 'LuaReloaded', rhs = [[lua require'telescope.builtin'.reloader()]], args = {force=true} } set_command{ lhs = 'HelpTags', rhs = function() require'telescope.builtin'.help_tags{} end, args = {force=true} } set_mapping{ mode = 'n', lhs = '<C-p>', rhs = function() local is_git = vim.b.project_root and vim.b.project_root.is_git or false require'telescope.builtin'.find_files { find_command = require'utils.helpers'.select_filelist(is_git, true) } end, args = {noremap = true} } set_mapping{ mode = 'n', lhs = '<C-b>', rhs = [[<cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>g', rhs = [[<cmd>lua require'telescope.builtin'.live_grep{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<C-q>', rhs = [[<cmd>lua require'telescope.builtin'.quickfix{}<CR>]], args = noremap, } set_command{ lhs = 'Oldfiles', rhs = [[lua require'telescope.builtin'.oldfiles{}]], args = {force=true} } set_command{ lhs = 'Registers', rhs = [[lua require'telescope.builtin'.registers{}]], args = {force=true} } set_command{ lhs = 'Marks', rhs = [[lua require'telescope.builtin'.marks{}]], args = {force=true} } set_command{ lhs = 'Manpages', rhs = [[lua require'telescope.builtin'.man_pages{}]], args = {force=true} } set_command{ lhs = 'GetVimFiles', rhs = function() require'telescope.builtin'.find_files{ cwd = require'sys'.base, find_command = require'utils.helpers'.select_filelist(false, true) } end, args = {force=true} } if executable('git') then -- set_mapping{ -- mode = 'n', -- lhs = '<leader>s', -- rhs = [[<cmd>lua require'telescope.builtin'.git_status{}<CR>]], -- args = noremap, -- } set_mapping{ mode = 'n', lhs = '<leader>c', rhs = [[<cmd>lua require'telescope.builtin'.git_bcommits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>C', rhs = [[<cmd>lua require'telescope.builtin'.git_commits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>b', rhs = [[<cmd>lua require'telescope.builtin'.git_branches{}<CR>]], args = noremap, } end if ts_langs then set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[nnoremap <A-s> <cmd>lua require'telescope.builtin'.treesitter{}<CR>]], group = 'TreesitterAutocmds' } set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[command! -buffer TSSymbols lua require'telescope.builtin'.treesitter{}]], group = 'TreesitterAutocmds' } end return true
fix: Restore telescope dynamic find files
fix: Restore telescope dynamic find files
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
8f5e105ee04692d8f6a23b3f9909cab25f39dad8
admin/server/player_admin.lua
admin/server/player_admin.lua
addCommandHandler( { "getpos", "pos", "getposition", "getxyz", "getloc", "loc", "getlocation" }, function( player, cmd, targetPlayer ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( targetPlayer ) then targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end else targetPlayer = player end local x, y, z = getElementPosition( targetPlayer ) local rotation = getPedRotation( targetPlayer ) local interior, dimension = getElementInterior( targetPlayer ), getElementDimension( targetPlayer ) x, y, z = math.floor( x * 100 ) / 100, math.floor( y * 100 ) / 100, math.floor( z * 100 ) / 100 rotation = math.floor( rotation * 100 ) / 100 local playerName = getPlayerName( targetPlayer ) outputChatBox( ( targetPlayer ~= player and exports.common:formatPlayerName( playerName ) or "Your" ) .. " position:", player, 230, 180, 95, false ) outputChatBox( " Position: " .. x .. ", " .. y .. ", " .. z, player, 230, 180, 95, false ) outputChatBox( " Rotation: " .. rotation .. ", Interior: " .. interior .. ", Dimension: " .. dimension, player, 230, 180, 95, false ) end end ) addCommandHandler( { "makeadmin", "setlevel", "setadminlevel" }, function( player, cmd, targetPlayer, level ) if ( exports.common:isPlayerServerSeniorAdmin( player ) ) then if ( not targetPlayer ) or ( not level ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [level]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local levelName = exports.common:getLevelName( level ) if ( levelName ~= "" ) then exports.security:modifyElementData( player, "account:level", level, true ) exports.database:query( "UPDATE `accounts` SET `level` = ? WHERE `id` = ?", level, getElementData( player, "database:id" ) ) triggerClientEvent( root, "admin:updateHUD", root ) outputChatBox( "Updated " .. exports.common:formatString( getPlayerName( targetPlayer ) ) .. " level to " .. level .. " (" .. levelName .. ").", player, 95, 230, 95, false ) else outputChatBox( "Such level does not exist.", player, 230, 95, 95, false ) return end end end ) addCommandHandler( { "toggleduty", "adminduty", "toggleadminduty", "togduty", "aduty", "admin" }, function( player, cmd ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then local newStatus = not exports.common:isOnDuty( player ) exports.security:modifyElementData( player, "account:duty", newStatus, true ) triggerClientEvent( player, "admin:updateHUD", player ) outputChatBox( "You are now " .. ( newStatus and "on" or "off" ) .. " admin duty mode.", player, 230, 180, 95, false ) end end ) addCommandHandler( { "announce", "announcement", "message" }, function( player, cmd, ... ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then local tick = getTickCount( ) exports.messages:createMessage( root, table.concat( { ... }, " " ), nil, tick ) end end )
addCommandHandler( { "getpos", "pos", "getposition", "getxyz", "getloc", "loc", "getlocation" }, function( player, cmd, targetPlayer ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( targetPlayer ) then targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end else targetPlayer = player end local x, y, z = getElementPosition( targetPlayer ) local rotation = getPedRotation( targetPlayer ) local interior, dimension = getElementInterior( targetPlayer ), getElementDimension( targetPlayer ) x, y, z = math.floor( x * 100 ) / 100, math.floor( y * 100 ) / 100, math.floor( z * 100 ) / 100 rotation = math.floor( rotation * 100 ) / 100 local playerName = getPlayerName( targetPlayer ) outputChatBox( ( targetPlayer ~= player and exports.common:formatPlayerName( playerName ) or "Your" ) .. " position:", player, 230, 180, 95, false ) outputChatBox( " Position: " .. x .. ", " .. y .. ", " .. z, player, 230, 180, 95, false ) outputChatBox( " Rotation: " .. rotation .. ", Interior: " .. interior .. ", Dimension: " .. dimension, player, 230, 180, 95, false ) end end ) addCommandHandler( { "makeadmin", "setlevel", "setadminlevel" }, function( player, cmd, targetPlayer, level ) if ( exports.common:isPlayerServerSeniorAdmin( player ) ) then if ( not targetPlayer ) or ( not level ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [level]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local levelName = exports.common:getLevelName( tonumber( level ) ) if ( levelName ~= "" ) then exports.security:modifyElementData( targetPlayer, "account:level", level, true ) exports.database:query( "UPDATE `accounts` SET `level` = ? WHERE `id` = ?", level, getElementData( targetPlayer, "database:id" ) ) if ( level > 0 ) then triggerClientEvent( targetPlayer, "admin:showHUD", targetPlayer ) triggerClientEvent( root, "admin:updateHUD", root ) else triggerClientEvent( targetPlayer, "admin:hideHUD", targetPlayer ) end outputChatBox( "Updated " .. exports.common:formatString( getPlayerName( targetPlayer ) ) .. " level to " .. level .. " (" .. levelName .. ").", player, 95, 230, 95, false ) else outputChatBox( "Such level does not exist.", player, 230, 95, 95, false ) return end end end ) addCommandHandler( { "toggleduty", "adminduty", "toggleadminduty", "togduty", "aduty", "admin" }, function( player, cmd ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then local newStatus = not exports.common:isOnDuty( player ) exports.security:modifyElementData( player, "account:duty", newStatus, true ) triggerClientEvent( player, "admin:updateHUD", player ) outputChatBox( "You are now " .. ( newStatus and "on" or "off" ) .. " admin duty mode.", player, 230, 180, 95, false ) end end ) addCommandHandler( { "announce", "announcement", "message" }, function( player, cmd, ... ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then exports.messages:createMessage( root, table.concat( { ... }, " " ), nil, getTickCount( ) ) end end )
admin: fix issues with set admin
admin: fix issues with set admin
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
e4c3dc4b01ddaad24234f43db6a1cee0e63f1498
src/nodish/fs.lua
src/nodish/fs.lua
local S = require'syscall' local events = require'nodish.events' local stream = require'nodish.stream' local nextTick = require'nodish.nexttick'.nextTick local util = require'nodish._util' local ev = require'ev' local buffer = require'nodish.buffer' local loop = ev.Loop.default local createReadStream = function(path,options) options = options or {} local fd = options.fd local encoding = options.encoding local flags = options.flags or 'r' local mode = options.mode or "RW" local self = events.EventEmitter() self.watchers = {} stream.readable(self) if not fd then local err fd,err = S.open(path,"rdonly",438)--mode) if not fd then error(err) end end local readable = true fd:nonblock(true) self.destroy = function(_,hadError) for _,watcher in pairs(self.watchers) do watcher:stop(loop) end if fd then fd:close() sock = nil self:emit('close',hadError) end end self:once('error',function(err) local hadError = err and true self:destroy(hadError) end) self:once('fin',function() self:destroy(hadError) end) local buf local chunkSize = 4096*2 self._read = function() if not buf or not buf:isReleased() then buf = buffer.Buffer(chunkSize) end local ret,err = fd:read(buf.buf,chunkSize) print(ret,err,'e') if ret then if ret > 0 then buf:_setLength(ret) assert(buf.length == ret) data = buf return data,err elseif ret == 0 then return nil,nil,true end end return nil,err end self:addReadWatcher(fd:getfd()) self:resume() return self end local readFile = function(path,callback) local rs = createReadStream(path) rs:on('error',function(err) callback(err) end) local content = '' rs:on('data',function(data) print(data.length) content = content..data:toString() end) rs:on('fin',function() callback(nil,content) end) end return { createReadStream = createReadStream, readFile = readFile, }
local S = require'syscall' local events = require'nodish.events' local stream = require'nodish.stream' local nextTick = require'nodish.nexttick'.nextTick local util = require'nodish._util' local ev = require'ev' local buffer = require'nodish.buffer' local octal = require "syscall.helpers".octal local loop = ev.Loop.default local createReadStream = function(path,options) options = options or {} local fd = options.fd local encoding = options.encoding local flags = options.flags or 'r' local autoClose if options.autoClose ~= nil then autoClose = options.autoClose else autoClose = true end local mode if options.mode then mode = octal(options.mode) else mode = octal('0666') end local self = events.EventEmitter() self.watchers = {} stream.readable(self) if not fd then local err fd,err = S.open(path,"rdonly",438)--mode) if not fd then error(err) end end local readable = true fd:nonblock(true) self.destroy = function(_,hadError) for _,watcher in pairs(self.watchers) do watcher:stop(loop) end if fd and autoClose then fd:close() fd = nil self:emit('close',hadError) end end self:once('error',function(err) local hadError = err and true self:destroy(hadError) end) self:once('fin',function() self:destroy(hadError) end) local buf local chunkSize = 4096*2 self._read = function() if not buf or not buf:isReleased() then buf = buffer.Buffer(chunkSize) end local ret,err = fd:read(buf.buf,chunkSize) if ret then if ret > 0 then buf:_setLength(ret) assert(buf.length == ret) data = buf return data,err elseif ret == 0 then return nil,nil,true end end return nil,err end nextTick(function() self:emit('open',fd:getfd()) self:addReadWatcher(fd:getfd()) self:resume() end) return self end local readFile = function(path,callback) local rs = createReadStream(path) rs:on('error',function(err) callback(err) end) local content = '' rs:on('data',function(data) content = content..data:toString() end) rs:on('fin',function() callback(nil,content) end) end return { createReadStream = createReadStream, readFile = readFile, }
fix mode, postpone resume and open event
fix mode, postpone resume and open event
Lua
mit
lipp/nodish
1bf1fc6311433afdae443d671e6a97437db328e4
modules/spotify.lua
modules/spotify.lua
-- http://developer.spotify.com/en/metadata-api/overview/ local simplehttp = require'simplehttp' local json = require'json' local utify8 = function(str) str = str:gsub("\\u(....)", function(n) n = tonumber(n, 16) if(n < 128) then return string.char(n) elseif(n < 2048) then return string.char(192 + ((n - (n % 64)) / 64), 128 + (n % 64)) else return string.char(224 + ((n - (n % 4096)) / 4096), 128 + (((n % 4096) - (n % 64)) / 64), 128 + (n % 64)) end end) return str end local validType = { track = true, album = true, artist = true, } local handlers = { track = function(json) if(json.description) then return nil, json.description end local title = utify8(json.track.name) local album = utify8(json.track.album.name) local artists = {} for _, artist in ipairs(json.track.artists) do table.insert(artists, utify8(artist.name)) end return true, string.format('%s - [%s] %s', table.concat(artists, ', '), album, title) end, album = function(json) if(json.description) then return json.description end local artist = utify8(json.album.artist) local album = utify8(json.album.name) return true, string.format('%s - %s', artist, album) end, artist = function(json) if(json.description) then return json.description end return true, utify8(json.artist.name) end, } local handleData = function(metadata, json) local success, message = handlers[metadata.type](json) if(success) then return message else return string.format('%s is not a valid Spotify link', metadata.uri) end end local handleOutput = function(data) local uris = {} local uriOrder = {} for i, meta in ipairs(data.handled) do local uri = meta.uri if(not uris[uri]) then table.insert(uriOrder, uri) uris[uri] = {n = i, meta = meta} else uris[uri].n = string.format('%s+%d', uris[uri].n, i) end end local output = {} for i=1, #uriOrder do local lookup = uris[uriOrder[i]] local url = string.format('http://open.spotify.com/%s/%s', lookup.meta.type, lookup.meta.hash) table.insert(output, string.format('\002[%s]\002 %s - %s', lookup.n, lookup.meta.info, url)) end if(#output > 0) then ivar2:Msg('privmsg', data.destination, data.source, table.concat(output, ' ')) end end -- http://ws.spotify.com/lookup/1/.json?uri=spotify:artist:4YrKBkKSVeqDamzBPWVnSJ -- http://ws.spotify.com/lookup/1/.json?uri=spotify:album:6G9fHYDCoyEErUkHrFYfs4 -- http://ws.spotify.com/lookup/1/.json?uri=spotify:track:6NmXV4o6bmp704aPGyTVVG local fetchInformation = function(output, n, info) simplehttp( ('http://ws.spotify.com/lookup/1/.json?uri=%s'):format(info.uri), function(data) local message = handleData(info, json.decode(data)) output.handled[n] = {uri = info.uri, type = info.type, hash = info.hash, info = message} output.num = output.num - 1 if(output.num == 0) then handleOutput(output) end end ) end return { PRIVMSG = { function(self, source, destination, argument) local tmp = {} local index = 0 for uri, type, hash in argument:gmatch('(spotify:(%w+):(%S+))') do if(validType[type]) then index = index + 1 tmp[index] = { uri = uri, type = type, hash = hash, } end end if(index > 0) then local output = { num = index, source = source, destination = destination, handled = {} } for i=1, #tmp do fetchInformation(output, i, tmp[i]) end end end, } }
-- http://developer.spotify.com/en/metadata-api/overview/ local simplehttp = require'simplehttp' local json = require'json' require'tokyocabinet' require'logging.console' local log = logging.console() local spotify = tokyocabinet.hdbnew() local utify8 = function(str) str = str:gsub("\\u(....)", function(n) n = tonumber(n, 16) if(n < 128) then return string.char(n) elseif(n < 2048) then return string.char(192 + ((n - (n % 64)) / 64), 128 + (n % 64)) else return string.char(224 + ((n - (n % 4096)) / 4096), 128 + (((n % 4096) - (n % 64)) / 64), 128 + (n % 64)) end end) return str end local validType = { track = true, album = true, artist = true, } local handlers = { track = function(json) if(json.description) then return nil, json.description end local title = utify8(json.track.name) local album = utify8(json.track.album.name) local artists = {} for _, artist in ipairs(json.track.artists) do table.insert(artists, utify8(artist.name)) end return true, string.format('%s - [%s] %s', table.concat(artists, ', '), album, title) end, album = function(json) if(json.description) then return json.description end local artist = utify8(json.album.artist) local album = utify8(json.album.name) return true, string.format('%s - %s', artist, album) end, artist = function(json) if(json.description) then return json.description end return true, utify8(json.artist.name) end, } local handleData = function(metadata, json) local success, message = handlers[metadata.type](json) if(success) then return message else return string.format('%s is not a valid Spotify link', metadata.uri) end end local parseRFC1123 do local monthName = { Jan = '01', Feb = '02', Mar = '03', Apr = '04', May = '05', Jun = '06', Jul = '07', Aug = '08', Sep = '09', Oct = '10', Nov = '11', Dec = '12' } parseRFC1123 = function(date) -- RFC 1123: http://www.ietf.org/rfc/rfc1123.txt -- RFC 822: http://www.ietf.org/rfc/rfc822.txt local day = tonumber(date:sub(6, 7)) local month = tonumber(monthName[date:sub(9, 11)]) local year = tonumber(date:sub(13, 16)) local hour = tonumber(date:sub(18, 19)) local minute = tonumber(date:sub(21, 22)) local seconds = tonumber(date:sub(24, 25)) -- TODO: Handle EST and friends. local tz = date:sub(27) hour = hour + os.date('%H') - os.date('!%H') minute = minute + os.date('%M') - os.date('!%M') return os.time{day = day, month = month, year = year, hour = hour, min = minute, sec = seconds} end end local handleOutput = function(data) local uris = {} local uriOrder = {} for i, meta in ipairs(data.handled) do local uri = meta.uri if(not uris[uri]) then table.insert(uriOrder, uri) uris[uri] = {n = i, meta = meta} else uris[uri].n = string.format('%s+%d', uris[uri].n, i) end end local output = {} for i=1, #uriOrder do local lookup = uris[uriOrder[i]] local url = string.format('http://open.spotify.com/%s/%s', lookup.meta.type, lookup.meta.hash) table.insert(output, string.format('\002[%s]\002 %s - %s', lookup.n, lookup.meta.info, url)) end if(#output > 0) then ivar2:Msg('privmsg', data.destination, data.source, table.concat(output, ' ')) end end -- http://ws.spotify.com/lookup/1/.json?uri=spotify:artist:4YrKBkKSVeqDamzBPWVnSJ -- http://ws.spotify.com/lookup/1/.json?uri=spotify:album:6G9fHYDCoyEErUkHrFYfs4 -- http://ws.spotify.com/lookup/1/.json?uri=spotify:track:6NmXV4o6bmp704aPGyTVVG local fetchInformation = function(output, n, info) spotify:open('data/spotify', spotify.OWRITER + spotify.OCREAT) if(spotify[info.uri] and tonumber(spotify[info.uri .. ':timestamp']) > os.time()) then log:debug(string.format('spotify: Fetching %s from cache.', info.uri)) output.handled[n] = {uri = info.uri, type = info.type, hash = info.hash, info = spotify[info.uri]} output.num = output.num - 1 spotify:close() if(output.num == 0) then handleOutput(output) end return else spotify:close() log:info(string.format('spotify: Requesting information on %s.', info.uri)) simplehttp( ('http://ws.spotify.com/lookup/1/.json?uri=%s'):format(info.uri), function(data, url, response) local message = handleData(info, json.decode(data)) local expires = parseRFC1123(response.headers.Expires) spotify:open('data/spotify', spotify.OWRITER + spotify.OCREAT) spotify[info.uri] = message spotify[info.uri .. ':timestamp'] = expires spotify:close() output.handled[n] = {uri = info.uri, type = info.type, hash = info.hash, info = message} output.num = output.num - 1 if(output.num == 0) then handleOutput(output) end end ) end end return { PRIVMSG = { function(self, source, destination, argument) local tmp = {} local index = 0 for uri, type, hash in argument:gmatch('(spotify:(%w+):(%S+))') do if(validType[type]) then index = index + 1 tmp[index] = { uri = uri, type = type, hash = hash, } end end if(index > 0) then local output = { num = index, source = source, destination = destination, handled = {} } for i=1, #tmp do fetchInformation(output, i, tmp[i]) end end end, } }
spotify: Respect the cache requirements.
spotify: Respect the cache requirements. This fixes #22.
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
f6c6042238789696f01831cfc53581990c00437b
init.lua
init.lua
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 local curline = buffer:get_cur_line() local cur_col = buffer.column[buffer.current_pos] + 1 for i = 1, cur_col do local shifted_col = cur_col - i local c = curline:sub(shifted_col, shifted_col) if c == c:match("([^%w_-])") then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end return shift, suggestions end local function remove_type_info(text, position) local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() end buffer:auto_c_cancel() end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 local curline = buffer:get_cur_line() local cur_col = buffer.column[buffer.current_pos] + 1 for i = 1, cur_col do local shifted_col = cur_col - i local c = curline:sub(shifted_col, shifted_col) if c == c:match("([^%w_-])") then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end return shift, suggestions end local function remove_type_info(text, position) if buffer == nil or buffer:get_lexer(true) ~= "nim" then return end local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() end buffer:auto_c_cancel() end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
Fixed autocompletion reset in non-nim files
Fixed autocompletion reset in non-nim files
Lua
mit
xomachine/textadept-nim
c3dc712169391cd676ae56bbe6e4cdae472d4395
frontend/ui/reader/readerhighlight.lua
frontend/ui/reader/readerhighlight.lua
ReaderHighlight = InputContainer:new{} function ReaderHighlight:init() if Device:hasKeyboard() then self.key_events = { ShowToc = { { "." }, doc = _("highlight text") }, } end end function ReaderHighlight:initGesListener() self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, Hold = { GestureRange:new{ ges = "hold", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, } end function ReaderHighlight:onSetDimensions(dimen) -- update listening according to new screen dimen if Device:isTouchDevice() then self:initGesListener() end end function ReaderHighlight:onTap(arg, ges) if self.view.highlight.rect then self.view.highlight.rect = nil UIManager:setDirty(self.dialog, "partial") return true end end function ReaderHighlight:onHold(arg, ges) self.pos = self.view:screenToPageTransform(ges.pos) DEBUG("hold position in page", self.pos) local text_boxes = self.ui.document:getTextBoxes(self.pos.page) --DEBUG("page text", text_boxes) if not text_boxes or #text_boxes == 0 then DEBUG("no text box detected") return true end self.word_info = self:getWordFromBoxes(text_boxes, self.pos) DEBUG("hold word info in page", self.word_info) if self.word_info then -- if we extracted text directly if self.word_info.word then self.ui:handleEvent(Event:new("LookupWord", self.word_info.word)) -- or we will do OCR else UIManager:scheduleIn(0.1, function() local word_box = self.word_info.box word_box.x = word_box.x - math.floor(word_box.h * 0.2) word_box.y = word_box.y - math.floor(word_box.h * 0.4) word_box.w = word_box.w + math.floor(word_box.h * 0.4) word_box.h = word_box.h + math.floor(word_box.h * 0.6) local word = self.ui.document:getOCRWord(self.pos.page, word_box) DEBUG("OCRed word:", word) self.ui:handleEvent(Event:new("LookupWord", word)) end) end local screen_rect = self.view:pageToScreenTransform(self.pos.page, self.word_info.box) DEBUG("highlight word rect", screen_rect) if screen_rect then screen_rect.x = screen_rect.x - screen_rect.h * 0.2 screen_rect.y = screen_rect.y - screen_rect.h * 0.2 screen_rect.w = screen_rect.w + screen_rect.h * 0.4 screen_rect.h = screen_rect.h + screen_rect.h * 0.4 self.view.highlight.rect = screen_rect UIManager:setDirty(self.dialog, "partial") end end return true end function ReaderHighlight:getWordFromBoxes(boxes, pos) local function ges_inside(x0, y0, x1, y1) local x, y = pos.x, pos.y if x0 ~= nil and y0 ~= nil and x1 ~= nil and y1 ~= nil then if x0 <= x and y0 <= y and x1 >= x and y1 >= y then return true end end return false end for i = 1, #boxes do local l = boxes[i] if ges_inside(l.x0, l.y0, l.x1, l.y1) then --DEBUG("line box", l.x0, l.y0, l.x1, l.y1) for j = 1, #boxes[i] do local w = boxes[i][j] if ges_inside(w.x0, w.y0, w.x1, w.y1) then local box = Geom:new{ x = w.x0, y = w.y0, w = w.x1 - w.x0, h = w.y1 - w.y0, } return { word = w.word, box = box, } end -- end if inside word box end -- end for each word end -- end if inside line box end -- end for each line end
ReaderHighlight = InputContainer:new{} function ReaderHighlight:init() if Device:hasKeyboard() then self.key_events = { ShowToc = { { "." }, doc = _("highlight text") }, } end end function ReaderHighlight:initGesListener() self.ges_events = { Tap = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, Hold = { GestureRange:new{ ges = "hold", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } } }, } end function ReaderHighlight:onSetDimensions(dimen) -- update listening according to new screen dimen if Device:isTouchDevice() then self:initGesListener() end end function ReaderHighlight:onTap(arg, ges) if self.view.highlight.rect then self.view.highlight.rect = nil UIManager:setDirty(self.dialog, "partial") return true end end function ReaderHighlight:onHold(arg, ges) self.pos = self.view:screenToPageTransform(ges.pos) DEBUG("hold position in page", self.pos) if not self.pos then DEBUG("not inside page area") return true end local text_boxes = self.ui.document:getTextBoxes(self.pos.page) --DEBUG("page text", text_boxes) if not text_boxes or #text_boxes == 0 then DEBUG("no text box detected") return true end self.word_info = self:getWordFromBoxes(text_boxes, self.pos) DEBUG("hold word info in page", self.word_info) if self.word_info then -- if we extracted text directly if self.word_info.word then self.ui:handleEvent(Event:new("LookupWord", self.word_info.word)) -- or we will do OCR else UIManager:scheduleIn(0.1, function() local word_box = self.word_info.box word_box.x = word_box.x - math.floor(word_box.h * 0.2) word_box.y = word_box.y - math.floor(word_box.h * 0.4) word_box.w = word_box.w + math.floor(word_box.h * 0.4) word_box.h = word_box.h + math.floor(word_box.h * 0.6) local word = self.ui.document:getOCRWord(self.pos.page, word_box) DEBUG("OCRed word:", word) self.ui:handleEvent(Event:new("LookupWord", word)) end) end local screen_rect = self.view:pageToScreenTransform(self.pos.page, self.word_info.box) DEBUG("highlight word rect", screen_rect) if screen_rect then screen_rect.x = screen_rect.x - screen_rect.h * 0.2 screen_rect.y = screen_rect.y - screen_rect.h * 0.2 screen_rect.w = screen_rect.w + screen_rect.h * 0.4 screen_rect.h = screen_rect.h + screen_rect.h * 0.4 self.view.highlight.rect = screen_rect UIManager:setDirty(self.dialog, "partial") end end return true end function ReaderHighlight:getWordFromBoxes(boxes, pos) local function ges_inside(x0, y0, x1, y1) local x, y = pos.x, pos.y if x0 ~= nil and y0 ~= nil and x1 ~= nil and y1 ~= nil then if x0 <= x and y0 <= y and x1 >= x and y1 >= y then return true end end return false end for i = 1, #boxes do local l = boxes[i] if ges_inside(l.x0, l.y0, l.x1, l.y1) then --DEBUG("line box", l.x0, l.y0, l.x1, l.y1) for j = 1, #boxes[i] do local w = boxes[i][j] if ges_inside(w.x0, w.y0, w.x1, w.y1) then local box = Geom:new{ x = w.x0, y = w.y0, w = w.x1 - w.x0, h = w.y1 - w.y0, } return { word = w.word, box = box, } end -- end if inside word box end -- end for each word end -- end if inside line box end -- end for each line end
fix reader crash when hold pos is outside of page area
fix reader crash when hold pos is outside of page area
Lua
agpl-3.0
koreader/koreader,koreader/koreader,NiLuJe/koreader,apletnev/koreader,chrox/koreader,NickSavage/koreader,ashang/koreader,Markismus/koreader,ashhher3/koreader,poire-z/koreader,lgeek/koreader,Frenzie/koreader,robert00s/koreader,noname007/koreader,poire-z/koreader,chihyang/koreader,NiLuJe/koreader,Frenzie/koreader,pazos/koreader,frankyifei/koreader,mwoz123/koreader,mihailim/koreader,Hzj-jie/koreader,houqp/koreader
648504119ec0e31a1472606eabfb0004bb162ac8
lualib/http/sockethelper.lua
lualib/http/sockethelper.lua
local socket = require "socket" local skynet = require "skynet" local readbytes = socket.read local writebytes = socket.write local sockethelper = {} local socket_error = setmetatable({} , { __tostring = function() return "[Socket Error]" end }) sockethelper.socket_error = socket_error local function preread(fd, str) return function (sz) if str then if sz == #str or sz == nil then local ret = str str = nil return ret else if sz < #str then local ret = str:sub(1,sz) str = str:sub(sz + 1) return ret else sz = sz - #str local ret = readbytes(fd, sz) if ret then return str .. ret else error(socket_error) end end end else local ret = readbytes(fd, sz) if ret then return ret else error(socket_error) end end end end function sockethelper.readfunc(fd, pre) if pre then return preread(fd, pre) end return function (sz) local ret = readbytes(fd, sz) if ret then return ret else error(socket_error) end end end sockethelper.readall = socket.readall function sockethelper.writefunc(fd) return function(content) local ok = writebytes(fd, content) if not ok then error(socket_error) end end end function sockethelper.connect(host, port, timeout) local fd if timeout then local drop_fd -- asynchronous connect skynet.fork(function() fd = socket.open(host, port) if drop_fd then -- sockethelper.connect already return, and raise socket_error socket.close(fd) end end) skynet.sleep(timeout) if not fd then -- not connect yet drop_fd = true end else -- block connect fd = socket.open(host, port) end if fd then return fd end error(socket_error) end function sockethelper.close(fd) socket.close(fd) end return sockethelper
local socket = require "socket" local skynet = require "skynet" local readbytes = socket.read local writebytes = socket.write local sockethelper = {} local socket_error = setmetatable({} , { __tostring = function() return "[Socket Error]" end }) sockethelper.socket_error = socket_error local function preread(fd, str) return function (sz) if str then if sz == #str or sz == nil then local ret = str str = nil return ret else if sz < #str then local ret = str:sub(1,sz) str = str:sub(sz + 1) return ret else sz = sz - #str local ret = readbytes(fd, sz) if ret then return str .. ret else error(socket_error) end end end else local ret = readbytes(fd, sz) if ret then return ret else error(socket_error) end end end end function sockethelper.readfunc(fd, pre) if pre then return preread(fd, pre) end return function (sz) local ret = readbytes(fd, sz) if ret then return ret else error(socket_error) end end end sockethelper.readall = socket.readall function sockethelper.writefunc(fd) return function(content) local ok = writebytes(fd, content) if not ok then error(socket_error) end end end function sockethelper.connect(host, port, timeout) local fd if timeout then local drop_fd local co = coroutine.running() -- asynchronous connect skynet.fork(function() fd = socket.open(host, port) if drop_fd then -- sockethelper.connect already return, and raise socket_error socket.close(fd) else -- socket.open before sleep, wakeup. skynet.wakeup(co) end end) skynet.sleep(timeout) if not fd then -- not connect yet drop_fd = true end else -- block connect fd = socket.open(host, port) end if fd then return fd end error(socket_error) end function sockethelper.close(fd) socket.close(fd) end return sockethelper
bugfix: wakeup sleep
bugfix: wakeup sleep
Lua
mit
xcjmine/skynet,sundream/skynet,ag6ag/skynet,kyle-wang/skynet,korialuo/skynet,Ding8222/skynet,iskygame/skynet,jxlczjp77/skynet,pigparadise/skynet,jxlczjp77/skynet,icetoggle/skynet,jxlczjp77/skynet,QuiQiJingFeng/skynet,icetoggle/skynet,pigparadise/skynet,JiessieDawn/skynet,firedtoad/skynet,zhangshiqian1214/skynet,bttscut/skynet,sundream/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,liuxuezhan/skynet,hongling0/skynet,cmingjian/skynet,sanikoyes/skynet,ag6ag/skynet,QuiQiJingFeng/skynet,zhouxiaoxiaoxujian/skynet,hongling0/skynet,xjdrew/skynet,codingabc/skynet,czlc/skynet,iskygame/skynet,Ding8222/skynet,cmingjian/skynet,bigrpg/skynet,bttscut/skynet,great90/skynet,czlc/skynet,xjdrew/skynet,great90/skynet,sanikoyes/skynet,icetoggle/skynet,ag6ag/skynet,korialuo/skynet,zhangshiqian1214/skynet,firedtoad/skynet,fztcjjl/skynet,xcjmine/skynet,liuxuezhan/skynet,codingabc/skynet,sundream/skynet,wangyi0226/skynet,iskygame/skynet,cloudwu/skynet,cloudwu/skynet,zhangshiqian1214/skynet,xcjmine/skynet,zhangshiqian1214/skynet,czlc/skynet,xjdrew/skynet,wangyi0226/skynet,codingabc/skynet,cmingjian/skynet,hongling0/skynet,JiessieDawn/skynet,bttscut/skynet,QuiQiJingFeng/skynet,zhouxiaoxiaoxujian/skynet,firedtoad/skynet,liuxuezhan/skynet,bigrpg/skynet,ypengju/skynet_comment,zhouxiaoxiaoxujian/skynet,fztcjjl/skynet,wangyi0226/skynet,ypengju/skynet_comment,sanikoyes/skynet,kyle-wang/skynet,ypengju/skynet_comment,bigrpg/skynet,korialuo/skynet,liuxuezhan/skynet,fztcjjl/skynet,cloudwu/skynet,Ding8222/skynet,pigparadise/skynet,JiessieDawn/skynet,great90/skynet,kyle-wang/skynet
91807837046a4b4efcd09ddae9258deb6e5a115d
test_scripts/Polices/Policy_Table_Update/040_ATF_P_TC_PTU_Policies_Manager_Changes_Status_To_UPDATE_NEEDED.lua
test_scripts/Polices/Policy_Table_Update/040_ATF_P_TC_PTU_Policies_Manager_Changes_Status_To_UPDATE_NEEDED.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UPDATE_NEEDED” -- -- Description: -- PoliciesManager must change the status to “UPDATE_NEEDED” and notify HMI with -- OnStatusUpdate(“UPDATE_NEEDED”) in case the timeout taken from "timeout_after_x_seconds" field -- of LocalPT or "timeout between retries" is expired before PoliciesManager receives SystemRequest -- with PTU from mobile application. -- -- Preconditions: -- 1. Register new app -- 2. Activate app -- Steps: -- 1. Start PTU sequence -- 2. Verify that SDL.OnStatusUpdate status changed: UPDATE_NEEDED -> UPDATING -- 3. Sleep right after HMI->SDL: BC.SystemRequest for about 70 sec. -- 4. Verify that SDL.OnStatusUpdate status changed: UPDATING -> UPDATE_NEEDED -- -- Expected result: -- Status of SDL.OnStatusUpdate notification changed: UPDATING -> UPDATE_NEEDED -- -- TODO: Reduce value of timeout_after_x_seconds parameter in LPT in order to make test faster --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_ChangeStatus_Update_Needed() local time_update_needed = {} local time_system_request = {} local endpoints = {} local is_test_fail = false local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") local seconds_between_retries = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value end if seconds_between_retries[1] == nil then self:FailTestCase("Problem with accessing in Policy table snapshot. Value not exists") end local time_wait = (timeout_pts*seconds_between_retries[1]*1000) local function verify_retry_sequence() time_update_needed[#time_update_needed + 1] = timestamp() local time_1 = time_update_needed[#time_update_needed] local time_2 = time_system_request[#time_system_request] local timeout = (time_1 - time_2) if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for first retry sequence is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms") else print("timeout is as expected: "..tostring(timeout_pts*1000).."ms. real: "..timeout) end end local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" }) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"}):Timeout(12000) :Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2):Timeout(time_wait) :Do(function(_,data) if(data.params.status == "UPDATE_NEEDED" ) then --first retry sequence verify_retry_sequence() end end) end) commonTestCases:DelayedExp(time_wait) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UPDATE_NEEDED” -- -- Description: -- PoliciesManager must change the status to “UPDATE_NEEDED” and notify HMI with -- OnStatusUpdate(“UPDATE_NEEDED”) in case the timeout taken from "timeout_after_x_seconds" field -- of LocalPT or "timeout between retries" is expired before PoliciesManager receives SystemRequest -- with PTU from mobile application. -- -- Preconditions: -- 1. Register new app -- 2. Activate app -- Steps: -- 1. Start PTU sequence -- 2. Verify that SDL.OnStatusUpdate status changed: UPDATE_NEEDED -> UPDATING -- 3. Sleep right after HMI->SDL: BC.SystemRequest for about 70 sec. -- 4. Verify that SDL.OnStatusUpdate status changed: UPDATING -> UPDATE_NEEDED -- -- Expected result: -- Status of SDL.OnStatusUpdate notification changed: UPDATING -> UPDATE_NEEDED -- -- TODO: Reduce value of timeout_after_x_seconds parameter in LPT in order to make test faster --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_ChangeStatus_Update_Needed() local time_update_needed = {} local time_system_request = {} local endpoints = {} local is_test_fail = false local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") local seconds_between_retries = {} for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value end if seconds_between_retries[1] == nil then self:FailTestCase("Problem with accessing in Policy table snapshot. Value not exists") end local time_wait = (timeout_pts*seconds_between_retries[1]*1000) local function verify_retry_sequence() time_update_needed[#time_update_needed + 1] = timestamp() local time_1 = time_update_needed[#time_update_needed] local time_2 = time_system_request[#time_system_request] local timeout = (time_1 - time_2) if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for first retry sequence is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms") else print("timeout is as expected: "..tostring(timeout_pts*1000).."ms. real: "..timeout) end end local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" }) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"}):Timeout(12000) :Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2):Timeout(time_wait+2000) :Do(function(_,data) if(data.params.status == "UPDATE_NEEDED" ) then --first retry sequence verify_retry_sequence() end end) end) commonTestCases:DelayedExp(time_wait) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
135effa830a7a5bd5b7f1c670de6a6a7876d7887
luci/model-scutclient.lua
luci/model-scutclient.lua
-- LuCI by libc0607 (libc0607@gmail.com) -- 华工路由群 262939451 scut = Map( "scutclient", translate("华南理工大学客户端 设置"), ' <a href="'..luci.dispatcher.build_url("admin/network/wireless/radio0.network1")..'">' ..translate("点此处去设置Wi-Fi") ..'</a>'.."<br />" ..' <a href="'..luci.dispatcher.build_url("admin/network/network/wan")..'">' ..translate("点此处去设置IP")..'</a>'.."<br />" ..' <a href="'..luci.dispatcher.build_url("admin/system/crontab")..'">' ..translate("点此处去设置定时任务")..'</a>'.."<br />" .."<a href=\"http://jq.qq.com/?_wv=1027&k=27KCAyx\">" .."点击加入【华工路由器审核群】:262939451".."</a><br />" ) function scut.on_commit(self) os.execute("/etc/init.d/scutclient enable") os.execute("/etc/init.d/scutclient restart > /dev/null") end -- config option scut_option = scut:section(TypedSection, "option", translate("选项")) scut_option.anonymous = true scut_option_enable = scut_option:option(Flag, "enable", translate("启用")) scut_option_enable.addremove = false scut_option_enable.rmempty = false scut_option_debug = scut_option:option(Flag, "debug", translate("打开调试日志")) scut_option_debug.addremove = false scut_option_debug.rmempty = false scut_option_mode = scut_option:option(ListValue, "mode", translate("客户端选择")) scut_option_mode.rmempty = false --scut_option_mode:value("Young") -- No longer be used scut_option_mode:value("Drcom") scut_option_mode.default = "Drcom" -- config scutclient scut_client = scut:section(TypedSection, "scutclient", translate("用户信息")) scut_client.anonymous = true scut_client_username = scut_client:option(Value, "username", translate("用户名"), "学校提供的用户名,一般是学号") scut_client_username.rmempty = false scut_client_password = scut_client:option(Value, "password", translate("密码"), "学校提供的密码,一般是学号或者生日后六位") scut_client_password.rmempty = false scut_client_password.password = true -- config drcom scut_drcom = scut:section(TypedSection, "drcom", translate("Drcom设置")) scut_drcom.anonymous = true scut_drcom_version = scut_drcom:option(Value, "version", translate("Drcom版本")) scut_drcom_version.rmempty = false scut_drcom_version:value("4472434f4d00cf072a00332e31332e302d32342d67656e65726963") scut_drcom_version:value("4472434f4d0096022a00636b2031") scut_drcom_version:value("4472434f4d0096022a") scut_drcom_hash = scut_drcom:option(Value, "hash", translate("DrAuthSvr.dll版本")) scut_drcom_hash.rmempty = false scut_drcom_hash:value("915e3d0281c3a0bdec36d7f9c15e7a16b59c12b8") scut_drcom_hash:value("d985f3d51656a15837e00fab41d3013ecfb6313f") scut_drcom_hash:value("2ec15ad258aee9604b18f2f8114da38db16efd00") scut_drcom_server = scut_drcom:option(Value, "server_auth_ip", translate("服务器IP")) scut_drcom_server.rmempty = false scut_drcom_server.datatype = "ip4addr" scut_drcom_server:value("211.38.210.131") --[[ 主机名列表预置 1.生成一个 DESKTOP-XXXXXXX 的随机 2.dhcp分配的第一个 ]]-- scut_drcom_hostname = scut_drcom:option(Value, "hostname", translate("向服务器发送的主机名")) scut_drcom_hostname.rmempty = false local random_hostname = "DESKTOP-" local randtmp -- 抄的 string.split = function(s, p) local rt = {} string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end) return rt end math.randomseed(os.time()) for i = 1, 7 do randtmp = math.random(1, 36) random_hostname = (randtmp > 10) and random_hostname..string.char(randtmp+54) or random_hostname..string.char(randtmp+47) end -- 获取dhcp列表,加入第一个主机名候选 local dhcp_hostnames = string.split(luci.sys.exec("cat /tmp/dhcp.leases|awk {'print $4'}"), "\n") or {} scut_drcom_hostname:value(random_hostname) scut_drcom_hostname:value(dhcp_hostnames[1]) scut_drcom_delay = scut_drcom:option(Value, "delay", translate("开机延时后拨号(秒)")) scut_drcom_delay.rmempty = false scut_drcom_delay.datatype = "integer" scut_drcom_delay:value("30") scut_drcom_delay:value("60") scut_drcom_delay:value("99") scut_drcom_delay.default="99" return scut
-- LuCI by libc0607 (libc0607@gmail.com) -- 华工路由群 262939451 scut = Map( "scutclient", translate("华南理工大学客户端 设置"), ' <a href="'..luci.dispatcher.build_url("admin/network/wireless/radio0.network1")..'">' ..translate("点此处去设置Wi-Fi") ..'</a>'.."<br />" ..' <a href="'..luci.dispatcher.build_url("admin/network/network/wan")..'">' ..translate("点此处去设置IP")..'</a>'.."<br />" ..' <a href="'..luci.dispatcher.build_url("admin/system/crontab")..'">' ..translate("点此处去设置定时任务")..'</a>'.."<br />" .."<a href=\"http://jq.qq.com/?_wv=1027&k=27KCAyx\">" .."点击加入【华工路由器审核群】:262939451".."</a><br />" ) function scut.on_commit(self) os.execute("/etc/init.d/scutclient enable") os.execute("/etc/init.d/scutclient restart > /dev/null") end -- config option scut_option = scut:section(TypedSection, "option", translate("选项")) scut_option.anonymous = true scut_option_enable = scut_option:option(Flag, "enable", translate("启用")) scut_option_enable.addremove = false scut_option_enable.rmempty = false scut_option_debug = scut_option:option(Flag, "debug", translate("打开调试日志")) scut_option_debug.addremove = false scut_option_debug.rmempty = false scut_option_mode = scut_option:option(ListValue, "mode", translate("客户端选择")) scut_option_mode.rmempty = false --scut_option_mode:value("Young") -- No longer be used scut_option_mode:value("Drcom") scut_option_mode.default = "Drcom" -- config scutclient scut_client = scut:section(TypedSection, "scutclient", translate("用户信息")) scut_client.anonymous = true scut_client_username = scut_client:option(Value, "username", translate("用户名"), "学校提供的用户名,一般是学号") scut_client_username.rmempty = false scut_client_password = scut_client:option(Value, "password", translate("密码"), "学校提供的密码,一般是学号或者生日后六位") scut_client_password.rmempty = false scut_client_password.password = true -- config drcom scut_drcom = scut:section(TypedSection, "drcom", translate("Drcom设置")) scut_drcom.anonymous = true scut_drcom_version = scut_drcom:option(Value, "version", translate("Drcom版本")) scut_drcom_version.rmempty = false scut_drcom_version:value("4472434f4d00cf072a00332e31332e302d32342d67656e65726963") scut_drcom_version:value("4472434f4d0096022a00636b2031") scut_drcom_version:value("4472434f4d0096022a") scut_drcom_version.default = "4472434f4d0096022a00636b2031" scut_drcom_hash = scut_drcom:option(Value, "hash", translate("DrAuthSvr.dll版本")) scut_drcom_hash.rmempty = false scut_drcom_hash:value("915e3d0281c3a0bdec36d7f9c15e7a16b59c12b8") scut_drcom_hash:value("d985f3d51656a15837e00fab41d3013ecfb6313f") scut_drcom_hash:value("2ec15ad258aee9604b18f2f8114da38db16efd00") scut_drcom_hash.default = "2ec15ad258aee9604b18f2f8114da38db16efd00" scut_drcom_server = scut_drcom:option(Value, "server_auth_ip", translate("服务器IP")) scut_drcom_server.rmempty = false scut_drcom_server.datatype = "ip4addr" scut_drcom_server:value("211.38.210.131") --[[ 主机名列表预置 1.生成一个 DESKTOP-XXXXXXX 的随机 2.dhcp分配的第一个 ]]-- scut_drcom_hostname = scut_drcom:option(Value, "hostname", translate("向服务器发送的主机名")) scut_drcom_hostname.rmempty = false local random_hostname = "DESKTOP-" local randtmp -- 抄的 string.split = function(s, p) local rt = {} string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end) return rt end math.randomseed(os.time()) for i = 1, 7 do randtmp = math.random(1, 36) random_hostname = (randtmp > 10) and random_hostname..string.char(randtmp+54) or random_hostname..string.char(randtmp+47) end -- 获取dhcp列表,加入第一个主机名候选 local dhcp_hostnames = string.split(luci.sys.exec("cat /tmp/dhcp.leases|awk {'print $4'}"), "\n") or {} scut_drcom_hostname:value(random_hostname) scut_drcom_hostname:value(dhcp_hostnames[1]) scut_drcom_delay = scut_drcom:option(Value, "delay", translate("开机延时后拨号(秒)")) scut_drcom_delay.rmempty = false scut_drcom_delay.datatype = "integer" scut_drcom_delay:value("30") scut_drcom_delay:value("60") scut_drcom_delay:value("99") scut_drcom_delay.default="99" return scut
修正一些bug,mac双重获取,自动重连
修正一些bug,mac双重获取,自动重连
Lua
agpl-3.0
981213/scutclient,981213/scutclient,scutclient/scutclient,hanwckf/scutclient,scutclient/scutclient,hanwckf/scutclient
d326fe5f66becd014ca02a252739ef54007f8abb
premake5.lua
premake5.lua
local build_dir = "build/" .. _ACTION -------------------------------------------------------------------------------- solution "Libs" configurations { "Release", "Debug" } architecture "x64" location (build_dir) objdir (build_dir .. "/obj") warnings "Extra" configuration { "Debug" } targetdir (build_dir .. "/bin/Debug") configuration { "Release" } targetdir (build_dir .. "/bin/Release") configuration { "Debug" } defines { "_DEBUG" } symbols "On" configuration { "Release" } defines { "NDEBUG" } symbols "Off" optimize "On" -- On ==> -O2 -- Full ==> -O3 configuration { "gmake" } buildoptions { -- "-march=haswell", "-std=c++14", "-Wformat", "-Wsign-compare", "-Wsign-conversion", -- "-pedantic", "-fvisibility=hidden", "-fno-exceptions", "-fno-rtti", -- "-fno-omit-frame-pointer", -- "-ftime-report", } configuration { "gmake", "Debug" } buildoptions { "-fsanitize=undefined", } linkoptions { "-fsanitize=undefined", } configuration { "vs*" } buildoptions { -- "/arch:AVX2", -- "/GR-", } -- defines { -- "_CRT_SECURE_NO_WARNINGS=1", -- "_SCL_SECURE_NO_WARNINGS=1", -- } configuration { "windows" } characterset "Unicode" -------------------------------------------------------------------------------- group "Libs" project "fmtxx" language "C++" kind "SharedLib" files { "Format.h", "Format.cc", } defines { "FMTXX_SHARED", "FMTXX_EXPORT", } includedirs { "./", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-pedantic", } -------------------------------------------------------------------------------- group "Tests" project "Test" language "C++" kind "ConsoleApp" files { "Test.cc", } defines { "FMTXX_SHARED", } includedirs { "./", } links { "fmtxx", }
local build_dir = "build/" .. _ACTION -------------------------------------------------------------------------------- solution "Libs" configurations { "Release", "Debug" } architecture "x64" location (build_dir) objdir (build_dir .. "/obj") warnings "Extra" configuration { "Debug" } targetdir (build_dir .. "/bin/Debug") configuration { "Release" } targetdir (build_dir .. "/bin/Release") configuration { "Debug" } defines { "_DEBUG" } symbols "On" configuration { "Release" } defines { "NDEBUG" } symbols "Off" optimize "On" -- On ==> -O2 -- Full ==> -O3 configuration { "gmake" } buildoptions { -- "-march=haswell", "-std=c++14", "-Wformat", "-Wsign-compare", "-Wsign-conversion", -- "-pedantic", "-fvisibility=hidden", "-fno-exceptions", "-fno-rtti", -- "-fno-omit-frame-pointer", -- "-ftime-report", } configuration { "gmake", "Debug", "not Windows" } buildoptions { "-fsanitize=undefined", } linkoptions { "-fsanitize=undefined", } configuration { "vs*" } buildoptions { "/std:c++latest", -- "/arch:AVX2", -- "/GR-", } -- defines { -- "_CRT_SECURE_NO_WARNINGS=1", -- "_SCL_SECURE_NO_WARNINGS=1", -- } configuration { "windows" } characterset "Unicode" -------------------------------------------------------------------------------- group "Libs" project "fmtxx" language "C++" kind "SharedLib" files { "Format.h", "Format.cc", } defines { "FMTXX_SHARED", "FMTXX_EXPORT", } includedirs { "./", } configuration { "gmake" } buildoptions { "-Wsign-compare", "-Wsign-conversion", "-Wold-style-cast", "-pedantic", } -------------------------------------------------------------------------------- group "Tests" project "Test" language "C++" kind "ConsoleApp" files { "Test.cc", } defines { "FMTXX_SHARED", } includedirs { "./", } links { "fmtxx", }
Fix Windows build
Fix Windows build
Lua
mit
abolz/Format
584884deb8ac62ef49f7e11e1b893ff56369ea77
route.lua
route.lua
routes = {} routes['^/(.*).(jpg|gif|png|css|js|ico|swf|flv|mp3|mp4|woff|eot|ttf|otf|svg)'] = function() header('Cache-Control: max-age=864000') sendfile(headers.uri) end routes['^/user/:user_id'] = function(r) print('User ID: ', r.user_id) end routes['^/user/:user_id/:post'] = function(r) print('User ID: ', r.user_id) print('\nPost: ', r.post) end routes['^/(.*)'] = function(r) dofile('/index.lua') end --[[ others you want :) ]] if not router(headers.uri, routes, '/') then -- try local scripts --[[ / => /index.lua /hello => /hello.lua if not exists then try /hello/index.lua /hello/ => /hello.lua if not exists then try /hello/index.lua ]] header('HTTP/1.1 404 Not Found') echo('File Not Found!') end
routes = {} routes['^/(.*).(jpg|gif|png|css|js|ico|swf|flv|mp3|mp4|woff|eot|ttf|otf|svg)'] = function() header('Cache-Control: max-age=864000') sendfile(headers.uri) end routes['^/user/:user_id'] = function(r) print('User ID: ', r.user_id) end routes['^/user/:user_id/:post(.+)'] = function(r) print('User ID: ', r.user_id) print(' Post: ', r.post) end routes['^/(.*)'] = function(r) dofile('/index.lua') end --[[ others you want :) ]] -- if the 3rd argument is a path, then router will try to get local lua script file first if not router(headers.uri, routes, '/') then header('HTTP/1.1 404 Not Found') echo('File Not Found!') end
fix router example
fix router example
Lua
mit
oneoo/alilua,tempbottle/alilua,tempbottle/alilua,zhangf911/alilua,oneoo/alilua,zhangf911/alilua,oneoo/alilua,zhangf911/alilua,tempbottle/alilua
4de63fc5e7e3d471188a2e67dc60a9f31b6eaa39
nvim/init.lua
nvim/init.lua
vim.cmd [[ source ~/.vimrc ]] -- === lspconfig === -- Mappings. -- See `:help vim.diagnostic.*` for documentation on any of the below functions local opts = { noremap=true, silent=true } vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts) vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts) vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts) vim.keymap.set('n', '<space>q', vim.diagnostic.setloclist, opts) -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) -- Enable completion triggered by <c-x><c-o> vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. -- See `:help vim.lsp.*` for documentation on any of the below functions local bufopts = { noremap=true, silent=true, buffer=bufnr } vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts) vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts) vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts) vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, bufopts) vim.keymap.set('n', '<space>wa', vim.lsp.buf.add_workspace_folder, bufopts) vim.keymap.set('n', '<space>wr', vim.lsp.buf.remove_workspace_folder, bufopts) vim.keymap.set('n', '<space>wl', function() print(vim.inspect(vim.lsp.buf.list_workspace_folders())) end, bufopts) vim.keymap.set('n', '<space>D', vim.lsp.buf.type_definition, bufopts) vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts) vim.keymap.set('n', '<space>ca', vim.lsp.buf.code_action, bufopts) vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts) vim.keymap.set('n', '<space>f', vim.lsp.buf.formatting, bufopts) end -- Use a loop to conveniently call 'setup' on multiple servers and -- map buffer local keybindings when the language server attaches local servers = { 'pyright', 'clangd' } for _, lsp in pairs(servers) do require('lspconfig')[lsp].setup { on_attach = on_attach, flags = { -- This will be the default in neovim 0.7+ debounce_text_changes = 150, } } end -- === nvim-cmp === -- Add additional capabilities supported by nvim-cmp local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local lspconfig = require('lspconfig') -- Enable some language servers with the additional completion capabilities offered by nvim-cmp for _, lsp in ipairs(servers) do lspconfig[lsp].setup { -- on_attach = my_custom_on_attach, capabilities = capabilities, } end -- luasnip setup local luasnip = require 'luasnip' -- nvim-cmp setup local cmp = require 'cmp' cmp.setup { snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = cmp.mapping.preset.insert({ ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = true, }, ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() else fallback() end end, { 'i', 's' }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { 'i', 's' }), }), sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, }, }
vim.cmd [[ source ~/.vimrc ]] -- === lspconfig === -- Mappings. -- See `:help vim.diagnostic.*` for documentation on any of the below functions local opts = { noremap=true, silent=true } vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts) vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts) vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts) vim.keymap.set('n', '<space>q', vim.diagnostic.setloclist, opts) -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) -- Enable completion triggered by <c-x><c-o> vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. -- See `:help vim.lsp.*` for documentation on any of the below functions local bufopts = { noremap=true, silent=true, buffer=bufnr } vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts) vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts) vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts) vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, bufopts) vim.keymap.set('n', '<space>wa', vim.lsp.buf.add_workspace_folder, bufopts) vim.keymap.set('n', '<space>wr', vim.lsp.buf.remove_workspace_folder, bufopts) vim.keymap.set('n', '<space>wl', function() print(vim.inspect(vim.lsp.buf.list_workspace_folders())) end, bufopts) vim.keymap.set('n', '<space>D', vim.lsp.buf.type_definition, bufopts) vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts) vim.keymap.set('n', '<space>ca', vim.lsp.buf.code_action, bufopts) vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts) vim.keymap.set('n', '<space>f', vim.lsp.buf.formatting, bufopts) end -- Add additional capabilities supported by nvim-cmp local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local servers = { 'pyright', 'clangd' } local lspconfig = require('lspconfig') for _, lsp in ipairs(servers) do lspconfig[lsp].setup { on_attach = on_attach, flags = { -- This will be the default in neovim 0.7+ debounce_text_changes = 150, }, capabilities = capabilities, } end -- luasnip setup local luasnip = require 'luasnip' -- nvim-cmp setup local cmp = require 'cmp' cmp.setup { snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = cmp.mapping.preset.insert({ ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = true, }, ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() else fallback() end end, { 'i', 's' }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { 'i', 's' }), }), sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, }, }
[nvim] Fix nvim-lspconfig
[nvim] Fix nvim-lspconfig
Lua
mit
raulchen/dotfiles,raulchen/dotfiles
dad568bea5ac767a8d7c2e0ee5df032d10651be1
test_scripts/RC/GetInteriorVehicleData/012_Transfering_of_isSubscribed_parameter_in_case_request_from_Mob_app_with_subscribe_parameter_but_response_from_HMI_without_isSubscribed.lua
test_scripts/RC/GetInteriorVehicleData/012_Transfering_of_isSubscribed_parameter_in_case_request_from_Mob_app_with_subscribe_parameter_but_response_from_HMI_without_isSubscribed.lua
--------------------------------------------------------------------------------------------------- -- Requirement summary: -- [SDL_RC] Current module status data GetInteriorVehicleData -- -- Description: -- In case: -- 1) RC app sends valid and allowed by policies GetInteriorVehicleData request with "subscribe" parameter -- 2) and SDL received GetInteriorVehicledata response with "resultCode:<any_result>" and without "isSubscribed" parameter from HMI -- SDL must: -- 1) Transfer GetInteriorVehicleData response with provided from HMI current module data -- and with added "isSubscribed: <current_subscription_status>" to the related app --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') --[[ Local Variables ]] local modules = { "CLIMATE", "RADIO" } --[[ Local Functions ]] local function getDataForModule(pModuleType, isSubscriptionActive, pSubscribe, self) local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", { moduleType = pModuleType, subscribe = pSubscribe }) EXPECT_HMICALL("RC.GetInteriorVehicleData", { appID = self.applications["Test Application"], moduleType = pModuleType, subscribe = pSubscribe }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = commonRC.getModuleControlData(pModuleType), -- no isSubscribed parameter }) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", isSubscribed = isSubscriptionActive, -- return current value of subscription moduleData = commonRC.getModuleControlData(pModuleType) }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Title("Test") for _, mod in pairs(modules) do runner.Step("GetInteriorVehicleData " .. mod .. " NoSubscription_subscribe", getDataForModule, { mod, false, true }) runner.Step("GetInteriorVehicleData " .. mod .. " NoSubscription_unsubscribe", getDataForModule, { mod, false, false }) end for _, mod in pairs(modules) do runner.Step("Subscribe app to " .. mod, commonRC.subscribeToModule, { mod }) runner.Step("GetInteriorVehicleData " .. mod .. " ActiveSubscription_subscribe", getDataForModule, { mod, true, true }) runner.Step("GetInteriorVehicleData " .. mod .. " ActiveSubscription_unsubscribe", getDataForModule, { mod, true, false }) end runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--------------------------------------------------------------------------------------------------- -- Requirement summary: -- [SDL_RC] Current module status data GetInteriorVehicleData -- -- Description: -- In case: -- 1) RC app sends valid and allowed by policies GetInteriorVehicleData request with "subscribe" parameter -- 2) and SDL received GetInteriorVehicledata response with "resultCode:<any_result>" and without "isSubscribed" parameter from HMI -- SDL must: -- 1) Transfer GetInteriorVehicleData response with provided from HMI current module data -- and with added "isSubscribed: <current_subscription_status>" to the related app --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') --[[ Local Variables ]] local modules = { "CLIMATE", "RADIO" } --[[ Local Functions ]] local function getDataForModule(pModuleType, isSubscriptionActive, pSubscribe, self) local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", { moduleType = pModuleType, subscribe = pSubscribe }) local pSubscribeHMI = pSubscribe if (isSubscriptionActive and pSubscribe) or (not isSubscriptionActive and not pSubscribe) then pSubscribeHMI = nil end EXPECT_HMICALL("RC.GetInteriorVehicleData", { appID = self.applications["Test Application"], moduleType = pModuleType, subscribe = pSubscribeHMI }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = commonRC.getModuleControlData(pModuleType), -- no isSubscribed parameter }) end) EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", isSubscribed = isSubscriptionActive, -- return current value of subscription moduleData = commonRC.getModuleControlData(pModuleType) }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Title("Test") for _, mod in pairs(modules) do runner.Step("GetInteriorVehicleData " .. mod .. " NoSubscription_subscribe", getDataForModule, { mod, false, true }) runner.Step("GetInteriorVehicleData " .. mod .. " NoSubscription_unsubscribe", getDataForModule, { mod, false, false }) end for _, mod in pairs(modules) do runner.Step("Subscribe app to " .. mod, commonRC.subscribeToModule, { mod }) runner.Step("GetInteriorVehicleData " .. mod .. " ActiveSubscription_subscribe", getDataForModule, { mod, true, true }) runner.Step("GetInteriorVehicleData " .. mod .. " ActiveSubscription_unsubscribe", getDataForModule, { mod, true, false }) end runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
Fix according to new req-t regarding 2nd subscribe/unsubscribe
Fix according to new req-t regarding 2nd subscribe/unsubscribe
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
8ee8b53efcd7d2d54819b9a2a2a8b2247cce1f6d
src/util.lua
src/util.lua
local Pkg = {} local std = _G local ipairs = ipairs local pairs = pairs local type = type local setmetatable = setmetatable local getmetatable = getmetatable local tostring = tostring local print = print local table = table local io = io local string = string local math = math setfenv(1, Pkg) local empty = {} function printTable(obj, indent, maxDepth, seen) seen = seen or {} maxDepth = maxDepth or 10 if seen[obj] then io.write("<<cycle detected>>") return end if maxDepth == 0 then io.write("<<maxDepth exceeded>>") return end seen[obj] = true local indent = indent or 0 local padding = string.rep(" ", indent) io.write("{\n") for k, v in pairs(obj) do io.write(padding, " ", tostring(k), ": ") if type(v) == "table" then printTable(v, indent + 1, maxDepth - 1, seen) io.write(",\n") else io.write(tostring(v), "\n") end end io.write(padding, "}") if indent == 0 then io.write("\n") end end function printList(obj) io.write("{ ") for k, v in ipairs(obj) do io.write(tostring(v), ", ") end io.write("}") end if ... == nil then end function indentString(indent, str) local sep = "\n" .. string.rep(" ", indent) local result = "" for line in string.gmatch(str, "[^\n]+") do result = result .. (#result > 0 and sep or "") .. line end return result end function shallowCopy(obj) if type(obj) ~= "table" then return obj end local meta = getmetatable(obj) local neue = {} for k, v in pairs(obj) do neue[k] = v end setmetatable(neue, meta) return neue end function walk(obj, fn, seen) if type(obj) ~= "table" then return end seen = seen or {} for k, v in pairs(obj) do fn(k, v, obj) if type(v) == "table" and not seen[v] then seen[v] = true walk(v, fn, seen) end end end ------------------------------------------------------------ -- ID helpers ------------------------------------------------------------ local id = 0 function generateId() id = id + 1 return id end ------------------------------------------------------------ -- JSON helpers ------------------------------------------------------------ local function isArray(t) local i = 0 for _ in pairs(t) do i = i + 1 if t[i] == nil then return false end end return true end function toJSON(obj, seen) seen = seen or {} local objType = type(obj) if objType == "table" and obj.toJSON then return obj:toJSON(seen) elseif objType == "table" and isArray(obj) then seen[obj] = true local temp = {} for ix, child in ipairs(obj) do if not seen[child] then temp[#temp + 1] = toJSON(child, shallowCopy(seen)) end end return string.format("[%s]", table.concat(temp, ", ")) elseif objType == "table" then seen[obj] = true local temp = {} for key, value in pairs(obj) do if not seen[value] then temp[#temp + 1] = string.format("\"%s\": %s", key, toJSON(value, shallowCopy(seen))) end end return string.format("{%s}", table.concat(temp, ", ")) elseif objType == "string" then return string.format("\"%s\"", obj:gsub("\"", "\\\""):gsub("\n", "\\n")) elseif objType == "number" then return tostring(obj) elseif objType == "boolean" then return tostring(obj) end return "uh oh" end ------------------------------------------------------------ -- String helpers ------------------------------------------------------------ function makeWhitespace(size, char) local whitespace = {} local char = char or " " for i = 0, size do whitespace[#whitespace + 1] = char end return table.concat(whitespace) end function split(str, delim) local final = {} local index = 1 local splitStart, splitEnd = string.find(str, delim, index) while splitStart do final[#final + 1] = string.sub(str, index, splitStart-1) index = splitEnd + 1 splitStart, splitEnd = string.find(str, delim, index) end final[#final + 1] = string.sub(str, index) return final end function dedent(str) local lines = split(str,'\n') local _, indent = lines[1]:find("^%s*") local final = {} for _, line in ipairs(lines) do final[#final + 1] = line:sub(indent + 1) final[#final + 1] = "\n" end return table.concat(final) end function indent(str, by) local lines = split(str,'\n') local whitespace = makeWhitespace(by) local final = {} for _, line in ipairs(lines) do final[#final + 1] = whitespace final[#final + 1] = line final[#final + 1] = "\n" end return table.concat(final) end ------------------------------------------------------------ -- Package ------------------------------------------------------------ return Pkg --[[ print("Testing Set (empty)") printTable(Set:new()) print("Testing Set (content)") local testSet = Set:new{"foo", "bar", "baz", "quux"} print(testSet) print("Testing Set (cardinality)") print(#testSet) local otherSet = Set:new{"arg", "foo", 6, "baz", true} print("Set union with", otherSet) print(testSet + otherSet) print("Set intersection with", otherSet) print(testSet * otherSet) print("mutating union") local unionedSet = testSet:clone():union(otherSet, true) print(unionedSet) print("mutating intersect") local intersectedSet = testSet:clone():intersection(otherSet, true) print(intersectedSet) print("add 27 to ", testSet) testSet:add(27) print(testSet, #testSet) print("add 27 again") testSet:add(27) print(testSet, #testSet) print("remove foo") testSet:remove("foo") print(testSet, #testSet) print("remove foo again") testSet:remove("foo") print(testSet, #testSet) ]]--
local Pkg = {} local std = _G local ipairs = ipairs local pairs = pairs local type = type local setmetatable = setmetatable local getmetatable = getmetatable local tostring = tostring local print = print local table = table local io = io local string = string local math = math setfenv(1, Pkg) local empty = {} function printTable(obj, indent, maxDepth, seen) seen = seen or {} maxDepth = maxDepth or 10 if seen[obj] then io.write("<<cycle detected>>") return end if maxDepth == 0 then io.write("<<maxDepth exceeded>>") return end seen[obj] = true local indent = indent or 0 local padding = string.rep(" ", indent) io.write("{\n") for k, v in pairs(obj) do io.write(padding, " ", tostring(k), ": ") if type(v) == "table" then printTable(v, indent + 1, maxDepth - 1, seen) io.write(",\n") else io.write(tostring(v), "\n") end end io.write(padding, "}") if indent == 0 then io.write("\n") end end function printList(obj) io.write("{ ") for k, v in ipairs(obj) do io.write(tostring(v), ", ") end io.write("}") end if ... == nil then end function shallowCopy(obj) if type(obj) ~= "table" then return obj end local meta = getmetatable(obj) local neue = {} for k, v in pairs(obj) do neue[k] = v end setmetatable(neue, meta) return neue end function walk(obj, fn, seen) if type(obj) ~= "table" then return end seen = seen or {} for k, v in pairs(obj) do fn(k, v, obj) if type(v) == "table" and not seen[v] then seen[v] = true walk(v, fn, seen) end end end ------------------------------------------------------------ -- ID helpers ------------------------------------------------------------ local id = 0 function generateId() id = id + 1 return id end ------------------------------------------------------------ -- JSON helpers ------------------------------------------------------------ local function isArray(t) local i = 0 for _ in pairs(t) do i = i + 1 if t[i] == nil then return false end end return true end function toJSON(obj, seen) seen = seen or {} local objType = type(obj) if objType == "table" and obj.toJSON then return obj:toJSON(seen) elseif objType == "table" and isArray(obj) then seen[obj] = true local temp = {} for ix, child in ipairs(obj) do if not seen[child] then temp[#temp + 1] = toJSON(child, shallowCopy(seen)) end end return string.format("[%s]", table.concat(temp, ", ")) elseif objType == "table" then seen[obj] = true local temp = {} for key, value in pairs(obj) do if not seen[value] then temp[#temp + 1] = string.format("\"%s\": %s", key, toJSON(value, shallowCopy(seen))) end end return string.format("{%s}", table.concat(temp, ", ")) elseif objType == "string" then return string.format("\"%s\"", obj:gsub("\"", "\\\""):gsub("\n", "\\n")) elseif objType == "number" then return tostring(obj) elseif objType == "boolean" then return tostring(obj) end return "uh oh" end ------------------------------------------------------------ -- String helpers ------------------------------------------------------------ function makeWhitespace(size, char) local whitespace = {} local char = char or " " for i = 0, size do whitespace[#whitespace + 1] = char end return table.concat(whitespace) end function split(str, delim) local final = {} local index = 1 local splitStart, splitEnd = string.find(str, delim, index) while splitStart do final[#final + 1] = string.sub(str, index, splitStart-1) index = splitEnd + 1 splitStart, splitEnd = string.find(str, delim, index) end final[#final + 1] = string.sub(str, index) return final end function dedent(str) local lines = split(str,'\n') local _, indent = lines[1]:find("^%s*") local final = {} for _, line in ipairs(lines) do final[#final + 1] = line:sub(indent + 1) final[#final + 1] = "\n" end return table.concat(final) end function indent(str, by) local lines = split(str,'\n') local whitespace = makeWhitespace(by) local final = {} for _, line in ipairs(lines) do final[#final + 1] = whitespace final[#final + 1] = line final[#final + 1] = "\n" end return table.concat(final) end function indentString(indent, str) local sep = "\n" .. string.rep(" ", indent) local result = "" for line in string.gmatch(str, "[^\n]+") do result = result .. (#result > 0 and sep or "") .. line end return result end function fixPad(str) local indent = 0 for ix=1,#str do if str[ix] ~= " " then indent = ix - 1 break end end local sep = "\n" local result = "" for line in string.gmatch(str, "[^\n]+") do result = result .. (#result > 0 and sep or "") .. string.sub(line, indent) end return result end -- Courtesy of <https://gist.github.com/Badgerati/3261142> -- Returns the Levenshtein distance between the two given strings function levenshtein(str1, str2) local len1 = string.len(str1) local len2 = string.len(str2) local matrix = {} local cost = 0 -- quick cut-offs to save time if (len1 == 0) then return len2 elseif (len2 == 0) then return len1 elseif (str1 == str2) then return 0 end -- initialise the base matrix values for i = 0, len1, 1 do matrix[i] = {} matrix[i][0] = i end for j = 0, len2, 1 do matrix[0][j] = j end -- actual Levenshtein algorithm for i = 1, len1, 1 do for j = 1, len2, 1 do if (str1:byte(i) == str2:byte(j)) then cost = 0 else cost = 1 end matrix[i][j] = math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1, matrix[i-1][j-1] + cost) end end -- return the last value - this is the Levenshtein distance return matrix[len1][len2] end ------------------------------------------------------------ -- Package ------------------------------------------------------------ return Pkg --[[ print("Testing Set (empty)") printTable(Set:new()) print("Testing Set (content)") local testSet = Set:new{"foo", "bar", "baz", "quux"} print(testSet) print("Testing Set (cardinality)") print(#testSet) local otherSet = Set:new{"arg", "foo", 6, "baz", true} print("Set union with", otherSet) print(testSet + otherSet) print("Set intersection with", otherSet) print(testSet * otherSet) print("mutating union") local unionedSet = testSet:clone():union(otherSet, true) print(unionedSet) print("mutating intersect") local intersectedSet = testSet:clone():intersection(otherSet, true) print(intersectedSet) print("add 27 to ", testSet) testSet:add(27) print(testSet, #testSet) print("add 27 again") testSet:add(27) print(testSet, #testSet) print("remove foo") testSet:remove("foo") print(testSet, #testSet) print("remove foo again") testSet:remove("foo") print(testSet, #testSet) ]]--
Add fixPad and levenstein to util
Add fixPad and levenstein to util
Lua
apache-2.0
witheve/Eve,shamrin/Eve,witheve/Eve,witheve/Eve,nmsmith/Eve,shamrin/Eve,witheve/lueve,shamrin/Eve,nmsmith/Eve,nmsmith/Eve,witheve/lueve
dbbe9bf5a67ddd17e3aa85e2384d4b4ea75120b3
commands/update.lua
commands/update.lua
local log = require('log') local updater = require('auto-updater') local uv = require('uv') local pathJoin = require('luvi').path.join local exec = require('exec') local prompt = require('prompt')(require('pretty-print')) local miniz = require('miniz') local binDir = pathJoin(uv.exepath(), "..") local function updateLit() return updater.check(require('../package'), uv.exepath()) end local function updateLuvit() local luvitPath = pathJoin(binDir, "luvit") if require('ffi').os == "Windows" then luvitPath = luvitPath .. ".exe" end if uv.fs_stat(luvitPath) then local bundle = require('luvi').makeBundle({"/usr/local/bin/luvit"}) local fs = { readFile = bundle.readfile, stat = bundle.stat, } return updater.check(require('pkg').query(fs, "."), luvitPath) else return updater.check({ name = "luvit/luvit" }, luvitPath) end end local function updateLuvi() local target = pathJoin(binDir, "luvi") if require('ffi').os == "Windows" then target = target .. ".exe" end local new, old local toupdate = require('luvi').version if uv.fs_stat(target) then local stdout = exec(target, "-v") local version = stdout:match("luvi (v[^ \n]+)") if version and version == toupdate then log("luvi is up to date", version, "highlight") return end log("found system luvi", version) local res = prompt("Are you sure you wish to update " .. target .. " to luvi " .. toupdate .. "?", "Y/n") if not res:match("[yY]") then log("canceled update", version, "err") return end log("updating luvi", toupdate) new = target .. ".new" old = target .. ".old" else log("installing luvi binary", target, "highlight") old = nil new = target end local fd = assert(uv.fs_open(new, "w", 511)) -- 0777 local source = uv.exepath() local reader = miniz.new_reader(source) local binSize if reader then -- If contains a zip, find where the zip starts binSize = reader:get_offset() else -- Otherwise just read the file size binSize = uv.fs_stat(source).size end local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600 assert(uv.fs_sendfile(fd, fd2, 0, binSize)) uv.fs_close(fd2) uv.fs_close(fd) if old then log("replacing luvi binary", target, "highlight") uv.fs_rename(target, old) uv.fs_rename(new, target) uv.fs_unlink(old) log("luvi update complete", toupdate, "success") else log("luvi install complete", toupdate, "success") end end local commands = { luvi = updateLuvi, luvit = updateLuvit, lit = updateLit, all = function () updateLit() updateLuvit() updateLuvi() end } local cmd = commands[args[2] or "all"] if not cmd then error("Unknown update command: " .. args[2]) end cmd()
local log = require('log') local updater = require('auto-updater') local uv = require('uv') local pathJoin = require('luvi').path.join local exec = require('exec') local prompt = require('prompt')(require('pretty-print')) local miniz = require('miniz') local binDir = pathJoin(uv.exepath(), "..") local function updateLit() return updater.check(require('../package'), uv.exepath()) end local function updateLuvit() local luvitPath = pathJoin(binDir, "luvit") if require('ffi').os == "Windows" then luvitPath = luvitPath .. ".exe" end if uv.fs_stat(luvitPath) then local bundle = require('luvi').makeBundle({luvitPath}) local fs = { readFile = bundle.readfile, stat = bundle.stat, } return updater.check(require('pkg').query(fs, "."), luvitPath) else return updater.check({ name = "luvit/luvit" }, luvitPath) end end local function updateLuvi() local target = pathJoin(binDir, "luvi") if require('ffi').os == "Windows" then target = target .. ".exe" end local new, old local toupdate = require('luvi').version if uv.fs_stat(target) then local stdout = exec(target, "-v") local version = stdout:match("luvi (v[^ \n]+)") if version and version == toupdate then log("luvi is up to date", version, "highlight") return end if version then log("found system luvi", version) local res = prompt("Are you sure you wish to update " .. target .. " to luvi " .. toupdate .. "?", "Y/n") if not res:match("[yY]") then log("canceled update", version, "err") return end end log("updating luvi", toupdate) new = target .. ".new" old = target .. ".old" else log("installing luvi binary", target, "highlight") old = nil new = target end local fd = assert(uv.fs_open(new, "w", 511)) -- 0777 local source = uv.exepath() local reader = miniz.new_reader(source) local binSize if reader then -- If contains a zip, find where the zip starts binSize = reader:get_offset() else -- Otherwise just read the file size binSize = uv.fs_stat(source).size end local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600 assert(uv.fs_sendfile(fd, fd2, 0, binSize)) uv.fs_close(fd2) uv.fs_close(fd) if old then log("replacing luvi binary", target, "highlight") uv.fs_rename(target, old) uv.fs_rename(new, target) uv.fs_unlink(old) log("luvi update complete", toupdate, "success") else log("luvi install complete", toupdate, "success") end end local commands = { luvi = updateLuvi, luvit = updateLuvit, lit = updateLit, all = function () updateLit() updateLuvit() updateLuvi() end } local cmd = commands[args[2] or "all"] if not cmd then error("Unknown update command: " .. args[2]) end cmd()
Fix rest of update for windows
Fix rest of update for windows
Lua
apache-2.0
luvit/lit,squeek502/lit,kidaa/lit,1yvT0s/lit,DBarney/lit,lduboeuf/lit,kaustavha/lit,zhaozg/lit,james2doyle/lit
56f1edb675c55a4b4274dd4ca9fe2c815ebc9585
test_scripts/Polices/Policy_Table_Update/023_ATF_P_TC_PoliciesManager_changes_status_to_UP_TO_DATE.lua
test_scripts/Polices/Policy_Table_Update/023_ATF_P_TC_PoliciesManager_changes_status_to_UP_TO_DATE.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UP_TO_DATE” -- [HMI API] OnStatusUpdate -- [HMI API] OnReceivedPolicyUpdate notification -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) -- app->SDL: SystemRequest(requestType=PROPRIETARY) -- SDL->HMI: SystemRequest(requestType=PROPRIETARY, fileName, appID) -- HMI->SDL: SystemRequest(SUCCESS) -- 2. Performed steps -- HMI->SDL: OnReceivedPolicyUpdate(policy_file) according to data dictionary -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UP_TO_DATE) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_UP_TO_DATE() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {}):Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate",{}):Times(0) commonTestCases:DelayedExp(60*1000) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UP_TO_DATE” -- [HMI API] OnStatusUpdate -- [HMI API] OnReceivedPolicyUpdate notification -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) -- app->SDL: SystemRequest(requestType=PROPRIETARY) -- SDL->HMI: SystemRequest(requestType=PROPRIETARY, fileName, appID) -- HMI->SDL: SystemRequest(SUCCESS) -- 2. Performed steps -- HMI->SDL: OnReceivedPolicyUpdate(policy_file) according to data dictionary -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UP_TO_DATE) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_UP_TO_DATE() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate"):Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
Fix issues in script
Fix issues in script
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
3e24780cfb5393356a2545efadffee1b269341c2
test_scripts/Polices/Policy_Table_Update/019_ATF_P_TC_Sending_PTS_to_app_OnSystemRequest_appID_default.lua
test_scripts/Polices/Policy_Table_Update/019_ATF_P_TC_Sending_PTS_to_app_OnSystemRequest_appID_default.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Sending PTS to mobile application on getting OnSystemRequest with appID "default" -- [HMI API] SystemRequest request/response -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to any connected mobile application. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- device an app with app_ID1 is running is consented -- application with <app ID> is running on SDL -- device an app with app_ID2 is running is consented -- application with <app ID2> is running on SDL -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- 2. Performed steps -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- -- Expected result: -- -- SDL-><app1\app2>: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON") --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local mobileSession = require("mobile_session") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json") --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:StartNewSession() self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end function Test:Register2App() local correlationId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") self.mobileSession2:ExpectResponse(correlationId, { success = true }) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Sending_PTS_to_mobile_application() local endpoints = {} endpoints[1] ={} endpoints[1].url = "http://policies.telematics.ford.com/api/policies" local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints }} ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", url = endpoints[1].url}) -- no appID is send, so notification can came to any apps end) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON", url = endpoints[1].url }):Times(Between(0,1)) self.mobileSession2:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON", url = endpoints[1].url }):Times(Between(0,1)) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Sending PTS to mobile application on getting OnSystemRequest with appID "default" -- [HMI API] SystemRequest request/response -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to any connected mobile application. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- device an app with app_ID1 is running is consented -- application with <app ID> is running on SDL -- device an app with app_ID2 is running is consented -- application with <app ID2> is running on SDL -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- 2. Performed steps -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default") -- -- Expected result: -- -- SDL-><app1\app2>: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON") --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local mobileSession = require("mobile_session") --[[ Local Variables ]] local r_actual = { } --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json") --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:StartNewSession() self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end function Test:Register2App() local correlationId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_, d) self.applications[d.params.application.appName] = d.params.application.appID end) self.mobileSession2:ExpectResponse(correlationId, { success = true }) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Sending_PTS_to_mobile_application() local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"--, -- appID = self.applications["Test Application2"] }) -- no appID is send, so notification can came to any apps end) self.mobileSession:ExpectNotification("OnSystemRequest") :Do(function(_,d) if d.payload.requestType == "PROPRIETARY" then table.insert(r_actual, 1) end end) :Times(AnyNumber()) :Pin() self.mobileSession2:ExpectNotification("OnSystemRequest") :Do(function(_,d) if d.payload.requestType == "PROPRIETARY" then table.insert(r_actual, 2) end end) :Times(AnyNumber()) :Pin() end for i = 1, 3 do Test["Waiting " .. i .. " sec"] = function() os.execute("sleep 1") end end function Test:ValidateResult() if #r_actual == 0 then self:FailTestCase("Expected OnSystemRequest notification was NOT forwarded through any of registerred applications") elseif #r_actual > 1 then self:FailTestCase("Expected OnSystemRequest notification was forwarded through more than once") else print("Expected OnSystemRequest notification was forwarded through appplication '" .. r_actual[1] .. "'") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
e483a53902a9621f95681bf0db4582be83d9e916
OS/DiskOS/terminal.lua
OS/DiskOS/terminal.lua
--The terminal !-- local PATH = "C://Programs/;" local curdrive, curdir, curpath = "C", "/", "C:///" local editor = require("C://Editors") local function nextPath(p) if p:sub(-1)~=";" then p=p..";" end return p:gmatch("(.-);") end printCursor(1,1,1) color(9) print("LIKO-12 V0.6.0 DEV") flip() sleep(0.5) color(8) print("DiskOS DEV B1") flip() sleep(0.5) color(7) print("http://github.com/ramilego4game/liko12") --color(7) print("\nA PICO-8 INSPIRED OS WITH EXTRA ABILITIES") flip() sleep(0.25) color(10) print("\nTYPE HELP FOR HELP") flip() sleep(0.25) local history = {} local btimer, btime, blink = 0, 0.5, true local fw, fh = fontSize() local function checkCursor() local cx, cy = printCursor() local tw, th = termSize() if cx > tw+1 then cx = tw+1 end if cx < 1 then cx = 1 end if cy > th+1 then cy = th+1 end if cy < 1 then cy = 1 end printCursor(cx,cy) cy = cy-1 rect(cx*(fw+1)-2,cy*(fh+3)+2,fw+1,fh,false,blink and 5 or 1) end local function split(str) local t = {} for val in str:gmatch("%S+") do table.insert(t, val) end return unpack(t) end local term = {} function term.setdrive(d) if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end curdrive = d curpath = curdrive.."://"..curdir end function term.setdirectory(d) if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end if not fs.exists(curdrive.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(curdrive.."://"..d) then return error("It must be a directory, not a file") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end d = d:gsub("//","/") curdir = d curpath = curdrive.."://"..d end function term.setpath(p) if type(p) ~= "string" then return error("Path must be a string, provided: "..type(p)) end local dv, d = p:match("(.+)://(.+)") if (not dv) or (not d) then return error("Invalied path: "..p) end if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end if not fs.exists(dv.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(dv.."://"..d) then return error("It must be a directory, not a file") end d = d:gsub("//","/") curdrive, curdir, curpath = dv, d, dv.."://"..d end function term.getpath() return curpath end function term.getdrive() return curdrive end function term.getdirectory() return curdir end function term.setPATH(p) PATH = p end function term.getPATH() return PATH end function term.parsePath(path) if path:sub(1,3) == "../" then local fld = {} --A list of folders in the path for p in string.gmatch(curdir,"(.-)/") do table.insert(fld,p) end if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end table.remove(fld, #fld) --Remove the last directory return curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1), fs.exists(curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1)) elseif path:sub(1,2) == "./" then return curpath..sub(3,-1), fs.exists(curpath..sub(3,-1)) elseif path == ".." then local fld = {} --A list of folders in the path for p in string.gmatch(curdir,"(.-)/") do table.insert(fld,p) end if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end table.remove(fld, #fld) --Remove the last directory return curdrive..":///"..table.concat(fld,"/"), fs.exists(curdrive..":///"..table.concat(fld,"/")) elseif path == "." then return curpath, fs.exists(curpath) end local d, p = path:match("(.+)://(.+)") if d and p then return path, fs.exists(path) end local d = path:match("(.+):") --ex: D: if d then return d..":///", fs.exists(d..":///") end local d = path:match("/(.+)") if d then return curdrive.."://"..path, fs.exists(curdrive.."://"..path) end return curpath..path, fs.exists(curpath..path) end function term.execute(command,...) if not command then print("") return false, "No command" end if fs.exists(curpath..command..".lua") then local chunk, err = fs.load(curpath..command..".lua") if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end color(8) return true end for path in nextPath(PATH) do if fs.exists(path) then local files = fs.directoryItems(path) for _,file in ipairs(files) do if file == command..".lua" then local chunk, err = fs.load(path..file) if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end color(8) return true end end end end color(10) print("\nFile not found") color(8) return false, "File not found" end function term.loop() --Enter the while loop of the terminal cursor("none") clearEStack() color(8) checkCursor() print(term.getpath().."> ",false) local buffer = "" while true do checkCursor() local event, a, b, c, d, e, f = pullEvent() if event == "textinput" then buffer = buffer..a print(a,false) elseif event == "keypressed" then if a == "return" then table.insert(history, buffer) blink = false; checkCursor() term.execute(split(buffer)) buffer = "" color(8) checkCursor() print(term.getpath().."> ",false) blink = true cursor("none") elseif a == "backspace" then blink = false; checkCursor() if buffer:len() > 0 then buffer = buffer:sub(0,-2) printBackspace() end blink = true; checkCursor() elseif a == "delete" then blink = false; checkCursor() for i=1,buffer:len() do printBackspace() end buffer = "" blink = true; checkCursor() elseif a == "escape" then local screenbk = screenshot() local oldx, oldy, oldbk = printCursor() editor:loop() cursor("none") printCursor(oldx,oldy,oldbk) screenbk:image():draw(1,1) color(8) end elseif event == "touchpressed" then textinput(true) elseif event == "update" then btimer = btimer + a if btimer > btime then btimer = btimer-btime blink = not blink end end end end return term
--The terminal !-- local PATH = "C://Programs/;" local curdrive, curdir, curpath = "C", "/", "C:///" local editor = require("C://Editors") local function nextPath(p) if p:sub(-1)~=";" then p=p..";" end return p:gmatch("(.-);") end printCursor(1,1,1) color(9) print("LIKO-12 V0.6.0 DEV") flip() sleep(0.5) color(8) print("DiskOS DEV B1") flip() sleep(0.5) color(7) print("http://github.com/ramilego4game/liko12") --color(7) print("\nA PICO-8 INSPIRED OS WITH EXTRA ABILITIES") flip() sleep(0.25) color(10) print("\nTYPE HELP FOR HELP") flip() sleep(0.25) local history = {} local btimer, btime, blink = 0, 0.5, true local fw, fh = fontSize() local function checkCursor() local cx, cy = printCursor() local tw, th = termSize() if cx > tw+1 then cx = tw+1 end if cx < 1 then cx = 1 end if cy > th+1 then cy = th+1 end if cy < 1 then cy = 1 end printCursor(cx,cy,1) cy = cy-1 rect(cx*(fw+1)-2,blink and cy*(fh+3)+2 or cy*(fh+3)+1,fw+1,blink and fh or fh+2,false,blink and 5 or 1) --The blink end local function split(str) local t = {} for val in str:gmatch("%S+") do table.insert(t, val) end return unpack(t) end local term = {} function term.setdrive(d) if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end curdrive = d curpath = curdrive.."://"..curdir end function term.setdirectory(d) if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end if not fs.exists(curdrive.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(curdrive.."://"..d) then return error("It must be a directory, not a file") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end d = d:gsub("//","/") curdir = d curpath = curdrive.."://"..d end function term.setpath(p) if type(p) ~= "string" then return error("Path must be a string, provided: "..type(p)) end local dv, d = p:match("(.+)://(.+)") if (not dv) or (not d) then return error("Invalied path: "..p) end if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end if not fs.exists(dv.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(dv.."://"..d) then return error("It must be a directory, not a file") end d = d:gsub("//","/") curdrive, curdir, curpath = dv, d, dv.."://"..d end function term.getpath() return curpath end function term.getdrive() return curdrive end function term.getdirectory() return curdir end function term.setPATH(p) PATH = p end function term.getPATH() return PATH end function term.parsePath(path) if path:sub(1,3) == "../" then local fld = {} --A list of folders in the path for p in string.gmatch(curdir,"(.-)/") do table.insert(fld,p) end if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end table.remove(fld, #fld) --Remove the last directory return curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1), fs.exists(curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1)) elseif path:sub(1,2) == "./" then return curpath..sub(3,-1), fs.exists(curpath..sub(3,-1)) elseif path == ".." then local fld = {} --A list of folders in the path for p in string.gmatch(curdir,"(.-)/") do table.insert(fld,p) end if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end table.remove(fld, #fld) --Remove the last directory return curdrive..":///"..table.concat(fld,"/"), fs.exists(curdrive..":///"..table.concat(fld,"/")) elseif path == "." then return curpath, fs.exists(curpath) end local d, p = path:match("(.+)://(.+)") if d and p then return path, fs.exists(path) end local d = path:match("(.+):") --ex: D: if d then return d..":///", fs.exists(d..":///") end local d = path:match("/(.+)") if d then return curdrive.."://"..path, fs.exists(curdrive.."://"..path) end return curpath..path, fs.exists(curpath..path) end function term.execute(command,...) if not command then print("") return false, "No command" end if fs.exists(curpath..command..".lua") then local chunk, err = fs.load(curpath..command..".lua") if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end color(8) return true end for path in nextPath(PATH) do if fs.exists(path) then local files = fs.directoryItems(path) for _,file in ipairs(files) do if file == command..".lua" then local chunk, err = fs.load(path..file) if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end color(8) return true end end end end color(10) print("\nFile not found") color(8) return false, "File not found" end function term.loop() --Enter the while loop of the terminal cursor("none") clearEStack() color(8) checkCursor() print(term.getpath().."> ",false) local buffer = "" while true do checkCursor() local event, a, b, c, d, e, f = pullEvent() if event == "textinput" then buffer = buffer..a print(a,false) elseif event == "keypressed" then if a == "return" then table.insert(history, buffer) blink = false; checkCursor() term.execute(split(buffer)) buffer = "" color(8) checkCursor() print(term.getpath().."> ",false) blink = true cursor("none") elseif a == "backspace" then blink = false; checkCursor() if buffer:len() > 0 then buffer = buffer:sub(0,-2) printBackspace() end blink = true; checkCursor() elseif a == "delete" then blink = false; checkCursor() for i=1,buffer:len() do printBackspace() end buffer = "" blink = true; checkCursor() elseif a == "escape" then local screenbk = screenshot() local oldx, oldy, oldbk = printCursor() editor:loop() cursor("none") printCursor(oldx,oldy,oldbk) screenbk:image():draw(1,1) color(8) end elseif event == "touchpressed" then textinput(true) elseif event == "update" then btimer = btimer + a if btimer > btime then btimer = btimer-btime blink = not blink end end end end return term
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
1422c089c3c8a81cca0ab93684a22fd0445331b6
core/ext/find.lua
core/ext/find.lua
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then if next then buffer:goto_pos(buffer.current_pos + increment) buffer:search_anchor() result = buffer:search_next(flags, text) else buffer:goto_pos(buffer.anchor - increment) buffer:search_anchor() result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain both Lua -- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %() -- sequences for embedding Lua code for any search. function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() rtext = rtext:gsub('%%%%', '\\037') -- escape '%%' if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('%%'..i, v) end end local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())', function(code) local ret, val = pcall( loadstring('return '..code) ) if not ret then os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"') error() end return val end ) if ret then rtext = rtext:gsub('\\037', '%%') -- unescape '%' buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement else -- Since find is called after replace returns, have it 'find' the current -- text again, rather than the next occurance so the user can fix the error. buffer:goto_pos(buffer.current_pos) end end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. local find = textadept.find --- -- [Local table] Text escape sequences with their associated characters. -- @class table -- @name escapes local escapes = { ['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n', ['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\' } --- -- Finds and selects text in the current buffer. -- This is used by the find dialog. It is recommended to use the buffer:find() -- function for scripting. -- @param text The text to find. -- @param flags Search flags. This is a number mask of 3 flags: match case (2), -- whole word (4), and Lua pattern (8) joined with binary AND. -- @param next Flag indicating whether or not the search direction is forward. -- @param nowrap Flag indicating whether or not the search won't wrap. -- @param wrapped Utility flag indicating whether or not the search has wrapped -- for displaying useful statusbar information. This flag is used and set -- internally, and should not be set otherwise. function find.find(text, flags, next, nowrap, wrapped) local buffer = buffer local increment, result text = text:gsub('\\[abfnrtv\\]', escapes) find.captures = nil if buffer.current_pos == buffer.anchor then increment = 0 elseif not wrapped then increment = next and 1 or -1 end if flags < 8 then buffer:goto_pos( buffer[next and 'current_pos' or 'anchor'] + increment ) buffer:search_anchor() if next then result = buffer:search_next(flags, text) else result = buffer:search_prev(flags, text) end if result then buffer:scroll_caret() end else -- lua pattern search (forward search only) local buffer_text = buffer:get_text(buffer.length) local results = { buffer_text:find(text, buffer.anchor + increment) } if #results > 0 then result = results[1] find.captures = { unpack(results, 3) } buffer:set_sel(results[2], result - 1) else result = -1 end end if result == -1 and not nowrap and not wrapped then -- wrap the search local anchor, pos = buffer.anchor, buffer.current_pos if next or flags >= 8 then buffer:goto_pos(0) else buffer:goto_pos(buffer.length) end textadept.statusbar_text = 'Search wrapped' result = find.find(text, flags, next, true, true) if not result then textadept.statusbar_text = 'No results found' buffer:goto_pos(anchor) end return result elseif result ~= -1 and not wrapped then textadept.statusbar_text = '' end return result ~= -1 end --- -- Replaces found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- textadept.find.find is called first, to select any found text. The selected -- text is then replaced by the specified replacement text. -- @param rtext The text to replace found text with. It can contain both Lua -- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %() -- sequences for embedding Lua code for any search. function find.replace(rtext) if #buffer:get_sel_text() == 0 then return end local buffer = buffer buffer:target_from_selection() rtext = rtext:gsub('%%%%', '\\037') -- escape '%%' if find.captures then for i, v in ipairs(find.captures) do rtext = rtext:gsub('%%'..i, v) end end local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())', function(code) local ret, val = pcall( loadstring('return '..code) ) if not ret then os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"') error() end return val end ) if ret then rtext = rtext:gsub('\\037', '%%') -- unescape '%' buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) ) buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement else -- Since find is called after replace returns, have it 'find' the current -- text again, rather than the next occurance so the user can fix the error. buffer:goto_pos(buffer.current_pos) end end --- -- Replaces all found text. -- This function is used by the find dialog. It is not recommended to call it -- via scripts. -- @param ftext The text to find. -- @param rtext The text to replace found text with. -- @param flags The number mask identical to the one in 'find'. -- @see find.find function find.replace_all(ftext, rtext, flags) buffer:goto_pos(0) local count = 0 while( find.find(ftext, flags, true, true) ) do find.replace(rtext) count = count + 1 end textadept.statusbar_text = tostring(count)..' replacement(s) made' end
Fixed 'find previous' bug; core/ext/find.lua Changeset 15 introduced an 'increment' variable that is normally +/-1 for find next and find prev respectively. However instead of adding the increment for find prev, it subtracts it, effectively adding 1 which is not right.
Fixed 'find previous' bug; core/ext/find.lua Changeset 15 introduced an 'increment' variable that is normally +/-1 for find next and find prev respectively. However instead of adding the increment for find prev, it subtracts it, effectively adding 1 which is not right.
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
2b4e4c3639b995662bc667f52ec249dce7df9fce
base/explosion.lua
base/explosion.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local M = {} local function HitVictims(Posi,Hitpoints,CenterPos) if world:isCharacterOnField(Posi) then local explosionVictim = world:getCharacterOnField(Posi); if (explosionVictim:getType() == 2) then --dont touch npcs return; end local posX; local posY; if (Posi == CenterPos) then -- code path not reached posX = explosionVictim.pos.x+math.random(-9,9) posY = explosionVictim.pos.y+math.random(-9,9) else local Distance = explosionVictim:distanceMetricToPosition(CenterPos); local Diffx = CenterPos.x - explosionVictim.pos.x; local Diffy = CenterPos.y - explosionVictim.pos.y; if (Distance == 1) then Diffx = 6*Diffx; Diffy = 6*Diffy; elseif (Distance == 2) then Diffx = 2*Diffx; Diffy = 2*Diffy; end posX = explosionVictim.pos.x-Diffx posY = explosionVictim.pos.y-Diffy end local listOfStuff = world:LoS(explosionVictim.pos, position(posX,posY,explosionVictim.pos.z)) if listOfStuff ~= nil then local minDistance = explosionVictim:distanceMetricToPosition(position(posX,posY,explosionVictim.pos.z)); for i, listEntry in pairs(listOfStuff) do local itemPos = listEntry.OBJECT.pos local field = world:getField(itemPos) local tempX = posX; local tempY = posY; -- something not passable is in the way, recalculate position if not field:isPassable() then local phi = common.GetPhi(explosionVictim.pos, itemPos); if (phi < math.pi / 8) then tempX = itemPos.x - 1 elseif (phi < 3 * math.pi / 8) then tempX = itemPos.x - 1 tempY = itemPos.y - 1 elseif (phi < 5 * math.pi / 8) then tempY = itemPos.y - 1 elseif (phi < 7 * math.pi / 8) then tempX = itemPos.x + 1 tempY = itemPos.y - 1 elseif (phi < 9 * math.pi / 8) then tempX = itemPos.x + 1 elseif (phi < 11 * math.pi / 8) then tempX = itemPos.x + 1 tempY = itemPos.y + 1 elseif (phi < 13 * math.pi / 8) then tempY = itemPos.y + 1 elseif (phi < 15 * math.pi / 8) then tempX = itemPos.x - 1 tempY = itemPos.y + 1 else tempX = itemPos.x - 1 end; local tempDistance = explosionVictim:distanceMetricToPosition(position(tempX,tempY,explosionVictim.pos.z)); if ( tempDistance < minDistance) then minDistance = tempDistance; posX = tempX; posY = tempY; end end end end explosionVictim:warp(position(posX,posY,explosionVictim.pos.z)); common.InformNLS(explosionVictim, "Getroffen von der Detonation wirst du davon geschleudert.", "Hit by the detonation, you get thrown away."); explosionVictim:increaseAttrib("hitpoints",-Hitpoints); end; end; local function CreateExplosionCircle(HitPos,gfxid,Damage,CenterPos,setFlames) world:gfx(gfxid,HitPos); HitVictims(HitPos,Damage,CenterPos); if setFlames then if (math.random(1,5)==1) then world:createItemFromId(359,1,HitPos,true,math.random(200,600),nil); end end end; --[[ CreateExplosion Provide an explosion that also throws characters away, in a radios of 3 fields @param integer - Center of the explosion ]] function M.CreateExplosion(CenterPos) local function CreateOuterCircle(HitPos) CreateExplosionCircle(HitPos, 1,250,CenterPos,false); return true; end local function CreateMiddleCircle(HitPos) CreateExplosionCircle(HitPos,9,750,CenterPos,true); return true; end local function CreateInnerCircle(HitPos) CreateExplosionCircle(HitPos, 44,1000,CenterPos,true); return true; end common.CreateCircle(CenterPos, 3, CreateOuterCircle); common.CreateCircle(CenterPos, 2, CreateMiddleCircle); common.CreateCircle(CenterPos, 1, CreateInnerCircle); world:gfx(36,CenterPos); world:makeSound(5,CenterPos); end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local M = {} local function HitVictims(Posi,Hitpoints,CenterPos) if world:isCharacterOnField(Posi) then local explosionVictim = world:getCharacterOnField(Posi) if (explosionVictim:getType() == 2) then --dont touch npcs return end local Distance = explosionVictim:distanceMetricToPosition(CenterPos) local Diffx = CenterPos.x - explosionVictim.pos.x local Diffy = CenterPos.y - explosionVictim.pos.y if (Distance == 1) then Diffx = 6*Diffx Diffy = 6*Diffy elseif (Distance == 2) then Diffx = 2*Diffx Diffy = 2*Diffy end local posX = explosionVictim.pos.x - Diffx local posY = explosionVictim.pos.y - Diffy local listOfStuff = world:LoS(explosionVictim.pos, position(posX,posY,explosionVictim.pos.z)) if listOfStuff ~= nil then local minDistance = explosionVictim:distanceMetricToPosition(position(posX,posY,explosionVictim.pos.z)) for _, listEntry in pairs(listOfStuff) do local itemPos = listEntry.OBJECT.pos local field = world:getField(itemPos) local tempX = posX local tempY = posY -- something not passable is in the way, recalculate position if not field:isPassable() then local phi = common.GetPhi(explosionVictim.pos, itemPos) if (phi < math.pi / 8) then tempX = itemPos.x - 1 elseif (phi < 3 * math.pi / 8) then tempX = itemPos.x - 1 tempY = itemPos.y - 1 elseif (phi < 5 * math.pi / 8) then tempY = itemPos.y - 1 elseif (phi < 7 * math.pi / 8) then tempX = itemPos.x + 1 tempY = itemPos.y - 1 elseif (phi < 9 * math.pi / 8) then tempX = itemPos.x + 1 elseif (phi < 11 * math.pi / 8) then tempX = itemPos.x + 1 tempY = itemPos.y + 1 elseif (phi < 13 * math.pi / 8) then tempY = itemPos.y + 1 elseif (phi < 15 * math.pi / 8) then tempX = itemPos.x - 1 tempY = itemPos.y + 1 else tempX = itemPos.x - 1 end local tempDistance = explosionVictim:distanceMetricToPosition(position(tempX,tempY,explosionVictim.pos.z)) if tempDistance < minDistance then minDistance = tempDistance posX = tempX posY = tempY end end end end explosionVictim:warp(position(posX,posY,explosionVictim.pos.z)) common.InformNLS(explosionVictim, "Getroffen von der Detonation wirst du davon geschleudert.", "Hit by the detonation, you get thrown away.") explosionVictim:increaseAttrib("hitpoints",-Hitpoints) end end local function CreateExplosionCircle(HitPos,gfxid,Damage,CenterPos,setFlames) world:gfx(gfxid,HitPos) HitVictims(HitPos,Damage,CenterPos) if setFlames then if (math.random(1,5)==1) then local field = world:getField(HitPos) if field ~= nil and field:isPassable() then world:createItemFromId(359,1,HitPos,true,math.random(200,600),nil) end end end end --[[ CreateExplosion Provide an explosion that also throws characters away, in a radios of 3 fields @param integer - Center of the explosion ]] function M.CreateExplosion(CenterPos) local function CreateOuterCircle(HitPos) CreateExplosionCircle(HitPos, 1,250,CenterPos,false) return true end local function CreateMiddleCircle(HitPos) CreateExplosionCircle(HitPos,9,750,CenterPos,true) return true end local function CreateInnerCircle(HitPos) CreateExplosionCircle(HitPos, 44,1000,CenterPos,true) return true end common.CreateCircle(CenterPos, 3, CreateOuterCircle) common.CreateCircle(CenterPos, 2, CreateMiddleCircle) common.CreateCircle(CenterPos, 1, CreateInnerCircle) world:gfx(36,CenterPos) world:makeSound(5,CenterPos) end return M
fix #10775: do not create flames on impassable fields. While here also fix some style
fix #10775: do not create flames on impassable fields. While here also fix some style
Lua
agpl-3.0
vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
8c8d445cd99598caa7b497baec77946194cc490b
init.lua
init.lua
local init = {} local shell = require("shell") function init.getfiles() print("initializing files...") local repo for line in io.lines(os.getenv("PWD") .. "/init.files") do if repo == nil then repo = line print("repo " .. repo) else print("getting " .. line) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. "?" .. math.random() .. " " .. line) end end print("done") end function init.clone(repo) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/init.files?" .. math.random() .. " init.files") init.getfiles() end local args = shell.parse( ... ) if args[1] ~= nil then init.clone(args[1]) else init.getfiles() end return init
local init = {} local shell = require("shell") function init.getfiles(gotFilesList) print("initializing files...") local repo for line in io.lines(os.getenv("PWD") .. "/init.files") do if repo == nil then repo = line if not gotFilesList then -- restart, got file listing that may have changed init.clone(repo, true) return end print("repo " .. repo) else print("getting " .. line) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. "?" .. math.random() .. " " .. line) end end print("done") end function init.clone(repo, gotFilesList) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/init.files?" .. math.random() .. " init.files") init.getfiles(gotFilesList) end local args = shell.parse( ... ) if args[1] ~= nil then init.clone(args[1], false) else init.getfiles() end return init
fixes state init.files problem
fixes state init.files problem
Lua
apache-2.0
InfinitiesLoop/oclib
f5096bf55a684fd1dba9d68d1341521c9384aa00
modules/unicode.lua
modules/unicode.lua
local sql = require'lsqlite3' local util = require'util' -- utf-8 functions (C) Rici Lake -- http://luaparse.luaforge.net/libquery.lua.html local function X(str) return tonumber(str, 16) end local elevenBits = X"7FF" local sixteenBits = X"FFFF" local math = require 'math' local mod = math.mod local strchar = string.char local strbyte = string.byte local strfind = string.find local offset2 = X"C0" * 64 + X"80" local offset3 = X"E0" * 4096 + X"80" * (64 + 1) local offset4 = X"F0" * 262144 + X"80" * (4096 + 64 + 1) local function toUtf8(i) i = X(i) if i <= 127 then return strchar(i) elseif i <= elevenBits then return strchar(i / 64 + 192, mod(i, 64) + 128) elseif i <= sixteenBits then return strchar(i / 4096 + 224, mod(i / 64, 64) + 128, mod(i, 64) + 128) else return strchar(i / 262144 + 240, mod(i / 4096, 64) + 128, mod(i / 64, 64) + 128, mod(i, 64) + 128) end end local function fromUtf8(str) if strfind(str, "^[\1-\127%z]$") then return strbyte(str) elseif strfind(str, "^[\194-\223][\128-\191]$") then return strbyte(str, 1) * 64 + strbyte(str, 2) - offset2 elseif strfind(str, "^[\225-\236\238\239][\128-\191][\128-\191]$") or strfind(str, "^\224[\160-\191][\128-\191]$") or strfind(str, "^\237[\128-\159][\128-\191]$") then return strbyte(str, 1) * 4096 + strbyte(str, 2) * 64 + strbyte(str, 3) - offset3 elseif strfind(str, "^\240[\144-\191][\128-\191][\128-\191]$") or strfind(str, "^[\241\242\243][\128-\191][\128-\191][\128-\191]$") or strfind(str, "^\244[\128-\143][\128-\191][\128-\191]$") then return (strbyte(str, 1) * 262144 - offset4) + strbyte(str, 2) * 4096 + strbyte(str, 3) * 64 + strbyte(str, 4) end end local function handleSearch(self, source, destination, name) local db = sql.open("cache/unicode.sql") local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 50') selectStmt:bind_values('%'..name..'%') local out = {} for row in selectStmt:nrows() do table.insert(out, string.format('%s %s', toUtf8(row.cp), row.name)) end db:close() <<<<<<< HEAD if(#out) then self:Msg('privmsg', destination, source, table.concat(out, ', ')) ======= if #out > 0 then say(table.concat(out, ', ')) else say('No match. ಠ_ಠ') >>>>>>> 527be1c... unicode: gfind -> gmatch. Proper check for matches end end local function handleSearchShort(self, source, destination, name) local db = sql.open("cache/unicode.sql") local selectStmt = db:prepare('SELECT cp FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 500') selectStmt:bind_values('%'..name..'%') local out = {} for row in selectStmt:nrows() do table.insert(out, string.format('%s', toUtf8(row.cp))) end db:close() <<<<<<< HEAD if(#out) then self:Msg('privmsg', destination, source, table.concat(out, '')) ======= if #out > 0 then say(table.concat(out, '')) else say('No match. ಠ_ಠ') >>>>>>> 527be1c... unicode: gfind -> gmatch. Proper check for matches end end local function handleLookup(self, source, destination, str) local db = sql.open("cache/unicode.sql") local out = {} for uchar in string.gmatch(str, "([%z\1-\127\194-\244][\128-\191]*)") do uchar = fromUtf8(uchar) if uchar then local cp = string.format('%04x', uchar) local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(cp) LIKE LOWER(?)') selectStmt:bind_values(cp) for row in selectStmt:nrows() do table.insert(out, string.format('U+%s %s', (row.cp), row.name)) end end end db:close() if #out > 0 then say(table.concat(out, ', ')) else say('No match. ಠ_ಠ') end end local function genMojibake(self, source, destination, str) local factor = 0.65 local db = sql.open("cache/unicode.sql") local out = {} for uchar in util.utf8.chars(str) do local ucp = fromUtf8(uchar) if ucp and math.random() >= factor then local cp = string.format('%04x', ucp) local stmt = db:prepare('SELECT name FROM unicode WHERE LOWER(cp) LIKE LOWER(?)') stmt:bind_values(cp) local code = stmt:step() if code == sql.ROW then local name = stmt:get_value(0) name = string.format('%s with%%', name) local stmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) ORDER BY random() LIMIT 1') stmt:bind_values(name) local code = stmt:step() if code == sql.ROW then local cp = stmt:get_value(0) table.insert(out, string.format('%s', toUtf8(cp))) else table.insert(out, uchar) end else table.insert(out, uchar) end else table.insert(out, uchar) end end db:close() say(table.concat(out)) end return { PRIVMSG = { ['^%pu (.*)$'] = handleSearch, ['^%pus (.*)$'] = handleSearchShort, ['^%pw (.*)$'] = handleLookup, ['^%pmojibake (.*)$'] = genMojibake, } }
local sql = require'lsqlite3' local util = require'util' -- utf-8 functions (C) Rici Lake -- http://luaparse.luaforge.net/libquery.lua.html local function X(str) return tonumber(str, 16) end local elevenBits = X"7FF" local sixteenBits = X"FFFF" local math = require 'math' local mod = math.mod local strchar = string.char local strbyte = string.byte local strfind = string.find local offset2 = X"C0" * 64 + X"80" local offset3 = X"E0" * 4096 + X"80" * (64 + 1) local offset4 = X"F0" * 262144 + X"80" * (4096 + 64 + 1) local function toUtf8(i) i = X(i) if i <= 127 then return strchar(i) elseif i <= elevenBits then return strchar(i / 64 + 192, mod(i, 64) + 128) elseif i <= sixteenBits then return strchar(i / 4096 + 224, mod(i / 64, 64) + 128, mod(i, 64) + 128) else return strchar(i / 262144 + 240, mod(i / 4096, 64) + 128, mod(i / 64, 64) + 128, mod(i, 64) + 128) end end local function fromUtf8(str) if strfind(str, "^[\1-\127%z]$") then return strbyte(str) elseif strfind(str, "^[\194-\223][\128-\191]$") then return strbyte(str, 1) * 64 + strbyte(str, 2) - offset2 elseif strfind(str, "^[\225-\236\238\239][\128-\191][\128-\191]$") or strfind(str, "^\224[\160-\191][\128-\191]$") or strfind(str, "^\237[\128-\159][\128-\191]$") then return strbyte(str, 1) * 4096 + strbyte(str, 2) * 64 + strbyte(str, 3) - offset3 elseif strfind(str, "^\240[\144-\191][\128-\191][\128-\191]$") or strfind(str, "^[\241\242\243][\128-\191][\128-\191][\128-\191]$") or strfind(str, "^\244[\128-\143][\128-\191][\128-\191]$") then return (strbyte(str, 1) * 262144 - offset4) + strbyte(str, 2) * 4096 + strbyte(str, 3) * 64 + strbyte(str, 4) end end local function handleSearch(self, source, destination, name) local db = sql.open("cache/unicode.sql") local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 50') selectStmt:bind_values('%'..name..'%') local out = {} for row in selectStmt:nrows() do table.insert(out, string.format('%s %s', toUtf8(row.cp), row.name)) end db:close() if #out > 0 then say(table.concat(out, ', ')) else say('No match. ಠ_ಠ') end end local function handleSearchShort(self, source, destination, name) local db = sql.open("cache/unicode.sql") local selectStmt = db:prepare('SELECT cp FROM unicode WHERE LOWER(name) LIKE LOWER(?) LIMIT 500') selectStmt:bind_values('%'..name..'%') local out = {} for row in selectStmt:nrows() do table.insert(out, string.format('%s', toUtf8(row.cp))) end db:close() if #out > 0 then say(table.concat(out, '')) else say('No match. ಠ_ಠ') end end local function handleLookup(self, source, destination, str) local db = sql.open("cache/unicode.sql") local out = {} for uchar in string.gmatch(str, "([%z\1-\127\194-\244][\128-\191]*)") do uchar = fromUtf8(uchar) if uchar then local cp = string.format('%04x', uchar) local selectStmt = db:prepare('SELECT * FROM unicode WHERE LOWER(cp) LIKE LOWER(?)') selectStmt:bind_values(cp) for row in selectStmt:nrows() do table.insert(out, string.format('U+%s %s', (row.cp), row.name)) end end end db:close() if #out > 0 then say(table.concat(out, ', ')) else say('No match. ಠ_ಠ') end end local function genMojibake(self, source, destination, str) local factor = 0.65 local db = sql.open("cache/unicode.sql") local out = {} for uchar in util.utf8.chars(str) do local ucp = fromUtf8(uchar) if ucp and math.random() >= factor then local cp = string.format('%04x', ucp) local stmt = db:prepare('SELECT name FROM unicode WHERE LOWER(cp) LIKE LOWER(?)') stmt:bind_values(cp) local code = stmt:step() if code == sql.ROW then local name = stmt:get_value(0) name = string.format('%s with%%', name) local stmt = db:prepare('SELECT * FROM unicode WHERE LOWER(name) LIKE LOWER(?) ORDER BY random() LIMIT 1') stmt:bind_values(name) local code = stmt:step() if code == sql.ROW then local cp = stmt:get_value(0) table.insert(out, string.format('%s', toUtf8(cp))) else table.insert(out, uchar) end else table.insert(out, uchar) end else table.insert(out, uchar) end end db:close() say(table.concat(out)) end return { PRIVMSG = { ['^%pu (.*)$'] = handleSearch, ['^%pus (.*)$'] = handleSearchShort, ['^%pw (.*)$'] = handleLookup, ['^%pmojibake (.*)$'] = genMojibake, } }
unicode: Fix epic merge failure...
unicode: Fix epic merge failure...
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
28c2ce5a7d317d35b19d249ec4df4d2a296c5015
Hydra/repl.lua
Hydra/repl.lua
local Stdin = {} function Stdin.new() return setmetatable({pos = 1, chars = {}, cmds = {}, cmdpos = 1}, {__index = Stdin}) end function Stdin:tostring() return table.concat(self.chars) end function Stdin:reset() self.chars = {} self.pos = 1 end function Stdin:deletechar(dir) local delpos = self.pos if dir < 0 then delpos = delpos - 1 end if delpos < 1 or delpos > #self.chars then return end table.remove(self.chars, delpos) if dir < 0 then self.pos = self.pos - 1 end end function Stdin:gochar(dir) if dir < 0 then self.pos = math.max(self.pos - 1, 1) else self.pos = math.min(self.pos + 1, #self.chars + 1) end end function Stdin:goline(dir) if dir < 0 then self.pos = 1 else self.pos = #self.chars + 1 end end function Stdin:killtoend() for i = self.pos, #self.chars do self.chars[i] = nil end end function Stdin:insertchar(char) table.insert(self.chars, self.pos, char) self.pos = self.pos + 1 end function Stdin:addcommand(cmd) self.partialcmd = nil -- redundant? table.insert(self.cmds, cmd) self.cmdpos = #self.cmds + 1 end function Stdin:maybesavecommand() if self.cmdpos == #self.cmds + 1 then self.partialcmd = self:tostring() end end function Stdin:usecurrenthistory() local partialcmd if self.cmdpos == #self.cmds + 1 then partialcmd = self.partialcmd else partialcmd = self.cmds[self.cmdpos] end self.chars = {} for i = 1, partialcmd:len() do local c = partialcmd:sub(i,i) table.insert(self.chars, c) end self.pos = #partialcmd + 1 end function Stdin:historynext() self.cmdpos = math.min(self.cmdpos + 1, #self.cmds + 1) self:usecurrenthistory() end function Stdin:historyprev() self:maybesavecommand() self.cmdpos = math.max(self.cmdpos - 1, 1) self:usecurrenthistory() end doc.hydra.repl = {"hydra.repl() -> textgrid", "Opens a readline-like REPL (Read-Eval-Print-Loop) that has full access to Hydra's API; type 'help' for more info."} function hydra.repl() local win = textgrid.open() win:settitle("Hydra REPL") win:protect() local fg = "00FF00" local bg = "222222" local scrollpos = 0 local stdout = {} local stdin = Stdin.new() local function printline(win, line, gridwidth, y) if line == nil then return end local chars = utf8.chars(line) for x = 1, math.min(#chars, gridwidth) do win:setchar(chars[x], x, y) end end local function printscrollback() local size = win:getsize() for y = 1, math.min(#stdout, size.h) do printline(win, stdout[y + scrollpos], size.w, y) end local promptlocation = #stdout - scrollpos + 1 if promptlocation <= size.h then printline(win, "> " .. stdin:tostring(), size.w, promptlocation) win:setcharfg(bg, 2 + stdin.pos, promptlocation) win:setcharbg(fg, 2 + stdin.pos, promptlocation) end end local function restrictscrollpos() scrollpos = math.max(scrollpos, 0) scrollpos = math.min(scrollpos, #stdout) end local function redraw() win:setbg(bg) win:setfg(fg) win:clear() printscrollback() end local function ensurecursorvisible() local size = win:getsize() scrollpos = math.max(scrollpos, (#stdout+1) - size.h) end win.resized = redraw local function receivedlog(str) table.insert(stdout, str) redraw() end local loghandler = logger.addhandler(receivedlog) function win.closed() logger.removehandler(loghandler) end local function runcommand() local command = stdin:tostring() stdin:reset() stdin:addcommand(command) table.insert(stdout, "> " .. command) local results = table.pack(pcall(load("return " .. command))) if not results[1] then results = table.pack(pcall(load(command))) end local success = results[1] table.remove(results, 1) local resultstr if success then for i = 1, results.n - 1 do results[i] = tostring(results[i]) end resultstr = table.concat(results, ", ") else resultstr = "error: " .. results[2] end -- add each line separately for s in string.gmatch(resultstr, "[^\n]+") do table.insert(stdout, s) end end local function runprompt() runcommand() ensurecursorvisible() end local function delcharbackward() stdin:deletechar(-1) ensurecursorvisible() end local function delcharforward() stdin:deletechar(1) ensurecursorvisible() end local function scrollcharup() scrollpos = scrollpos - 1 restrictscrollpos() end local function scrollchardown() scrollpos = scrollpos + 1 restrictscrollpos() end local function gocharforward() stdin:gochar(1) ensurecursorvisible() end local function gocharbackward() stdin:gochar(-1) ensurecursorvisible() end local function golinefirst() stdin:goline(-1) ensurecursorvisible() end local function golinelast() stdin:goline(1) ensurecursorvisible() end local function killtoend(t) stdin:killtoend() ensurecursorvisible() end local function insertchar(t) stdin:insertchar(t.key) ensurecursorvisible() end local function historynext() stdin:historynext() ensurecursorvisible() end local function historyprev() stdin:historyprev() ensurecursorvisible() end local mods = { none = 0, ctrl = 1, alt = 2, cmd = 4, shift = 8, } local keytable = { {"return", mods.none, runprompt}, {"delete", mods.none, delcharbackward}, {"h", mods.ctrl, delcharbackward}, {"d", mods.ctrl, delcharforward}, {"p", mods.alt, scrollcharup}, {"n", mods.alt, scrollchardown}, {"p", mods.ctrl, historyprev}, {"n", mods.ctrl, historynext}, {"b", mods.ctrl, gocharbackward}, {"f", mods.ctrl, gocharforward}, {"a", mods.ctrl, golinefirst}, {"e", mods.ctrl, golinelast}, {"k", mods.ctrl, killtoend}, {"left", mods.none, gocharbackward}, {"right", mods.none, gocharforward}, } function win.keydown(t) local mod = mods.none if t.ctrl then mod = bit32.bor(mod, mods.ctrl) end if t.alt then mod = bit32.bor(mod, mods.alt) end if t.cmd then mod = bit32.bor(mod, mods.cmd) end if t.shift then mod = bit32.bor(mod, mods.shift) end local fn for _, maybe in pairs(keytable) do if t.key == maybe[1] and mod == maybe[2] then fn = maybe[3] break end end if fn == nil and mod == mods.none or mod == mods.shift then fn = insertchar end if fn then fn(t) end redraw() end redraw() win:focus() return win end
local Stdin = {} function Stdin.new() return setmetatable({pos = 1, chars = {}, cmds = {}, cmdpos = 1}, {__index = Stdin}) end function Stdin:tostring() return table.concat(self.chars) end function Stdin:reset() self.chars = {} self.pos = 1 end function Stdin:deletechar(dir) local delpos = self.pos if dir < 0 then delpos = delpos - 1 end if delpos < 1 or delpos > #self.chars then return end table.remove(self.chars, delpos) if dir < 0 then self.pos = self.pos - 1 end end function Stdin:gochar(dir) if dir < 0 then self.pos = math.max(self.pos - 1, 1) else self.pos = math.min(self.pos + 1, #self.chars + 1) end end function Stdin:goline(dir) if dir < 0 then self.pos = 1 else self.pos = #self.chars + 1 end end function Stdin:killtoend() for i = self.pos, #self.chars do self.chars[i] = nil end end function Stdin:insertchar(char) table.insert(self.chars, self.pos, char) self.pos = self.pos + 1 end function Stdin:addcommand(cmd) self.partialcmd = nil -- redundant? table.insert(self.cmds, cmd) self.cmdpos = #self.cmds + 1 end function Stdin:maybesavecommand() if self.cmdpos == #self.cmds + 1 then self.partialcmd = self:tostring() end end function Stdin:usecurrenthistory() local partialcmd if self.cmdpos == #self.cmds + 1 then partialcmd = self.partialcmd else partialcmd = self.cmds[self.cmdpos] end self.chars = {} for i = 1, partialcmd:len() do local c = partialcmd:sub(i,i) table.insert(self.chars, c) end self.pos = #partialcmd + 1 end function Stdin:historynext() self.cmdpos = math.min(self.cmdpos + 1, #self.cmds + 1) self:usecurrenthistory() end function Stdin:historyprev() self:maybesavecommand() self.cmdpos = math.max(self.cmdpos - 1, 1) self:usecurrenthistory() end doc.hydra.repl = {"hydra.repl() -> textgrid", "Opens a readline-like REPL (Read-Eval-Print-Loop) that has full access to Hydra's API; type 'help' for more info."} function hydra.repl() local win = textgrid.open() win:settitle("Hydra REPL") win:protect() local fg = "00FF00" local bg = "222222" local scrollpos = 0 local stdout = {} local stdin = Stdin.new() local function printline(win, line, gridwidth, y) if line == nil then return end local chars = utf8.chars(line) for x = 1, math.min(#chars, gridwidth) do win:setchar(chars[x], x, y) end end local function printscrollback() local size = win:getsize() for y = 1, math.min(#stdout, size.h) do printline(win, stdout[y + scrollpos], size.w, y) end local promptlocation = #stdout - scrollpos + 1 if promptlocation <= size.h then printline(win, "> " .. stdin:tostring(), size.w, promptlocation) win:setcharfg(bg, 2 + stdin.pos, promptlocation) win:setcharbg(fg, 2 + stdin.pos, promptlocation) end end local function restrictscrollpos() scrollpos = math.max(scrollpos, 0) scrollpos = math.min(scrollpos, #stdout) end local function redraw() win:setbg(bg) win:setfg(fg) win:clear() printscrollback() end local function ensurecursorvisible() local size = win:getsize() scrollpos = math.max(scrollpos, (#stdout+1) - size.h) end win.resized = redraw local function appendstdout(line) line = line:gsub("\t", " ") table.insert(stdout, line) end local function receivedlog(str) appendstdout(str) redraw() end local loghandler = logger.addhandler(receivedlog) function win.closed() logger.removehandler(loghandler) end local function runcommand() local command = stdin:tostring() stdin:reset() stdin:addcommand(command) appendstdout("> " .. command) local results = table.pack(pcall(load("return " .. command))) if not results[1] then results = table.pack(pcall(load(command))) end local success = results[1] table.remove(results, 1) local resultstr if success then for i = 1, results.n - 1 do results[i] = tostring(results[i]) end resultstr = table.concat(results, ", ") else resultstr = "error: " .. results[2] end -- add each line separately for s in string.gmatch(resultstr, "[^\n]+") do appendstdout(s) end end local function runprompt() runcommand() ensurecursorvisible() end local function delcharbackward() stdin:deletechar(-1) ensurecursorvisible() end local function delcharforward() stdin:deletechar(1) ensurecursorvisible() end local function scrollcharup() scrollpos = scrollpos - 1 restrictscrollpos() end local function scrollchardown() scrollpos = scrollpos + 1 restrictscrollpos() end local function gocharforward() stdin:gochar(1) ensurecursorvisible() end local function gocharbackward() stdin:gochar(-1) ensurecursorvisible() end local function golinefirst() stdin:goline(-1) ensurecursorvisible() end local function golinelast() stdin:goline(1) ensurecursorvisible() end local function killtoend(t) stdin:killtoend() ensurecursorvisible() end local function insertchar(t) stdin:insertchar(t.key) ensurecursorvisible() end local function historynext() stdin:historynext() ensurecursorvisible() end local function historyprev() stdin:historyprev() ensurecursorvisible() end local mods = { none = 0, ctrl = 1, alt = 2, cmd = 4, shift = 8, } local keytable = { {"return", mods.none, runprompt}, {"delete", mods.none, delcharbackward}, {"h", mods.ctrl, delcharbackward}, {"d", mods.ctrl, delcharforward}, {"p", mods.alt, scrollcharup}, {"n", mods.alt, scrollchardown}, {"p", mods.ctrl, historyprev}, {"n", mods.ctrl, historynext}, {"b", mods.ctrl, gocharbackward}, {"f", mods.ctrl, gocharforward}, {"a", mods.ctrl, golinefirst}, {"e", mods.ctrl, golinelast}, {"k", mods.ctrl, killtoend}, {"left", mods.none, gocharbackward}, {"right", mods.none, gocharforward}, } function win.keydown(t) local mod = mods.none if t.ctrl then mod = bit32.bor(mod, mods.ctrl) end if t.alt then mod = bit32.bor(mod, mods.alt) end if t.cmd then mod = bit32.bor(mod, mods.cmd) end if t.shift then mod = bit32.bor(mod, mods.shift) end local fn for _, maybe in pairs(keytable) do if t.key == maybe[1] and mod == maybe[2] then fn = maybe[3] break end end if fn == nil and mod == mods.none or mod == mods.shift then fn = insertchar end if fn then fn(t) end redraw() end redraw() win:focus() return win end
Fixing printing of tab char in REPL.
Fixing printing of tab char in REPL.
Lua
mit
cmsj/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,kkamdooong/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,Stimim/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,hypebeast/hammerspoon,emoses/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,joehanchoi/hammerspoon,ocurr/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,asmagill/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,tmandry/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,lowne/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,nkgm/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,wvierber/hammerspoon,joehanchoi/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,asmagill/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,joehanchoi/hammerspoon,lowne/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,bradparks/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,asmagill/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,wvierber/hammerspoon,trishume/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,trishume/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,knu/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,wvierber/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,zzamboni/hammerspoon
a989e9579fbe56f94fb7cc48334ab1d208c927b9
tests/test-dns.lua
tests/test-dns.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 dns = require('dns') local jit = require('jit') local path = require('luvi').path -- Appveyor is failing builds randomly... need to re-enable if require('os').getenv('APPVEYOR') then return end require('tap')(function (test) test("resolve4", function (expect) dns.resolve4('luvit.io', expect(function(err, answers) assert(not err) assert(#answers > 0) p(answers) end)) end) test("resolve6", function (expect) dns.resolve6('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolve6", function (expect) dns.resolve6('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveSrv", function (expect) dns.resolveSrv('_https._tcp.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveMx", function (expect) dns.resolveMx('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveNs", function (expect) dns.resolveNs('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveCname", function (expect) dns.resolveCname('try.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveTxt", function (expect) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveTxtTimeout Order", function (expect) dns.setServers( { { ['host'] = '127.0.0.1', ['port'] = 53234 }, { ['host'] = '8.8.8.8', ['port'] = 53 } }) dns.setTimeout(200) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) assert(answers[1].server.host == '8.8.8.8') end)) end) test("resolveTxtTimeout", function (expect) dns.setServers( { { ['host'] = '127.0.0.1', ['port'] = 53234 } } ) dns.setTimeout(200) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(err) end)) end) test("resolveTxtTCP", function (expect) dns.setTimeout(2000) dns.setServers( { { ['host'] = '8.8.8.8', ['port'] = 53, ['tcp'] = true } } ) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) end)) end) test("load resolver", function () if jit.os == 'Windows' then return end local servers = dns.loadResolver({ file = path.join(module.dir, 'fixtures', 'resolve.conf.a')}) assert(#servers == 3) assert(servers[1].host == '192.168.0.1') assert(servers[2].host == '::1') assert(servers[3].host == '::2') dns.setDefaultServers() end) test("load resolver (resolv.conf search)", function () if jit.os == 'Windows' then return end local servers = dns.loadResolver({ file = path.join(module.dir, 'fixtures', 'resolve.conf.b')}) assert(#servers == 2) assert(servers[1].host == '127.0.0.1') assert(servers[2].host == '127.0.0.2') dns.setDefaultServers() end) test('bad address', function(expect) dns.resolve4('luvit.not_a_domain', expect(function(err) assert(err) assert(err.code > 0) end)) end) end)
--[[ 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 dns = require('dns') local jit = require('jit') local path = require('luvi').path -- Appveyor is failing builds randomly... need to re-enable if require('os').getenv('APPVEYOR') then return end require('tap')(function (test) test("resolve4", function (expect) dns.resolve4('luvit.io', expect(function(err, answers) assert(not err) assert(#answers > 0) p(answers) end)) end) test("resolve6", function (expect) dns.resolve6('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveSrv", function (expect) dns.resolveSrv('_https._tcp.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveMx", function (expect) dns.resolveMx('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveNs", function (expect) dns.resolveNs('luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveCname", function (expect) dns.resolveCname('try.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveTxt", function (expect) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) end)) end) test("resolveTxtTimeout Order", function (expect) dns.setServers( { { ['host'] = '127.0.0.1', ['port'] = 53234 }, { ['host'] = '8.8.8.8', ['port'] = 53 } }) dns.setTimeout(200) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) p(answers) assert(#answers > 0) assert(answers[1].server.host == '8.8.8.8') end)) end) test("resolveTxtTimeout", function (expect) dns.setServers( { { ['host'] = '127.0.0.1', ['port'] = 53234 } } ) dns.setTimeout(200) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(err) end)) end) test("resolveTxtTCP", function (expect) dns.setTimeout(2000) dns.setServers( { { ['host'] = '8.8.8.8', ['port'] = 53, ['tcp'] = true } } ) dns.resolveTxt('google._domainkey.luvit.io', expect(function(err, answers) assert(not err) end)) end) test("load resolver", function () if jit.os == 'Windows' then return end local servers = dns.loadResolver({ file = path.join(module.dir, 'fixtures', 'resolve.conf.a')}) assert(#servers == 3) assert(servers[1].host == '192.168.0.1') assert(servers[2].host == '::1') assert(servers[3].host == '::2') dns.setDefaultServers() end) test("load resolver (resolv.conf search)", function () if jit.os == 'Windows' then return end local servers = dns.loadResolver({ file = path.join(module.dir, 'fixtures', 'resolve.conf.b')}) assert(#servers == 2) assert(servers[1].host == '127.0.0.1') assert(servers[2].host == '127.0.0.2') dns.setDefaultServers() end) test('bad address', function(expect) dns.resolve4('luvit.not_a_domain', expect(function(err) assert(err) assert(err.code > 0) end)) end) end)
fix: remove duplicate dns test "resolve6"
fix: remove duplicate dns test "resolve6"
Lua
apache-2.0
zhaozg/luvit,luvit/luvit,luvit/luvit,zhaozg/luvit
97eeb9ff4cdd5b2c592bbb503837f9ea71a046b8
spec/unit/payload_spec.lua
spec/unit/payload_spec.lua
--- payload_spec.lua -- -- Copyright (c) 2013 Snowplow Analytics Ltd. All rights reserved. -- -- This program is licensed to you under the Apache License Version 2.0, -- and you may not use this file except in compliance with the Apache License Version 2.0. -- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the Apache License Version 2.0 is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. -- -- Authors: Alex Dean -- Copyright: Copyright (c) 2013 Snowplow Analytics Ltd -- License: Apache License Version 2.0 local payload = require("lib.snowplow.payload") local validate = require("lib.snowplow.validate") describe("payload", function() it("should correctly assemble a payload", function() local pb = payload.newPayloadBuilder( self.config.encodeBase64 ) pb.addRaw( "e", "sv" ) pb.add( "sv_na", "Welcome" ) pb.add( "sv_id", "231", validate.isStringOrNil ) assert.are.equal(pb.build(), "?arg") end) it("should correctly assemble a second payload", function() local pb = payload.newPayloadBuilder( self.config.encodeBase64 ) pb.addRaw( "e", "hello" ) pb.addRaw( "hello_test", "test") pb.add( "ev_ca", "2 spaces", validate.isNonEmptyString ) pb.add( "ev_va", -23.34, validate.isNumberOrNil ) assert.are.equal(pb.build(), "?arg") end) it("should error when a validation on an add() fails") local pb = payload.newPayloadBuilder( self.config.encodeBase64 ) local f = function() pb.add( "num", -2, validate.isPositiveInteger ) end assert.has_error(f, "num is required and must be a positive integer, not [-2]") end) it("should error when a validation on an addRaw() fails") local pb = payload.newPayloadBuilder( self.config.encodeBase64 ) pb.add( "ev_la", nil, validate.isStringOrNil ) local f = function() pb.addRaw( "flag", "falsy", validate.isBoolean ) end assert.has_error(f, "flag is required and must be a boolean, not [falsy]") end) end)
--- payload_spec.lua -- -- Copyright (c) 2013 Snowplow Analytics Ltd. All rights reserved. -- -- This program is licensed to you under the Apache License Version 2.0, -- and you may not use this file except in compliance with the Apache License Version 2.0. -- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the Apache License Version 2.0 is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. -- -- Authors: Alex Dean -- Copyright: Copyright (c) 2013 Snowplow Analytics Ltd -- License: Apache License Version 2.0 local payload = require("lib.snowplow.payload") local validate = require("lib.snowplow.validate") describe("payload", function() it("should correctly assemble a payload", function() local pb = payload.newPayloadBuilder( true ) pb.addRaw( "e", "sv" ) pb.add( "sv_na", "Welcome" ) pb.add( "sv_id", "231", validate.isStringOrNil ) assert.are.equal(pb.build(), "?arg") end) it("should correctly assemble a second payload", function() local pb = payload.newPayloadBuilder( false ) pb.addRaw( "e", "hello" ) pb.addRaw( "hello_test", "test") pb.add( "ev_ca", "2 spaces", validate.isNonEmptyString ) pb.add( "ev_va", -23.34, validate.isNumberOrNil ) assert.are.equal(pb.build(), "?arg") end) it("should error when a validation on an add() fails") local pb = payload.newPayloadBuilder( true ) local f = function() pb.add( "num", -2, validate.isPositiveInteger ) end assert.has_error(f, "num is required and must be a positive integer, not [-2]") end) it("should error when a validation on an addRaw() fails") local pb = payload.newPayloadBuilder( false ) pb.add( "ev_la", nil, validate.isStringOrNil ) local f = function() pb.addRaw( "flag", "falsy", validate.isBoolean ) end assert.has_error(f, "flag is required and must be a boolean, not [falsy]") end) end)
Fixed the references to config.encodeBase64
Fixed the references to config.encodeBase64
Lua
apache-2.0
snowplow/snowplow-lua-tracker
0d29892d2537bfdbb27f2a455bcd3edc2fa5a183
plugins/webshot.lua
plugins/webshot.lua
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param, psize) local response_body = { } local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = psize } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) if is_momod(msg) then local size = 'X' if matches[2] then size = matches[2] end local find = get_webshot_url(matches[1], size) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end else return lang_text('require_mod') end end return { description = "WEBSHOT", usage = { "MOD", "[#]|[sasha] webshot <url> [<size>]: Sasha fa uno screenshot del sito e lo manda, se <size> specificato lo manda con quella dimensione altrimenti con dimensione X.", "La dimensione pu essere:", "'T': (120 x 90px) - tiny", "'S': (200 x 150px) - small", "'E': (320 x 240px) - seminormal", "'N': (400 x 300px) - normal", "'M': (640 x 480px) - medium", "'L': (800 x 600px) - large", "'X': (1024 x 768px) - extra large", "'F': full page, complete page from the top to the bottom (can be pretty long)", "'Nmob': (480 x 800px) - normal", "'Fmob': full page, complete page from the top to the bottom", }, patterns = { "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)?$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.)?$", -- webshot "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)?$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+) (.)?$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)?$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.)?$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", }, run = run, min_rank = 1 }
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param, psize) local response_body = { } local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = psize } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) if is_momod(msg) then local size = 'X' if matches[2] then size = matches[2] end local find = get_webshot_url(matches[1], size) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end else return lang_text('require_mod') end end return { description = "WEBSHOT", usage = { "MOD", "[#]|[sasha] webshot <url> [<size>]: Sasha fa uno screenshot del sito e lo manda, se <size> specificato lo manda con quella dimensione altrimenti con dimensione X.", "La dimensione pu essere:", "'T': (120 x 90px) - tiny", "'S': (200 x 150px) - small", "'E': (320 x 240px) - seminormal", "'N': (400 x 300px) - normal", "'M': (640 x 480px) - medium", "'L': (800 x 600px) - large", "'X': (1024 x 768px) - extra large", "'F': full page, complete page from the top to the bottom (can be pretty long)", "'Nmob': (480 x 800px) - normal", "'Fmob': full page, complete page from the top to the bottom", }, patterns = { "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", -- webshot "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+) (.)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", }, run = run, min_rank = 1 }
patterns fix
patterns fix
Lua
agpl-3.0
xsolinsx/AISasha
52fcdbf99071105f3a2c9221a406a05fec5d4692
Hydra/API/window.lua
Hydra/API/window.lua
--- window --- --- Functions for managing any window. --- --- To get windows, see `window.focusedwindow` and `window.visiblewindows`. --- --- To get window geometrical attributes, see `window.{frame,size,topleft}`. --- --- To move and resize windows, see `window.set{frame,size,topleft}`. --- --- It may be handy to get a window's app or screen via `window.application` and `window.screen`. --- --- See the `screen` module for detailed explanation of how Hydra uses window/screen coordinates. --- window.allwindows() -> win[] --- Returns all windows function window.allwindows() return fnutils.mapcat(application.runningapplications(), application.allwindows) end --- window.windowforid() -> win or nil --- Returns the window for the given id, or nil if it's an invalid id. function window.windowforid(id) return fnutils.find(window.allwindows(), function(win) return win:id() == id end) end --- window:isvisible() -> bool --- True if the app is not hidden or minimized. function window:isvisible() return not self:application():ishidden() and not self:isminimized() end --- window:frame() -> rect --- Get the frame of the window in absolute coordinates. function window:frame() local s = self:size() local tl = self:topleft() return {x = tl.x, y = tl.y, w = s.w, h = s.h} end --- window:setframe(rect) --- Set the frame of the window in absolute coordinates. function window:setframe(f) self:setsize(f) self:settopleft(f) self:setsize(f) end --- window:otherwindows_samescreen() -> win[] --- Get other windows on the same screen as self. function window:otherwindows_samescreen() return fnutils.filter(window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end) end --- window:otherwindows_allscreens() -> win[] --- Get every window except this one. function window:otherwindows_allscreens() return fnutils.filter(window.visiblewindows(), function(win) return self ~= win end) end --- window:focus() -> bool --- Try to make this window focused. function window:focus() return self:becomemain() and self:application():activate() end --- window.visiblewindows() -> win[] --- Get all windows on all screens that match window.isvisible. function window.visiblewindows() return fnutils.filter(window:allwindows(), window.isvisible) end --- window.orderedwindows() -> win[] --- Returns all visible windows, ordered from front to back. function window.orderedwindows() local orderedwins = {} local orderedwinids = window._orderedwinids() local windows = window.visiblewindows() fnutils.each(windows, function(win) win:_cachewinid() end) for _, orderedwinid in pairs(orderedwinids) do for _, win in pairs(windows) do if orderedwinid == win._winid then table.insert(orderedwins, win) break end end end return orderedwins end --- window:maximize() --- Make this window fill the whole screen its on, without covering the dock or menu. function window:maximize() local screenrect = self:screen():frame_without_dock_or_menu() self:setframe(screenrect) end --- window:screen() --- Get the screen which most contains this window (by area). function window:screen() local windowframe = self:frame() local lastvolume = 0 local lastscreen = nil for _, screen in pairs(screen.allscreens()) do local screenframe = screen:frame_including_dock_and_menu() local intersection = geometry.intersectionrect(windowframe, screenframe) local volume = intersection.w * intersection.h if volume > lastvolume then lastvolume = volume lastscreen = screen end end return lastscreen end local function windows_in_direction(win, numrotations) -- assume looking to east -- use the score distance/cos(A/2), where A is the angle by which it -- differs from the straight line in the direction you're looking -- for. (may have to manually prevent division by zero.) -- thanks mark! local thiswindow = window.focusedwindow() local startingpoint = geometry.rectmidpoint(thiswindow:frame()) local otherwindows = fnutils.filter(thiswindow:otherwindows_allscreens(), function(win) return window.isvisible(win) and window.isstandard(win) end) local closestwindows = {} for _, win in pairs(otherwindows) do local otherpoint = geometry.rectmidpoint(win:frame()) otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations) local delta = { x = otherpoint.x - startingpoint.x, y = otherpoint.y - startingpoint.y, } if delta.x > 0 then local angle = math.atan2(delta.y, delta.x) local distance = geometry.hypot(delta) local anglediff = -angle local score = distance / math.cos(anglediff / 2) table.insert(closestwindows, {win = win, score = score}) end end table.sort(closestwindows, function(a, b) return a.score < b.score end) return fnutils.map(closestwindows, function(x) return x.win end) end local function focus_first_valid_window(ordered_wins) for _, win in pairs(ordered_wins) do if win:focus() then return true end end return false end --- window:windows_to_east() --- Get all windows east of this one, ordered by closeness. --- window:windows_to_west() --- Get all windows west of this one, ordered by closeness. --- window:windows_to_north() --- Get all windows north of this one, ordered by closeness. --- window:windows_to_south() --- Get all windows south of this one, ordered by closeness. --- window:focuswindow_east() --- Focus the first focus-able window to the east of this one. --- window:focuswindow_west() --- Focus the first focus-able window to the west of this one. --- window:focuswindow_north() --- Focus the first focus-able window to the north of this one. --- window:focuswindow_south() --- Focus the first focus-able window to the south of this one. function window:windows_to_east() return windows_in_direction(self, 0) end function window:windows_to_west() return windows_in_direction(self, 2) end function window:windows_to_north() return windows_in_direction(self, 1) end function window:windows_to_south() return windows_in_direction(self, 3) end function window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end function window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end function window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end function window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
--- window --- --- Functions for managing any window. --- --- To get windows, see `window.focusedwindow` and `window.visiblewindows`. --- --- To get window geometrical attributes, see `window.{frame,size,topleft}`. --- --- To move and resize windows, see `window.set{frame,size,topleft}`. --- --- It may be handy to get a window's app or screen via `window.application` and `window.screen`. --- --- See the `screen` module for detailed explanation of how Hydra uses window/screen coordinates. --- window.allwindows() -> win[] --- Returns all windows function window.allwindows() return fnutils.mapcat(application.runningapplications(), application.allwindows) end --- window.windowforid() -> win or nil --- Returns the window for the given id, or nil if it's an invalid id. function window.windowforid(id) return fnutils.find(window.allwindows(), function(win) return win:id() == id end) end --- window:isvisible() -> bool --- True if the app is not hidden or minimized. function window:isvisible() return not self:application():ishidden() and not self:isminimized() end --- window:frame() -> rect --- Get the frame of the window in absolute coordinates. function window:frame() local s = self:size() local tl = self:topleft() return {x = tl.x, y = tl.y, w = s.w, h = s.h} end --- window:setframe(rect) --- Set the frame of the window in absolute coordinates. function window:setframe(f) self:setsize(f) self:settopleft(f) self:setsize(f) end --- window:otherwindows_samescreen() -> win[] --- Get other windows on the same screen as self. function window:otherwindows_samescreen() return fnutils.filter(window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end) end --- window:otherwindows_allscreens() -> win[] --- Get every window except this one. function window:otherwindows_allscreens() return fnutils.filter(window.visiblewindows(), function(win) return self ~= win end) end --- window:focus() -> bool --- Try to make this window focused. function window:focus() return self:becomemain() and self:application():activate() end --- window.visiblewindows() -> win[] --- Get all windows on all screens that match window.isvisible. function window.visiblewindows() return fnutils.filter(window:allwindows(), window.isvisible) end --- window.orderedwindows() -> win[] --- Returns all visible windows, ordered from front to back. function window.orderedwindows() local orderedwins = {} local orderedwinids = window._orderedwinids() local windows = window.visiblewindows() for _, orderedwinid in pairs(orderedwinids) do for _, win in pairs(windows) do if orderedwinid == win:id() then table.insert(orderedwins, win) break end end end return orderedwins end --- window:maximize() --- Make this window fill the whole screen its on, without covering the dock or menu. function window:maximize() local screenrect = self:screen():frame_without_dock_or_menu() self:setframe(screenrect) end --- window:screen() --- Get the screen which most contains this window (by area). function window:screen() local windowframe = self:frame() local lastvolume = 0 local lastscreen = nil for _, screen in pairs(screen.allscreens()) do local screenframe = screen:frame_including_dock_and_menu() local intersection = geometry.intersectionrect(windowframe, screenframe) local volume = intersection.w * intersection.h if volume > lastvolume then lastvolume = volume lastscreen = screen end end return lastscreen end local function windows_in_direction(win, numrotations) -- assume looking to east -- use the score distance/cos(A/2), where A is the angle by which it -- differs from the straight line in the direction you're looking -- for. (may have to manually prevent division by zero.) -- thanks mark! local thiswindow = window.focusedwindow() local startingpoint = geometry.rectmidpoint(thiswindow:frame()) local otherwindows = fnutils.filter(thiswindow:otherwindows_allscreens(), function(win) return window.isvisible(win) and window.isstandard(win) end) local closestwindows = {} for _, win in pairs(otherwindows) do local otherpoint = geometry.rectmidpoint(win:frame()) otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations) local delta = { x = otherpoint.x - startingpoint.x, y = otherpoint.y - startingpoint.y, } if delta.x > 0 then local angle = math.atan2(delta.y, delta.x) local distance = geometry.hypot(delta) local anglediff = -angle local score = distance / math.cos(anglediff / 2) table.insert(closestwindows, {win = win, score = score}) end end table.sort(closestwindows, function(a, b) return a.score < b.score end) return fnutils.map(closestwindows, function(x) return x.win end) end local function focus_first_valid_window(ordered_wins) for _, win in pairs(ordered_wins) do if win:focus() then return true end end return false end --- window:windows_to_east() --- Get all windows east of this one, ordered by closeness. --- window:windows_to_west() --- Get all windows west of this one, ordered by closeness. --- window:windows_to_north() --- Get all windows north of this one, ordered by closeness. --- window:windows_to_south() --- Get all windows south of this one, ordered by closeness. --- window:focuswindow_east() --- Focus the first focus-able window to the east of this one. --- window:focuswindow_west() --- Focus the first focus-able window to the west of this one. --- window:focuswindow_north() --- Focus the first focus-able window to the north of this one. --- window:focuswindow_south() --- Focus the first focus-able window to the south of this one. function window:windows_to_east() return windows_in_direction(self, 0) end function window:windows_to_west() return windows_in_direction(self, 2) end function window:windows_to_north() return windows_in_direction(self, 1) end function window:windows_to_south() return windows_in_direction(self, 3) end function window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end function window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end function window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end function window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
Fixes window.orderedwindows(); closes #207.
Fixes window.orderedwindows(); closes #207.
Lua
mit
hypebeast/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,tmandry/hammerspoon,trishume/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,CommandPost/CommandPost-App,wvierber/hammerspoon,nkgm/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,emoses/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,heptal/hammerspoon,zzamboni/hammerspoon,dopcn/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,kkamdooong/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,trishume/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,peterhajas/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,CommandPost/CommandPost-App,TimVonsee/hammerspoon,junkblocker/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,lowne/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,Habbie/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,heptal/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,nkgm/hammerspoon
0df9649feb4417edf895a33bcfd25ec196a11f7e
scripts/example.lua
scripts/example.lua
function process(packet) if packet.size ~= 0 then -- skip the syn and ack local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec print(string.format("%s %s:%d=>%s:%d %s %u %u %d %u %s", time_str, packet.sip, -- source ip packet.sport, -- source port packet.dip, -- destination ip packet.dport, -- destination port type, -- request or response packet packet.seq, -- sequence number packet.ack, -- ack number packet.flags, -- flags, e.g. syn|ack|psh.. packet.size, -- payload size packet.payload -- payload )) end end
function process(packet) if packet.size ~= 0 then -- skip the syn and ack local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec print(string.format("%s %s:%d=>%s:%d %s %u %u %d %u %s", time_str, packet.sip, -- source ip packet.sport, -- source port packet.dip, -- destination ip packet.dport, -- destination port packet.seq, -- sequence number packet.ack, -- ack number packet.flags, -- flags, e.g. syn|ack|psh.. packet.size, -- payload size packet.payload -- payload )) end end
FIX: remove non-exists from example.lua
FIX: remove non-exists from example.lua
Lua
mit
git-hulk/tcpkit,git-hulk/tcpkit
a0f4015f7d9e74762bc444ab405dbebba50326ed
frontend/ui/opdsparser.lua
frontend/ui/opdsparser.lua
--[[ This code is derived from the LAPHLibs which can be found here: https://github.com/Wiladams/LAPHLibs --]] local util = require("util") local luxl = require("luxl") local ffi = require("ffi") local OPDSParser = {} local unescape_map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } local gsub = string.gsub local function unescape(str) return gsub(str, '(&(#?)([%d%a]+);)', function(orig, n, s) if unescape_map[s] then return unescape_map[s] elseif n == "#" then -- unescape unicode return util.unicodeCodepointToUtf8(tonumber(s)) else return orig end end) end function OPDSParser:createFlatXTable(xlex, curr_element) curr_element = curr_element or {} local curr_attr_name local attr_count = 0 -- start reading the thing for event, offset, size in xlex:Lexemes() do local txt = ffi.string(xlex.buf + offset, size) if event == luxl.EVENT_START then if txt ~= "xml" then -- does current element already have something -- with this name? -- if it does, if it's a table, add to it -- if it doesn't, then add a table local tab = self:createFlatXTable(xlex) if txt == "entry" or txt == "link" then if curr_element[txt] == nil then curr_element[txt] = {} end table.insert(curr_element[txt], tab) elseif type(curr_element) == "table" then curr_element[txt] = tab end end elseif event == luxl.EVENT_ATTR_NAME then curr_attr_name = unescape(txt) elseif event == luxl.EVENT_ATTR_VAL then curr_element[curr_attr_name] = unescape(txt) attr_count = attr_count + 1 curr_attr_name = nil elseif event == luxl.EVENT_TEXT then curr_element = unescape(txt) elseif event == luxl.EVENT_END then return curr_element end end return curr_element end function OPDSParser:parse(text) -- Murder Calibre's whole "content" block, because luxl doesn't really deal well with various XHTML quirks, -- as the list of crappy replacements below attests to... -- There's also a high probability of finding orphaned tags or badly nested ones in there, which will screw everything up. text = text:gsub('<content type="xhtml">.-</content>', '') -- luxl doesn't handle XML comments, so strip them text = text:gsub("<!%-%-.-%-%->", "") -- luxl prefers <br />, the other two forms are valid in HTML, but will kick luxl's ass text = text:gsub("<br>", "<br />") text = text:gsub("<br/>", "<br />") -- Same deal with hr text = text:gsub("<hr>", "<hr />") text = text:gsub("<hr/>", "<hr />") -- It's also allergic to orphaned <em/> (As opposed to a balanced <em></em> pair)... text = text:gsub("<em/>", "") -- Let's assume it might also happen to strong... text = text:gsub("<strong/>", "") -- Some OPDS catalogs wrap text in a CDATA section, remove it as it causes parsing problems text = text:gsub("<!%[CDATA%[(.-)%]%]>", function (s) return s:gsub( "%p", {["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;" } ) end ) local xlex = luxl.new(text, #text) return assert(self:createFlatXTable(xlex)) end return OPDSParser
--[[ This code is derived from the LAPHLibs which can be found here: https://github.com/Wiladams/LAPHLibs --]] local util = require("util") local luxl = require("luxl") local ffi = require("ffi") local OPDSParser = {} local unescape_map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } local gsub = string.gsub local function unescape(str) return gsub(str, '(&(#?)([%d%a]+);)', function(orig, n, s) if unescape_map[s] then return unescape_map[s] elseif n == "#" then -- unescape unicode return util.unicodeCodepointToUtf8(tonumber(s)) else return orig end end) end function OPDSParser:createFlatXTable(xlex, curr_element) curr_element = curr_element or {} local curr_attr_name local attr_count = 0 -- start reading the thing for event, offset, size in xlex:Lexemes() do local txt = ffi.string(xlex.buf + offset, size) if event == luxl.EVENT_START then if txt ~= "xml" then -- does current element already have something -- with this name? -- if it does, if it's a table, add to it -- if it doesn't, then add a table local tab = self:createFlatXTable(xlex) if txt == "entry" or txt == "link" then if curr_element[txt] == nil then curr_element[txt] = {} end table.insert(curr_element[txt], tab) elseif type(curr_element) == "table" then curr_element[txt] = tab end end elseif event == luxl.EVENT_ATTR_NAME then curr_attr_name = unescape(txt) elseif event == luxl.EVENT_ATTR_VAL then curr_element[curr_attr_name] = unescape(txt) attr_count = attr_count + 1 curr_attr_name = nil elseif event == luxl.EVENT_TEXT then curr_element = unescape(txt) elseif event == luxl.EVENT_END then return curr_element end end return curr_element end function OPDSParser:parse(text) -- Murder Calibre's whole "content" block, because luxl doesn't really deal well with various XHTML quirks, -- as the list of crappy replacements below attests to... -- There's also a high probability of finding orphaned tags or badly nested ones in there, which will screw everything up. text = text:gsub('<content type="xhtml">.-</content>', '') -- luxl doesn't handle XML comments, so strip them text = text:gsub("<!%-%-.-%-%->", "") -- luxl is also particular about the syntax for self-closing, empty & orphaned tags... text = text:gsub("<(%l+)/>", "<%1 />") -- We also need to handle the slash-less variants for br & hr... text = text:gsub("<br>", "<br />") text = text:gsub("<hr>", "<hr />") -- Some OPDS catalogs wrap text in a CDATA section, remove it as it causes parsing problems text = text:gsub("<!%[CDATA%[(.-)%]%]>", function (s) return s:gsub( "%p", {["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;" } ) end ) local xlex = luxl.new(text, #text) return assert(self:createFlatXTable(xlex)) end return OPDSParser
Workaround luxl's issue with self-closing tags once and for all (#6994)
Workaround luxl's issue with self-closing tags once and for all (#6994) * luxl and self-closing tags, once more with feeling... Fix #6993 * More generic fix to the self-closing tag issue w/ luxl Re #6902 & co.
Lua
agpl-3.0
koreader/koreader,Frenzie/koreader,poire-z/koreader,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,Frenzie/koreader,mwoz123/koreader,poire-z/koreader,pazos/koreader,NiLuJe/koreader,Markismus/koreader
4f784635da0ca1ada073894e9d771a56ec285f03
lib/redis/voncount.lua
lib/redis/voncount.lua
-------------- Function to simulate inheritance ------------------------------------- -- local function inheritsFrom( baseClass ) -- local new_class = {} -- local class_mt = { __index = new_class } -- if baseClass then -- setmetatable( new_class, { __index = baseClass } ) -- end -- return new_class -- end ---------- Array methods --------------------------- local function concatToArray(a1, a2) for i = 1, #a2 do a1[#a1 + 1] = a2[i] end return a1 end local function flattenArray(arr) local flat = {} for i = 1, #arr do if type(arr[i]) == "table" then local inner_flatten = flattenArray(arr[i]) concatToArray(flat, inner_flatten) else flat[#flat + 1] = arr[i] end end return flat end local function dupArray(arr) local dup = {} for i = 1, #arr do dup[i] = arr[i] end return dup end ----------------------------------------------------- -------------- Base Class --------------------------------------------------------- local Base = {} function Base:new(_obj_type, ids, _type) local redis_key = _obj_type for k, id in ipairs(ids) do redis_key = redis_key .. "_" .. id end local baseObj = { redis_key = redis_key, _type = _type, _ids = ids, _obj_type = _obj_type } self.__index = self return setmetatable(baseObj, self) end function Base:count(key, num) local allKeys = flattenArray({ key }) for i, curKey in ipairs(allKeys) do if self._type == "set" then redis.call("ZINCRBY", self.redis_key, num, curKey) else redis.call("HINCRBY", self.redis_key, curKey, num) end end end function Base:expire(ttl) if redis.call("TTL", self.redis_key) == -1 then redis.call("EXPIRE", self.redis_key, ttl) end end ----------------- Custom Methods ------------------------- function Base:conditionalCount(should_count, key) if should_count ~= "0" and should_count ~= "false" then self:count(key, 1) end end function Base:countIfExist(value, should_count, key) if value and value ~= "" and value ~= "null" and value ~= "nil" then self:conditionalCount(should_count, key) end end function Base:sevenDaysCount(should_count, key) if should_count ~= "0" and should_count ~= "false" then local first_day = tonumber(self._ids[3]) for day = 0, 6, 1 do local curDayObjIds = dupArray(self._ids) curDayObjIds[3] = (first_day + day) % 366 local curDayObj = Base:new(self._obj_type, curDayObjIds, self._type) curDayObj:count(key, 1) curDayObj:expire(1209600) -- expire in 2 weeks end end end function Base:countAndSetIf(should_count, countKey, redisKey, setKey) if should_count ~= "0" and should_count ~= "false" then self:count(countKey, 1) local setCount = redis.call("ZCOUNT", self.redis_key, "-inf", "+inf") redis.call("HSET", redisKey, setKey, setCount) end end ---------------------------------------------------------- ------------- Helper Methods ------------------------ -- return an array with all the values in tbl that match the given keys array local function getValueByKeys(tbl, keys) local values = {} if type(keys) == "table" then for i, key in ipairs(keys) do table.insert(values, tbl[key]) end else table.insert(values, tbl[keys]) end return values end local function justDebugIt(tbl, key) local rslt = { key } local match = key:match("{[%w_]*}") while match do local subStrings = flattenArray({ tbl[match:sub(2, -2)] }) local tempResult = {} for i, subStr in ipairs(subStrings) do local dup = dupArray(rslt) for j, existingKey in ipairs(dup) do local curKey = existingKey:gsub(match, subStr) dup[j] = curKey end concatToArray(tempResult, dup) end rslt = tempResult match = rslt[1]:match("{[%w_]*}") end if #rslt == 1 then return rslt[1] else return rslt end end -- parse key and replace "place holders" with their value from tbl. -- matching replace values in tbl can be arrays, in such case an array will be returned with all the possible keys combinations local function addValuesToKey(tbl, key) local status, err = pcall(justDebugIt, tbl, key) if not status then redis.call("SET", "JustDebugIt", "match is " .. key:match("{.*}") .. " key is " .. key) end local rslt = { key } local match = key:match("{[%w_]*}") while match do local subStrings = flattenArray({ tbl[match:sub(2, -2)] }) local tempResult = {} for i, subStr in ipairs(subStrings) do local dup = dupArray(rslt) for j, existingKey in ipairs(dup) do local curKey = existingKey:gsub(match, subStr) dup[j] = curKey end concatToArray(tempResult, dup) end rslt = tempResult match = rslt[1]:match("{[%w_]*}") end if #rslt == 1 then return rslt[1] else return rslt end end -------------------------------------------------- local mode = ARGV[2] or "live" local arg = ARGV[1] local params = cjson.decode(arg) local config = cjson.decode(redis.call("get", "von_count_config_".. mode)) local action = params["action"] local defaultMethod = { change = 1, custom_functions = {} } local action_config = config[action] if action_config then for obj_type, methods in pairs(action_config) do for i, defs in ipairs(methods) do setmetatable(defs, { __index = defaultMethod }) local ids = getValueByKeys(params, defs["id"]) local _type = defs["type"] or "hash" local obj = Base:new(obj_type, ids, _type) if defs["count"] then local key = addValuesToKey(params, defs["count"]) local change = defs["change"] obj:count(key, change) end for j, custom_function in ipairs(defs["custom_functions"]) do local function_name = custom_function["name"] local args = {} for z, arg in ipairs(custom_function["args"]) do local arg_value = addValuesToKey(params, arg) table.insert(args, arg_value) end obj[function_name](obj, unpack(args)) end if defs["expire"] then obj:expire(defs["expire"]) end end end end
-------------- Function to simulate inheritance ------------------------------------- -- local function inheritsFrom( baseClass ) -- local new_class = {} -- local class_mt = { __index = new_class } -- if baseClass then -- setmetatable( new_class, { __index = baseClass } ) -- end -- return new_class -- end ---------- Array methods --------------------------- local function concatToArray(a1, a2) for i = 1, #a2 do a1[#a1 + 1] = a2[i] end return a1 end local function flattenArray(arr) local flat = {} for i = 1, #arr do if type(arr[i]) == "table" then local inner_flatten = flattenArray(arr[i]) concatToArray(flat, inner_flatten) else flat[#flat + 1] = arr[i] end end return flat end local function dupArray(arr) local dup = {} for i = 1, #arr do dup[i] = arr[i] end return dup end ----------------------------------------------------- -------------- Base Class --------------------------------------------------------- local Base = {} function Base:new(_obj_type, ids, _type) local redis_key = _obj_type for k, id in ipairs(ids) do redis_key = redis_key .. "_" .. id end local baseObj = { redis_key = redis_key, _type = _type, _ids = ids, _obj_type = _obj_type } self.__index = self return setmetatable(baseObj, self) end function Base:count(key, num) local allKeys = flattenArray({ key }) for i, curKey in ipairs(allKeys) do if self._type == "set" then redis.call("ZINCRBY", self.redis_key, num, curKey) else redis.call("HINCRBY", self.redis_key, curKey, num) end end end function Base:expire(ttl) if redis.call("TTL", self.redis_key) == -1 then redis.call("EXPIRE", self.redis_key, ttl) end end ----------------- Custom Methods ------------------------- function Base:conditionalCount(should_count, key) if should_count ~= "0" and should_count ~= "false" then self:count(key, 1) end end function Base:countIfExist(value, should_count, key) if value and value ~= "" and value ~= "null" and value ~= "nil" then self:conditionalCount(should_count, key) end end function Base:sevenDaysCount(should_count, key) if should_count ~= "0" and should_count ~= "false" then local first_day = tonumber(self._ids[3]) for day = 0, 6, 1 do local curDayObjIds = dupArray(self._ids) curDayObjIds[3] = (first_day + day) % 366 local curDayObj = Base:new(self._obj_type, curDayObjIds, self._type) curDayObj:count(key, 1) curDayObj:expire(1209600) -- expire in 2 weeks end end end function Base:countAndSetIf(should_count, countKey, redisKey, setKey) if should_count ~= "0" and should_count ~= "false" then self:count(countKey, 1) local setCount = redis.call("ZCOUNT", self.redis_key, "-inf", "+inf") redis.call("HSET", redisKey, setKey, setCount) end end ---------------------------------------------------------- ------------- Helper Methods ------------------------ -- return an array with all the values in tbl that match the given keys array local function getValueByKeys(tbl, keys) local values = {} if type(keys) == "table" then for i, key in ipairs(keys) do table.insert(values, tbl[key]) end else table.insert(values, tbl[keys]) end return values end local function justDebugIt(tbl, key) local rslt = { key } local match = key:match("{[%w_]*}") while match do local subStrings = flattenArray({ tbl[match:sub(2, -2)] }) local tempResult = {} for i, subStr in ipairs(subStrings) do local dup = dupArray(rslt) for j, existingKey in ipairs(dup) do local curKey = existingKey:gsub(match, subStr) dup[j] = curKey end concatToArray(tempResult, dup) end rslt = tempResult match = rslt[1]:match("{[%w_]*}") end if #rslt == 1 then return rslt[1] else return rslt end end -- parse key and replace "place holders" with their value from tbl. -- matching replace values in tbl can be arrays, in such case an array will be returned with all the possible keys combinations local function addValuesToKey(tbl, key) local status, err = pcall(justDebugIt, tbl, key) if not status then redis.call("SET", "JustDebugIt", "match is " .. key:match("{.*}") .. " key is " .. key) end local rslt = { key } local match = key:match("{[%w_]*}") while match do local subStrings = flattenArray({ tbl[match:sub(2, -2)] }) local tempResult = {} for i, subStr in ipairs(subStrings) do local dup = dupArray(rslt) for j, existingKey in ipairs(dup) do local curKey = existingKey:gsub(match, subStr) dup[j] = curKey end concatToArray(tempResult, dup) end rslt = tempResult if #rslt > 0 then match = rslt[1]:match("{[%w_]*}") else match = nil end end if #rslt == 1 then return rslt[1] else return rslt end end -------------------------------------------------- local mode = ARGV[2] or "live" local arg = ARGV[1] local params = cjson.decode(arg) local config = cjson.decode(redis.call("get", "von_count_config_".. mode)) local action = params["action"] local defaultMethod = { change = 1, custom_functions = {} } local action_config = config[action] if action_config then for obj_type, methods in pairs(action_config) do for i, defs in ipairs(methods) do setmetatable(defs, { __index = defaultMethod }) local ids = getValueByKeys(params, defs["id"]) local _type = defs["type"] or "hash" local obj = Base:new(obj_type, ids, _type) if defs["count"] then local key = addValuesToKey(params, defs["count"]) local change = defs["change"] obj:count(key, change) end for j, custom_function in ipairs(defs["custom_functions"]) do local function_name = custom_function["name"] local args = {} for z, arg in ipairs(custom_function["args"]) do local arg_value = addValuesToKey(params, arg) table.insert(args, arg_value) end obj[function_name](obj, unpack(args)) end if defs["expire"] then obj:expire(defs["expire"]) end end end end
small fix for non existing variables
small fix for non existing variables
Lua
mit
FTBpro/count-von-count,FTBpro/count-von-count
d9df3871d45a23b87dfe39ecc1c03661f0115f41
src/lua-factory/sources/grl-guardianvideos.lua
src/lua-factory/sources/grl-guardianvideos.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 * --]] -- Test the API at: -- http://explorer.content.guardianapis.com/search?api-key=rppwmmu3mfqj6gkbs8kcjg23&show-fields=all&page-size=50&tag=type/video API_KEY = 'rppwmmu3mfqj6gkbs8kcjg23' GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=type/video&page=%d&page-size=%d&show-fields=all&api-key=%s' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, icon = 'resource:///org/gnome/grilo/plugins/guardianvideos/guardianvideos.svg', tags = { 'news', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count, API_KEY) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count, API_KEY) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count, API_KEY) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end grl.fetch(urls, guardianvideos_fetch_cb) end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results) local count = grl.get_options("count") for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then grl.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.url = item.webUrl media.title = grl.unescape(item.webTitle) media.thumbnail = item.fields.thumbnail 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 * --]] -- Test the API at: -- http://explorer.content.guardianapis.com/search?api-key=rppwmmu3mfqj6gkbs8kcjg23&show-fields=all&page-size=50&tag=type/video API_KEY = 'rppwmmu3mfqj6gkbs8kcjg23' GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=type/video&page=%d&page-size=%d&show-fields=all&api-key=%s' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, icon = 'resource:///org/gnome/grilo/plugins/guardianvideos/guardianvideos.svg', tags = { 'news', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count, API_KEY) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count, API_KEY) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count, API_KEY) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end grl.fetch(urls, guardianvideos_fetch_cb) end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results) local count = grl.get_options("count") for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then grl.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.title = grl.unescape(item.webTitle) main = item.fields.main -- Some entries rarely don't have a 'main' field. So, we bail out. if not main then grl.warning ("No media URL metadata found for: " .. media.title) return media end media.url = main:match('src="(.-%.mp4)"') media.thumbnail = main:match('poster="(.-%.jpg)"') if not media.url then grl.warning ("No media streaming URL found for: " .. media.title) grl.debug ("Data from: " .. media.title .. "\n" .. grl.lua.inspect(item)); end if not media.thumbnail then -- Try to see if we have a 'thumbnail' field. This field seems -- to exist for some entries, which don't have a 'poster' field if item.fields.thumbnail then media.thumbnail = item.fields.thumbnail else grl.debug ("No media thumbnail URL found for: " .. media.title) end end return media end
guardianvideos: Fix parsing of metadata
guardianvideos: Fix parsing of metadata Closes #2 Signed-off-by: Victor Toso <39b7599ff73bbf5db531748ba5250f21fa7120ff@redhat.com>
Lua
lgpl-2.1
jasuarez/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
f0037bb50230e6350e10ad174233b12e4114d246
lualib/socket.lua
lualib/socket.lua
local core = require "silly.core" local ns = require "netstream" local nb_pool = {} local socket_pool = {} local socket = {} local EVENT = {} function EVENT.close(_, fd, _, _) local s = socket_pool[fd] if s == nil then return end ns.clear(s.sbuffer) if s.co then local co = s.co s.co = false core.resume(co, false) end socket_pool[fd] = nil end function EVENT.data(_, fd, _, message) local s = socket_pool[fd] s.sbuffer = ns.push(nb_pool, s.sbuffer, message) if not s.delim then --non suspend read assert(not s.co) return end if type(s.delim) == "number" then assert(s.co) if ns.check(s.sbuffer, s.delim) then local co = s.co s.co = false s.delim = false core.resume(co, true) end elseif type(s.delim) == "string" then assert(s.co) if ns.checkline(s.sbuffer, s.delim) then local co = s.co s.co = false s.delim = false core.resume(co, true) end end end local function socket_dispatch(type, fd, _, message) local s = assert(socket_pool[fd]) assert(type ~= "accept") assert(EVENT[type])(type, fd, _, message) end function socket.connect(ip, port) local fd = core.connect(ip, port, socket_dispatch) if fd < 0 then return fd end s = { fd = fd, delim = false, suspend = false, co = false, } setmetatable(s, { __index = self, __gc = function(t) ns.clear(nb_pool, t.sbuffer) if t.fd then core.close(t.fd) end end }) socket_pool[fd] = s return fd end function socket.close(fd) local s = socket_pool[fd] assert(s) assert(not s.co) ns.clear(nb_pool, s.sbuffer) socket_pool[fd] = nil core.close(fd) end function socket.closed(fd) local s = socket_pool[fd] if s then return true else return false end end local function suspend(s) assert(not s.co) s.co = core.running() return core.yield() end function socket.read(fd, n) local s = socket_pool[fd] assert(s) local r = ns.read(nb_pool, s.sbuffer, n) if r then return r end s.delim = n local ok = suspend(s) if ok == false then --occurs error return nil end local r = ns.read(nb_pool, s.sbuffer, n) assert(r) return r; end function socket.readline(fd, delim) delim = delim or "\n" local s = socket_pool[fd] assert(s) local r = ns.readline(nb_pool, s.sbuffer, delim) if r then return r end s.delim = delim local ok = suspend(s) if ok == false then --occurs error return nil end local r = ns.readline(nb_pool, s.sbuffer, delim) assert(r) return r end function socket.write(fd, str) local p, sz = ns.pack(str) core.write(fd, p, sz) end return socket
local core = require "silly.core" local ns = require "netstream" local nb_pool = {} local socket_pool = {} local socket = {} local EVENT = {} function EVENT.close(_, fd, _, _) local s = socket_pool[fd] if s == nil then return end ns.clear(s.sbuffer) if s.co then local co = s.co s.co = false core.resume(co, false) end socket_pool[fd] = nil end function EVENT.data(_, fd, _, message) local s = socket_pool[fd] s.sbuffer = ns.push(nb_pool, s.sbuffer, message) if not s.delim then --non suspend read assert(not s.co) return end if type(s.delim) == "number" then assert(s.co) if ns.check(s.sbuffer, s.delim) then local co = s.co s.co = false s.delim = false core.resume(co, true) end elseif type(s.delim) == "string" then assert(s.co) if ns.checkline(s.sbuffer, s.delim) then local co = s.co s.co = false s.delim = false core.resume(co, true) end end end local function socket_dispatch(type, fd, _, message) local s = assert(socket_pool[fd]) assert(type ~= "accept") assert(EVENT[type])(type, fd, _, message) end function socket.connect(ip, port) local fd = core.connect(ip, port, socket_dispatch) if fd < 0 then return fd end s = { fd = fd, delim = false, suspend = false, co = false, } socket_pool[fd] = s return fd end function socket.close(fd) local s = socket_pool[fd] assert(s) assert(not s.co) ns.clear(nb_pool, s.sbuffer) socket_pool[fd] = nil core.close(fd) end function socket.closed(fd) local s = socket_pool[fd] if s then return true else return false end end local function suspend(s) assert(not s.co) s.co = core.running() return core.yield() end function socket.read(fd, n) local s = socket_pool[fd] assert(s) local r = ns.read(nb_pool, s.sbuffer, n) if r then return r end s.delim = n local ok = suspend(s) if ok == false then --occurs error return nil end local r = ns.read(nb_pool, s.sbuffer, n) assert(r) return r; end function socket.readline(fd, delim) delim = delim or "\n" local s = socket_pool[fd] assert(s) local r = ns.readline(nb_pool, s.sbuffer, delim) if r then return r end s.delim = delim local ok = suspend(s) if ok == false then --occurs error return nil end local r = ns.readline(nb_pool, s.sbuffer, delim) assert(r) return r end function socket.write(fd, str) local p, sz = ns.pack(str) core.write(fd, p, sz) end return socket
bug fix: wrong gc set when nb_pool's gc called before socket_pool[fd]'s gc, it will crash
bug fix: wrong gc set when nb_pool's gc called before socket_pool[fd]'s gc, it will crash
Lua
mit
findstr/silly