repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
D3vMa3sTrO/superbot
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-2.0
masterteam1/Master-plus
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
nightrune/wireshark
test/lua/tvb.lua
32
30608
---------------------------------------- -- script-name: tvb.lua -- This tests the Tvb/TvbRange and proto_add_XXX_item API. ---------------------------------------- ------------- general test helper funcs ------------ local FRAME = "frame" local OTHER = "other" local total_tests = 0 local function getTotal() return total_tests end local packet_counts = {} local function incPktCount(name) if not packet_counts[name] then packet_counts[name] = 1 else packet_counts[name] = packet_counts[name] + 1 end end local function getPktCount(name) return packet_counts[name] or 0 end local passed = {} local function setPassed(name) if not passed[name] then passed[name] = 1 else passed[name] = passed[name] + 1 end total_tests = total_tests + 1 end local fail_count = 0 local function setFailed(name) fail_count = fail_count + 1 total_tests = total_tests + 1 end -- expected number of runs per type -- -- CHANGE THIS TO MATCH HOW MANY TESTS THERE ARE -- local taptests = { [FRAME]=4, [OTHER]=312 } local function getResults() print("\n-----------------------------\n") for k,v in pairs(taptests) do -- each frame run executes the same test again, so multiply by #frames if k ~= "frame" and v ~= 0 then v = (v * taptests.frame) end if v ~= 0 and passed[k] ~= v then print("Something didn't run or ran too much... tests failed!") print("Dissector type " .. k .. " expected: " .. v .. " (" .. ( v / taptests.frame) .. ")" .. ", but got: " .. tostring(passed[k]) .. " (" .. (tonumber(passed[k] or 0) / taptests.frame) .. ")" ) return false end end print("All tests passed!\n\n") return true end local function testing(type,...) print("\n-------- Testing " .. tostring(...) .. " ---- for packet # " .. getPktCount(type) .. " --------\n") end local function execute(type,name, ...) io.stdout:write("test --> "..name.."-"..getTotal().."-"..getPktCount(type).."...") local results = { ... } if #results > 0 and results[1] == true then setPassed(type) io.stdout:write("passed\n") return true else setFailed(type) io.stdout:write("failed!\n") if #results > 1 then print("Got the following error: '" .. tostring(results[2]) .. "'") end error(name.." test failed!") end end --------- -- the following are so we can use pcall (which needs a function to call) local function callFunc(func,...) func(...) end local function callObjFuncGetter(vart,varn,tobj,name,...) vart[varn] = tobj[name](...) end local function setValue(tobj,name,value) tobj[name] = value end local function getValue(tobj,name) local foo = tobj[name] end ------------- test script ------------ ---------------------------------- -- modify original test function for now, kinda sorta local orig_execute = execute execute = function (...) return orig_execute(OTHER,...) end ---------------------------------------- -- creates a Proto object for our testing local test_proto = Proto("test","Test Protocol") local numinits = 0 function test_proto.init() numinits = numinits + 1 if numinits == 2 then getResults() end end ---------------------------------------- -- a table of all of our Protocol's fields local testfield = { basic = { STRING = ProtoField.string ("test.basic.string", "Basic string"), BOOLEAN = ProtoField.bool ("test.basic.boolean", "Basic boolean", 16, {"yes","no"}, 0x0001), UINT16 = ProtoField.uint16 ("test.basic.uint16", "Basic uint16"), BYTES = ProtoField.bytes ("test.basic.bytes", "Basic Bytes"), UINT_BYTES = ProtoField.ubytes ("test.basic.ubytes", "Basic Uint Bytes"), OID = ProtoField.oid ("test.basic.oid", "Basic OID"), REL_OID = ProtoField.rel_oid("test.basic.rel_oid", "Basic Relative OID"), ABSOLUTE_LOCAL = ProtoField.absolute_time("test.basic.absolute.local","Basic absolute local"), ABSOLUTE_UTC = ProtoField.absolute_time("test.basic.absolute.utc", "Basic absolute utc", 1001), -- GUID = ProtoField.guid ("test.basic.guid", "Basic GUID"), }, time = { ABSOLUTE_LOCAL = ProtoField.absolute_time("test.time.absolute.local","Time absolute local"), ABSOLUTE_UTC = ProtoField.absolute_time("test.time.absolute.utc", "Time absolute utc", 1001), }, bytes = { BYTES = ProtoField.bytes ("test.bytes.bytes", "Bytes"), UINT_BYTES = ProtoField.ubytes ("test.bytes.ubytes", "Uint Bytes"), OID = ProtoField.oid ("test.bytes.oid", "OID"), REL_OID = ProtoField.rel_oid("test.bytes.rel_oid", "Relative OID"), -- GUID = ProtoField.guid ("test.bytes.guid", "GUID"), }, } -- create a flat array table of the above that can be registered local pfields = {} for _,t in pairs(testfield) do for k,v in pairs(t) do pfields[#pfields+1] = v end end -- register them test_proto.fields = pfields print("test_proto ProtoFields registered") local getfield = { basic = { STRING = Field.new ("test.basic.string"), BOOLEAN = Field.new ("test.basic.boolean"), UINT16 = Field.new ("test.basic.uint16"), BYTES = Field.new ("test.basic.bytes"), UINT_BYTES = Field.new ("test.basic.ubytes"), OID = Field.new ("test.basic.oid"), REL_OID = Field.new ("test.basic.rel_oid"), ABSOLUTE_LOCAL = Field.new ("test.basic.absolute.local"), ABSOLUTE_UTC = Field.new ("test.basic.absolute.utc"), -- GUID = Field.new ("test.basic.guid"), }, time = { ABSOLUTE_LOCAL = Field.new ("test.time.absolute.local"), ABSOLUTE_UTC = Field.new ("test.time.absolute.utc"), }, bytes = { BYTES = Field.new ("test.bytes.bytes"), UINT_BYTES = Field.new ("test.bytes.ubytes"), OID = Field.new ("test.bytes.oid"), REL_OID = Field.new ("test.bytes.rel_oid"), -- GUID = Field.new ("test.bytes.guid"), }, } print("test_proto Fields created") local function addMatchFields(match_fields, ... ) match_fields[#match_fields + 1] = { ... } end local function getFieldInfos(name) local base, field = name:match("([^.]+)%.(.+)") if not base or not field then error("failed to get base.field from '" .. name .. "'") end local t = { getfield[base][field]() } return t end local function verifyFields(name, match_fields) local finfos = getFieldInfos(name) execute ("verify-fields-size-" .. name, #finfos == #match_fields, "#finfos=" .. #finfos .. ", #match_fields=" .. #match_fields) for i, t in ipairs(match_fields) do if type(t) ~= 'table' then error("verifyFields didn't get a table inside the matches table") end if #t ~= 1 then error("verifyFields matches table's table is not size 1") end local result = finfos[i]() local value = t[1] print( name .. " got:", "\n\tfinfos [" .. i .. "]='" .. tostring( result ) .. "'", "\n\tmatches[" .. i .. "]='" .. tostring( value ) .. "'" ) execute ( "verify-fields-value-" .. name .. "-" .. i, result == value ) end end local function addMatchValues(match_values, ... ) match_values[#match_values + 1] = { ... } end local function addMatchFieldValues(match_fields, match_values, match_both, ...) addMatchFields(match_fields, match_both) addMatchValues(match_values, match_both, ...) end local result_values = {} local function resetResults() result_values = {} end local function treeAddPField(...) local t = { pcall ( TreeItem.add_packet_field, ... ) } if t[1] == nil then return nil, t[2] end -- it gives back a TreeItem, then the results if typeof(t[2]) ~= 'TreeItem' then return nil, "did not get a TreeItem returned from TreeItem.add_packet_field, ".. "got a '" .. typeof(t[2]) .."'" end if #t ~= 4 then return nil, "did not get 3 return values from TreeItem.add_packet_field" end result_values[#result_values + 1] = { t[3], t[4] } return true end local function verifyResults(name, match_values) execute ("verify-results-size-" .. name, #result_values == #match_values, "#result_values=" .. #result_values .. ", #match_values=" .. #match_values) for j, t in ipairs(match_values) do if type(t) ~= 'table' then error("verifyResults didn't get a table inside the matches table") end for i, match in ipairs(t) do local r = result_values[j][i] print( name .. " got:", "\n\tresults[" .. j .. "][" .. i .. "]='" .. tostring( r ) .. "'", "\n\tmatches[" .. j .. "][" .. i .. "]='" .. tostring( match ) .. "'" ) local result_type, match_type if type(match) == 'userdata' then match_type = typeof(match) else match_type = type(match) end if type(r) == 'userdata' then result_type = typeof(r) else result_type = type(r) end execute ( "verify-results-type-" .. name .. "-" .. i, result_type == match_type ) execute ( "verify-results-value-" .. name .. "-" .. i, r == match ) end end end -- Compute the difference in seconds between local time and UTC -- from http://lua-users.org/wiki/TimeZone local function get_timezone() local now = os.time() return os.difftime(now, os.time(os.date("!*t", now))) end local timezone = get_timezone() print ("timezone = " .. timezone) ---------------------------------------- -- The following creates the callback function for the dissector. -- The 'tvbuf' is a Tvb object, 'pktinfo' is a Pinfo object, and 'root' is a TreeItem object. function test_proto.dissector(tvbuf,pktinfo,root) incPktCount(FRAME) incPktCount(OTHER) testing(OTHER, "Basic string") local tree = root:add(test_proto, tvbuf:range(0,tvbuf:len())) -- create a fake Tvb to use for testing local teststring = "this is the string for the first test" local bytearray = ByteArray.new(teststring, true) local tvb_string = bytearray:tvb("Basic string") local function callTreeAdd(tree,...) tree:add(...) end local string_match_fields = {} execute ("basic-tvb_get_string", tvb_string:range():string() == teststring ) execute ("basic-string", tree:add(testfield.basic.STRING, tvb_string:range(0,tvb_string:len())) ~= nil ) addMatchFields(string_match_fields, teststring) execute ("basic-string", pcall (callTreeAdd, tree, testfield.basic.STRING, tvb_string:range() ) ) addMatchFields(string_match_fields, teststring) verifyFields("basic.STRING", string_match_fields) ---------------------------------------- testing(OTHER, "Basic boolean") local barray_bytes_hex = "00FF00018000" local barray_bytes = ByteArray.new(barray_bytes_hex) local tvb_bytes = barray_bytes:tvb("Basic bytes") local bool_match_fields = {} execute ("basic-boolean", pcall (callTreeAdd, tree, testfield.basic.BOOLEAN, tvb_bytes:range(0,2)) ) addMatchFields(bool_match_fields, true) execute ("basic-boolean", pcall (callTreeAdd, tree, testfield.basic.BOOLEAN, tvb_bytes:range(2,2)) ) addMatchFields(bool_match_fields, true) execute ("basic-boolean", pcall (callTreeAdd, tree, testfield.basic.BOOLEAN, tvb_bytes:range(4,2)) ) addMatchFields(bool_match_fields, false) verifyFields("basic.BOOLEAN", bool_match_fields ) ---------------------------------------- testing(OTHER, "Basic uint16") local uint16_match_fields = {} execute ("basic-uint16", pcall (callTreeAdd, tree, testfield.basic.UINT16, tvb_bytes:range(0,2)) ) addMatchFields(uint16_match_fields, 255) execute ("basic-uint16", pcall (callTreeAdd, tree, testfield.basic.UINT16, tvb_bytes:range(2,2)) ) addMatchFields(uint16_match_fields, 1) execute ("basic-uint16", pcall (callTreeAdd, tree, testfield.basic.UINT16, tvb_bytes:range(4,2)) ) addMatchFields(uint16_match_fields, 32768) verifyFields("basic.UINT16", uint16_match_fields) ---------------------------------------- testing(OTHER, "Basic uint16-le") local function callTreeAddLE(tree,...) tree:add_le(...) end execute ("basic-uint16-le", pcall (callTreeAddLE, tree, testfield.basic.UINT16, tvb_bytes:range(0,2)) ) addMatchFields(uint16_match_fields, 65280) execute ("basic-uint16-le", pcall (callTreeAddLE, tree, testfield.basic.UINT16, tvb_bytes:range(2,2)) ) addMatchFields(uint16_match_fields, 256) execute ("basic-uint16-le", pcall (callTreeAddLE, tree, testfield.basic.UINT16, tvb_bytes:range(4,2)) ) addMatchFields(uint16_match_fields, 128) verifyFields("basic.UINT16", uint16_match_fields) ---------------------------------------- testing(OTHER, "Basic bytes") local bytes_match_fields = {} execute ("basic-tvb_get_string_bytes", string.lower(tostring(tvb_bytes:range():bytes())) == string.lower(barray_bytes_hex)) execute ("basic-bytes", pcall (callTreeAdd, tree, testfield.basic.BYTES, tvb_bytes:range()) ) addMatchFields(bytes_match_fields, barray_bytes) -- TODO: it's silly that tree:add_packet_field() requires an encoding argument -- need to fix that separately in a bug fix execute ("add_pfield-bytes", treeAddPField(tree, testfield.basic.BYTES, tvb_bytes:range(), ENC_BIG_ENDIAN)) addMatchFields(bytes_match_fields, barray_bytes) verifyFields("basic.BYTES", bytes_match_fields) ---------------------------------------- testing(OTHER, "Basic uint bytes") local len_string = string.format("%02x", barray_bytes:len()) local barray_uint_bytes = ByteArray.new(len_string) .. barray_bytes local tvb_uint_bytes = barray_uint_bytes:tvb("Basic UINT_BYTES") local uint_bytes_match_fields = {} execute ("basic-uint-bytes", pcall (callTreeAdd, tree, testfield.basic.UINT_BYTES, tvb_uint_bytes:range(0,1)) ) addMatchFields(uint_bytes_match_fields, barray_bytes) execute ("add_pfield-uint-bytes", treeAddPField(tree, testfield.basic.UINT_BYTES, tvb_uint_bytes:range(0,1), ENC_BIG_ENDIAN) ) addMatchFields(uint_bytes_match_fields, barray_bytes) verifyFields("basic.UINT_BYTES", uint_bytes_match_fields) ---------------------------------------- testing(OTHER, "Basic OID") -- note: the tvb being dissected and compared isn't actually a valid OID. -- tree:add() and tree:add_packet-field() don't care about its validity right now. local oid_match_fields = {} execute ("basic-oid", pcall(callTreeAdd, tree, testfield.basic.OID, tvb_bytes:range()) ) addMatchFields(oid_match_fields, barray_bytes) execute ("add_pfield-oid", treeAddPField(tree, testfield.basic.OID, tvb_bytes:range(), ENC_BIG_ENDIAN) ) addMatchFields(oid_match_fields, barray_bytes) verifyFields("basic.OID", oid_match_fields) ---------------------------------------- testing(OTHER, "Basic REL_OID") -- note: the tvb being dissected and compared isn't actually a valid OID. -- tree:add() and tree:add_packet-field() don't care about its validity right now. local rel_oid_match_fields = {} execute ("basic-rel-oid", pcall(callTreeAdd, tree, testfield.basic.REL_OID, tvb_bytes:range())) addMatchFields(rel_oid_match_fields, barray_bytes) execute ("add_pfield-rel_oid", treeAddPField(tree, testfield.basic.REL_OID, tvb_bytes:range(), ENC_BIG_ENDIAN) ) addMatchFields(rel_oid_match_fields, barray_bytes) verifyFields("basic.REL_OID", rel_oid_match_fields) -- TODO: a FT_GUID is not really a ByteArray, so we can't simply treat it as one -- local barray_guid = ByteArray.new("00FF0001 80001234 567890AB CDEF00FF") -- local tvb_guid = barray_guid:tvb("Basic GUID") -- local guid_match_fields = {} -- execute ("basic-guid", pcall(callTreeAdd, tree, testfield.basic.GUID, tvb_guid:range()) ) -- addMatchFields(guid_match_fields, barray_guid) -- execute ("add_pfield-guid", treeAddPField(tree, testfield.basic.GUID, -- tvb_guid:range(), ENC_BIG_ENDIAN) ) -- addMatchFields(guid_match_fields, barray_guid) -- verifyFields("basic.GUID", guid_match_fields) ---------------------------------------- testing(OTHER, "tree:add_packet_field Bytes") resetResults() bytes_match_fields = {} local bytes_match_values = {} -- something to make this easier to read local function addMatch(...) addMatchFieldValues(bytes_match_fields, bytes_match_values, ...) end local bytesstring1 = "deadbeef0123456789DEADBEEFabcdef" local bytesstring = ByteArray.new(bytesstring1) -- the binary version of above, for comparing local bytestvb1 = ByteArray.new(bytesstring1, true):tvb("Bytes hex-string 1") local bytesstring2 = " de:ad:be:ef:01:23:45:67:89:DE:AD:BE:EF:ab:cd:ef" local bytestvb2 = ByteArray.new(bytesstring2 .. "-f0-00 foobar", true):tvb("Bytes hex-string 2") local bytestvb1_decode = bytestvb1:range():bytes(ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH) execute ("tvb_get_string_bytes", string.lower(tostring(bytestvb1_decode)) == string.lower(tostring(bytesstring1))) execute ("add_pfield-bytes1", treeAddPField(tree, testfield.bytes.BYTES, bytestvb1:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring1)) execute ("add_pfield-bytes2", treeAddPField(tree, testfield.bytes.BYTES, bytestvb2:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring2)) verifyResults("add_pfield-bytes", bytes_match_values) verifyFields("bytes.BYTES", bytes_match_fields) ---------------------------------------- testing(OTHER, "tree:add_packet_field OID") resetResults() bytes_match_fields = {} bytes_match_values = {} execute ("add_pfield-oid1", treeAddPField(tree, testfield.bytes.OID, bytestvb1:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring1)) execute ("add_pfield-oid2", treeAddPField(tree, testfield.bytes.OID, bytestvb2:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring2)) verifyResults("add_pfield-oid", bytes_match_values) verifyFields("bytes.OID", bytes_match_fields) ---------------------------------------- testing(OTHER, "tree:add_packet_field REL_OID") resetResults() bytes_match_fields = {} bytes_match_values = {} execute ("add_pfield-rel_oid1", treeAddPField(tree, testfield.bytes.REL_OID, bytestvb1:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring1)) execute ("add_pfield-rel_oid2", treeAddPField(tree, testfield.bytes.REL_OID, bytestvb2:range(), ENC_STR_HEX + ENC_SEP_NONE + ENC_SEP_COLON + ENC_SEP_DASH)) addMatch(bytesstring, string.len(bytesstring2)) verifyResults("add_pfield-rel_oid", bytes_match_values) verifyFields("bytes.REL_OID", bytes_match_fields) ---------------------------------------- testing(OTHER, "tree:add Time") local tvb = ByteArray.new("00000000 00000000 0000FF0F 00FF000F"):tvb("Time") local ALOCAL = testfield.time.ABSOLUTE_LOCAL local alocal_match_fields = {} execute ("time-local", pcall (callTreeAdd, tree, ALOCAL, tvb:range(0,8)) ) addMatchFields(alocal_match_fields, NSTime()) execute ("time-local", pcall (callTreeAdd, tree, ALOCAL, tvb:range(8,8)) ) addMatchFields(alocal_match_fields, NSTime( 0x0000FF0F, 0x00FF000F) ) execute ("time-local-le", pcall (callTreeAddLE, tree, ALOCAL, tvb:range(0,8)) ) addMatchFields(alocal_match_fields, NSTime()) execute ("time-local-le", pcall (callTreeAddLE, tree, ALOCAL, tvb:range(8,8)) ) addMatchFields(alocal_match_fields, NSTime( 0x0FFF0000, 0x0F00FF00 ) ) verifyFields("time.ABSOLUTE_LOCAL", alocal_match_fields) local AUTC = testfield.time.ABSOLUTE_UTC local autc_match_fields = {} execute ("time-utc", pcall (callTreeAdd, tree, AUTC, tvb:range(0,8)) ) addMatchFields(autc_match_fields, NSTime()) execute ("time-utc", pcall (callTreeAdd, tree, AUTC, tvb:range(8,8)) ) addMatchFields(autc_match_fields, NSTime( 0x0000FF0F, 0x00FF000F) ) execute ("time-utc-le", pcall (callTreeAddLE, tree, AUTC, tvb:range(0,8)) ) addMatchFields(autc_match_fields, NSTime()) execute ("time-utc-le", pcall (callTreeAddLE, tree, AUTC, tvb:range(8,8)) ) addMatchFields(autc_match_fields, NSTime( 0x0FFF0000, 0x0F00FF00 ) ) verifyFields("time.ABSOLUTE_UTC", autc_match_fields ) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time bytes") resetResults() local autc_match_values = {} -- something to make this easier to read addMatch = function(...) addMatchFieldValues(autc_match_fields, autc_match_values, ...) end -- tree:add_packet_field(ALOCAL, tvb:range(0,8), ENC_BIG_ENDIAN) execute ("add_pfield-time-bytes-local", treeAddPField ( tree, AUTC, tvb:range(0,8), ENC_BIG_ENDIAN) ) addMatch( NSTime(), 8) execute ("add_pfield-time-bytes-local", treeAddPField ( tree, AUTC, tvb:range(8,8), ENC_BIG_ENDIAN) ) addMatch( NSTime( 0x0000FF0F, 0x00FF000F), 8) execute ("add_pfield-time-bytes-local-le", treeAddPField ( tree, AUTC, tvb:range(0,8), ENC_LITTLE_ENDIAN) ) addMatch( NSTime(), 8) execute ("add_pfield-time-bytes-local-le", treeAddPField ( tree, AUTC, tvb:range(8,8), ENC_LITTLE_ENDIAN) ) addMatch( NSTime( 0x0FFF0000, 0x0F00FF00 ), 8) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-time-bytes-local", autc_match_values) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time string ENC_ISO_8601_DATE_TIME") resetResults() autc_match_values = {} local datetimestring1 = "2013-03-01T22:14:48+00:00" -- this is 1362176088 seconds epoch time local tvb1 = ByteArray.new(datetimestring1, true):tvb("Date_Time string 1") local datetimestring2 = " 2013-03-01T17:14:48+05:00" -- this is 1362176088 seconds epoch time local tvb2 = ByteArray.new(datetimestring2 .. " foobar", true):tvb("Date_Time string 2") local datetimestring3 = " 2013-03-01T16:44+05:30" -- this is 1362176040 seconds epoch time local tvb3 = ByteArray.new(datetimestring3, true):tvb("Date_Time string 3") local datetimestring4 = "2013-03-02T01:44:00-03:30" -- this is 1362176040 seconds epoch time local tvb4 = ByteArray.new(datetimestring4, true):tvb("Date_Time string 4") local datetimestring5 = "2013-03-01T22:14:48Z" -- this is 1362176088 seconds epoch time local tvb5 = ByteArray.new(datetimestring5, true):tvb("Date_Time string 5") local datetimestring6 = "2013-03-01T22:14Z" -- this is 1362176040 seconds epoch time local tvb6 = ByteArray.new(datetimestring6, true):tvb("Date_Time string 6") execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb1:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176088, 0), string.len(datetimestring1)) execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb2:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176088, 0), string.len(datetimestring2)) execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb3:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176040, 0), string.len(datetimestring3)) execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb4:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176040, 0), string.len(datetimestring4)) execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb5:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176088, 0), string.len(datetimestring5)) execute ("add_pfield-datetime-local", treeAddPField ( tree, AUTC, tvb6:range(), ENC_ISO_8601_DATE_TIME) ) addMatch( NSTime( 1362176040, 0), string.len(datetimestring6)) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-datetime-local", autc_match_values) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time string ENC_ISO_8601_DATE") resetResults() autc_match_values = {} local datestring1 = "2013-03-01" -- this is 1362096000 seconds epoch time local d_tvb1 = ByteArray.new(datestring1, true):tvb("Date string 1") local datestring2 = " 2013-03-01" -- this is 1362096000 seconds epoch time local d_tvb2 = ByteArray.new(datestring2 .. " foobar", true):tvb("Date string 2") execute ("add_pfield-date-local", treeAddPField ( tree, AUTC, d_tvb1:range(), ENC_ISO_8601_DATE) ) addMatch( NSTime( 1362096000, 0), string.len(datestring1)) execute ("add_pfield-date-local", treeAddPField ( tree, AUTC, d_tvb2:range(), ENC_ISO_8601_DATE) ) addMatch( NSTime( 1362096000, 0), string.len(datestring2)) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-date-local", autc_match_values) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time string ENC_ISO_8601_TIME") resetResults() autc_match_values = {} local timestring1 = "22:14:48" -- this is 80088 seconds local t_tvb1 = ByteArray.new(timestring1, true):tvb("Time string 1") local timestring2 = " 22:14:48" -- this is 80088 seconds local t_tvb2 = ByteArray.new(timestring2 .. " foobar", true):tvb("Time string 2") local now = os.date("!*t") now.hour = 22 now.min = 14 now.sec = 48 local timebase = os.time( now ) timebase = timebase + timezone print ("timebase = " .. tostring(timebase) .. ", timezone=" .. timezone) execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, t_tvb1:range(), ENC_ISO_8601_TIME) ) addMatch( NSTime( timebase, 0), string.len(timestring1)) execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, t_tvb2:range(), ENC_ISO_8601_TIME) ) addMatch( NSTime( timebase, 0), string.len(timestring2)) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-time-local", autc_match_values) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time string ENC_RFC_822") resetResults() autc_match_values = {} local rfc822string1 = "Fri, 01 Mar 13 22:14:48 GMT" -- this is 1362176088 seconds epoch time local rfc822_tvb1 = ByteArray.new(rfc822string1, true):tvb("RFC 822 Time string 1") local rfc822string2 = " Fri, 01 Mar 13 22:14:48 GMT" -- this is 1362176088 seconds epoch time local rfc822_tvb2 = ByteArray.new(rfc822string2 .. " foobar", true):tvb("RFC 822 Time string 2") execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, rfc822_tvb1:range(), ENC_RFC_822) ) addMatch( NSTime( 1362176088, 0), string.len(rfc822string1)) execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, rfc822_tvb2:range(), ENC_RFC_822) ) addMatch( NSTime( 1362176088, 0), string.len(rfc822string2)) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-rfc822-local", autc_match_values) ---------------------------------------- testing(OTHER, "tree:add_packet_field Time string ENC_RFC_1123") resetResults() autc_match_values = {} local rfc1123string1 = "Fri, 01 Mar 2013 22:14:48 GMT" -- this is 1362176088 seconds epoch time local rfc1123_tvb1 = ByteArray.new(rfc1123string1, true):tvb("RFC 1123 Time string 1") local rfc1123string2 = " Fri, 01 Mar 2013 22:14:48 GMT" -- this is 1362176088 seconds epoch time local rfc1123_tvb2 = ByteArray.new(rfc1123string2 .. " foobar", true):tvb("RFC 1123 Time string 2") execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, rfc1123_tvb1:range(), ENC_RFC_1123) ) addMatch( NSTime( 1362176088, 0), string.len(rfc1123string1)) execute ("add_pfield-time-local", treeAddPField ( tree, AUTC, rfc1123_tvb2:range(), ENC_RFC_1123) ) addMatch( NSTime( 1362176088, 0), string.len(rfc1123string2)) verifyFields("time.ABSOLUTE_UTC", autc_match_fields) verifyResults("add_pfield-rfc1123-local", autc_match_values) ---------------------------------------- setPassed(FRAME) end ---------------------------------------- -- we want to have our protocol dissection invoked for a specific UDP port, -- so get the udp dissector table and add our protocol to it DissectorTable.get("udp.port"):add(65333, test_proto) DissectorTable.get("udp.port"):add(65346, test_proto) print("test_proto dissector registered")
gpl-2.0
deepakjois/ufy
src/ufy/init.lua
1
2114
local path = require("path") local ufy = {} -- Cache ufy’s config directory location. local ufy_config_dir -- Location of standalone LuaTeX binary in a regular -- installation of ufy. local luatex_program = "luatex" -- Locate ufy’s config directory. function ufy.locate_config() local datafile = require("datafile") local luarocks_opener = require("datafile.openers.luarocks") -- Try LuaRocks opener datafile.openers = { luarocks_opener } ufy_config_dir = datafile.path("config") if ufy_config_dir == nil then print("Could not locate config. Aborting…") os.exit(1) end end -- Return ufy’s config directory. function ufy.config_dir() if ufy_config_dir == nil then ufy.locate_config() end return ufy_config_dir end -- Run the ufy program. -- -- Setup and invoke the LuaTeX interpreter with a Lua file. function ufy.run(args) -- Locate pre-init file local pre_init_file = path.join(ufy.config_dir(), "ufy_pre_init.lua") -- Extract basename without extension for jobname local jobname, _ = path.splitext(path.basename(args[1])) local command_args = { luatex_program, -- LuaTeX binary "--shell-escape", -- Allows io.popen in Lua init script: see http://tug.org/pipermail/luatex/2016-October/006249.html "--lua=" .. pre_init_file, -- Pre-init file "--jobname=" .. jobname, -- Set jobname from filname "--ini", -- IniTeX mode, no format file -- minimal wrapper for executing a Lua file "'\\catcode`\\{=1'", "'\\catcode`\\}=2'", "'\\directlua{ufy.init()}'", string.format("'\\directlua{dofile(\"%s\")}'", args[1]), "'\\end'" } local command = table.concat(command_args, " ") print(string.format("\n%s\n", command)) local _, _, code = os.execute(command) os.exit(code) end function ufy.pre_init() texconfig.shell_escape = 't' end function ufy.init() tex.enableprimitives('',tex.extraprimitives()) ufy.loader.add_lua_searchers() tex.outputmode = 1 pdf.mapfile(nil) pdf.mapline('') end ufy.locate_config() ufy.loader = require("ufy.loader") return ufy
mit
dianedelallee/Blinn-Phong
premake4.lua
1
3275
solution "advanced_opengl_imac3_exercises" configurations { "Debug", "Release" } platforms {"native", "x64", "x32"} -- src Exercicse Deferred project "SyntheseImage" kind "ConsoleApp" language "C++" files { "src/main.cpp", "common/*.hpp", "common/*.cpp", "common/*.h" } includedirs { "lib/glfw/include", "src", "common", "lib/" } links {"glfw", "glew", "stb_image"} defines { "GLEW_STATIC" } configuration { "linux" } links {"X11","Xrandr", "rt", "GL", "GLU", "pthread"} configuration { "windows" } links {"glu32","opengl32", "gdi32", "winmm", "user32"} configuration { "macosx" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir "bin/debug/src/" configuration "Release" defines { "NDEBUG" } flags { "Optimize"} targetdir "bin/release/src/" -- GLFW Library project "glfw" kind "StaticLib" language "C" files { "lib/glfw/lib/*.h", "lib/glfw/lib/*.c", "lib/glfw/include/GL/glfw.h" } includedirs { "lib/glfw/lib", "lib/glfw/include"} configuration {"linux"} files { "lib/glfw/lib/x11/*.c", "lib/glfw/x11/*.h" } includedirs { "lib/glfw/lib/x11" } defines { "_GLFW_USE_LINUX_JOYSTICKS", "_GLFW_HAS_XRANDR", "_GLFW_HAS_PTHREAD" ,"_GLFW_HAS_SCHED_YIELD", "_GLFW_HAS_GLXGETPROCADDRESS" } buildoptions { "-pthread" } configuration {"windows"} files { "lib/glfw/lib/win32/*.c", "lib/glfw/win32/*.h" } includedirs { "lib/glfw/lib/win32" } defines { "_GLFW_USE_LINUX_JOYSTICKS", "_GLFW_HAS_XRANDR", "_GLFW_HAS_PTHREAD" ,"_GLFW_HAS_SCHED_YIELD", "_GLFW_HAS_GLXGETPROCADDRESS" } configuration {"Macosx"} files { "lib/glfw/lib/cocoa/*.c", "lib/glfw/lib/cocoa/*.h", "lib/glfw/lib/cocoa/*.m" } includedirs { "lib/glfw/lib/cocoa" } defines { } buildoptions { " -fno-common" } linkoptions { "-framework OpenGL", "-framework Cocoa", "-framework IOKit" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir "bin/debug" configuration "Release" defines { "NDEBUG" } flags { "Optimize" } targetdir "bin/release" -- GLEW Library project "glew" kind "StaticLib" language "C" files {"lib/glew/*.c", "lib/glew/*.h"} defines { "GLEW_STATIC" } configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir "bin/debug" configuration "Release" defines { "NDEBUG" } flags { "Optimize" } targetdir "bin/release" -- stb_image Library project "stb_image" kind "StaticLib" language "C" files {"lib/stb_image/*.c", "lib/stb_image/*.h"} configuration "Debug" defines { "DEBUG" } flags { "Symbols" } targetdir "bin/debug" configuration "Release" defines { "NDEBUG" } flags { "Optimize" } targetdir "bin/release"
cc0-1.0
DavidIngraham/ardupilot
libraries/AP_Scripting/examples/Aerobatics/Via_Switch/10_loops-and-immelman.lua
4
11279
-- loops and returns on switch TRICK_NUMBER = 10 -- selector number recognized to execute trick, change as desired -- number of loops controlled by AERO_RPT_COUNT, if 0 it will do an immelman instead, trick returns control after executing even if trick id remains 10 local target_vel -- trick specific global variables local loop_stage ------------------------------------------------------------------- -- do not change anything unless noted local running = false local not_bound = true local initial_yaw_deg = 0 local initial_height = 0 local repeat_count -- constrain a value between limits function constrain(v, vmin, vmax) if v < vmin then v = vmin end if v > vmax then v = vmax end return v end function wrap_360(angle) --function returns positive angle modulo360, -710 in returns 10, -10 returns +350 local res = math.fmod(angle, 360.0) if res < 0 then res = res + 360.0 end return res end function wrap_180(angle) local res = wrap_360(angle) if res > 180 then res = res - 360 end return res end -- roll angle error 180 wrap to cope with errors while in inverted segments function roll_angle_error_wrap(roll_angle_error) if math.abs(roll_angle_error) > 180 then if roll_angle_error > 0 then roll_angle_error = roll_angle_error - 360 else roll_angle_error= roll_angle_error +360 end end return roll_angle_error end --roll controller to keep wings level in earth frame. if arg is 0 then level is at only 0 deg, otherwise its at 180/-180 roll also for loops function earth_frame_wings_level(arg) local roll_deg = math.deg(ahrs:get_roll()) local roll_angle_error = 0.0 if (roll_deg > 90 or roll_deg < -90) and arg ~= 0 then roll_angle_error = 180 - roll_deg else roll_angle_error = - roll_deg end return roll_angle_error_wrap(roll_angle_error)/(RLL2SRV_TCONST:get()) end -- constrain rates to rate controller call function _set_target_throttle_rate_rpy(throttle,roll_rate, pitch_rate, yaw_rate) local r_rate = constrain(roll_rate,-RATE_MAX:get(),RATE_MAX:get()) local p_rate = constrain(pitch_rate,-RATE_MAX:get(),RATE_MAX:get()) vehicle:set_target_throttle_rate_rpy(throttle, r_rate, p_rate, yaw_rate) end -- a PI controller implemented as a Lua object local function PI_controller(kP,kI,iMax) -- the new instance. You can put public variables inside this self -- declaration if you want to local self = {} -- private fields as locals local _kP = kP or 0.0 local _kI = kI or 0.0 local _kD = kD or 0.0 local _iMax = iMax local _last_t = nil local _I = 0 local _P = 0 local _total = 0 local _counter = 0 local _target = 0 local _current = 0 -- update the controller. function self.update(target, current) local now = millis():tofloat() * 0.001 if not _last_t then _last_t = now end local dt = now - _last_t _last_t = now local err = target - current _counter = _counter + 1 local P = _kP * err _I = _I + _kI * err * dt if _iMax then _I = constrain(_I, -_iMax, iMax) end local I = _I local ret = P + I _target = target _current = current _P = P _total = ret return ret end -- reset integrator to an initial value function self.reset(integrator) _I = integrator end function self.set_I(I) _kI = I end function self.set_P(P) _kP = P end function self.set_Imax(Imax) _iMax = Imax end -- log the controller internals function self.log(name, add_total) -- allow for an external addition to total logger:write(name,'Targ,Curr,P,I,Total,Add','ffffff',_target,_current,_P,_I,_total,add_total) end -- return the instance return self end local function height_controller(kP_param,kI_param,KnifeEdge_param,Imax) local self = {} local kP = kP_param local kI = kI_param local KnifeEdge = KnifeEdge_param local PI = PI_controller(kP:get(), kI:get(), Imax) function self.update(target) local target_pitch = PI.update(initial_height, ahrs:get_position():alt()*0.01) local roll_rad = ahrs:get_roll() local ke_add = math.abs(math.sin(roll_rad)) * KnifeEdge:get() target_pitch = target_pitch + ke_add PI.log("HPI", ke_add) return constrain(target_pitch,-45,45) end function self.reset() PI.reset(math.max(math.deg(ahrs:get_pitch()), 3.0)) PI.set_P(kP:get()) PI.set_I(kI:get()) end return self end -- a controller to target a zero pitch angle and zero heading change, used in a roll -- output is a body frame pitch rate, with convergence over time tconst in seconds function pitch_controller(target_pitch_deg, target_yaw_deg, tconst) local roll_deg = math.deg(ahrs:get_roll()) local pitch_deg = math.deg(ahrs:get_pitch()) local yaw_deg = math.deg(ahrs:get_yaw()) -- get earth frame pitch and yaw rates local ef_pitch_rate = (target_pitch_deg - pitch_deg) / tconst local ef_yaw_rate = wrap_180(target_yaw_deg - yaw_deg) / tconst local bf_pitch_rate = math.sin(math.rad(roll_deg)) * ef_yaw_rate + math.cos(math.rad(roll_deg)) * ef_pitch_rate local bf_yaw_rate = math.cos(math.rad(roll_deg)) * ef_yaw_rate - math.sin(math.rad(roll_deg)) * ef_pitch_rate return bf_pitch_rate, bf_yaw_rate end -- a controller for throttle to account for pitch function throttle_controller() local pitch_rad = ahrs:get_pitch() local thr_ff = THR_PIT_FF:get() local throttle = TRIM_THROTTLE:get() + math.sin(pitch_rad) * thr_ff return constrain(throttle, TRIM_THROTTLE:get(), 100.0) end function bind_param(name) local p = Parameter() if p:init(name) then not_bound = false return p else not_bound = true end end -- recover entry altitude function recover_alt() local target_pitch = height_PI.update(initial_height) local pitch_rate, yaw_rate = pitch_controller(target_pitch, initial_yaw_deg, PITCH_TCONST:get()) throttle = throttle_controller() return throttle, pitch_rate, yaw_rate end ---------------------------------------------------------------------------------------------- --every trick needs an init, change as needed...to bind the AERO params it uses(which will depend on the trick), and setup PID controllers used by script function init() HGT_P = bind_param("AERO_HGT_P") -- height P gain, required for height controller HGT_I = bind_param("AERO_HGT_I") -- height I gain, required for height controller HGT_KE_BIAS = bind_param("AERO_HGT_KE_BIAS") -- height knifeedge addition for pitch THR_PIT_FF = bind_param("AERO_THR_PIT_FF") -- throttle FF from pitch TRIM_THROTTLE = bind_param("TRIM_THROTTLE") --usually required for any trick TRIM_ARSPD_CM = bind_param("TRIM_ARSPD_CM") --usually required for any trick RATE_MAX = bind_param("AERO_RATE_MAX") RLL2SRV_TCONST = bind_param("RLL2SRV_TCONST") --usually required for any trick PITCH_TCONST = bind_param("PTCH2SRV_TCONST") --usually required for any trick TRICK_ID = bind_param("AERO_TRICK_ID") --- required for any trick TRICK_RAT = bind_param("AERO_TRICK_RAT") --usually required for any trick RPT_COUNT = bind_param("AERO_RPT_COUNT") --repeat count for trick if not_bound then gcs:send_text(0,string.format("Not bound yet")) return init, 100 else gcs:send_text(0,string.format("Params bound,Trick %.0f loaded", TRICK_NUMBER)) height_PI = height_controller(HGT_P, HGT_I, HGT_KE_BIAS, 20.0) -- this trick needs this height PID controller setup to hold height during the trick loop_stage = 0 return update, 50 end end ----------------------------------------------------------------------------------------------- --every trick will have its own do_trick function to perform the trick...this will change totally for each different trick function do_loop(arg1) -- do one loop with controllable pitch rate arg1 is pitch rate, arg2 number of loops, 0 indicates 1/2 cuban8 reversa local throttle = throttle_controller() local pitch_deg = math.deg(ahrs:get_pitch()) local roll_deg = math.deg(ahrs:get_roll()) local vel = ahrs:get_velocity_NED():length() local pitch_rate = arg1 local yaw_rate = 0 pitch_rate = pitch_rate * (1+ 2*((vel/target_vel)-1)) --increase/decrease rate based on velocity to round loop pitch_rate = constrain(pitch_rate,.5 * arg1, 3 * arg1) if loop_stage == 0 then if pitch_deg > 60 then loop_stage = 1 end elseif loop_stage == 1 then if (math.abs(roll_deg) < 90 and pitch_deg > -5 and pitch_deg < 5 and repeat_count > 0) then -- we're done with loop gcs:send_text(0, string.format("Finished loop p=%.1f", pitch_deg)) loop_stage = 2 --now recover stage repeat_count = repeat_count - 1 elseif (math.abs(roll_deg) > 90 and pitch_deg > -5 and pitch_deg < 5 and repeat_count <= 0) then gcs:send_text(0, string.format("Finished return p=%.1f", pitch_deg)) loop_stage = 2 --now recover stage repeat_count = repeat_count - 1 initial_yaw_deg = math.deg(ahrs:get_yaw()) end elseif loop_stage == 2 then -- recover alt if above or below start and terminate if repeat_count > 0 then --yaw_rate = 0 loop_stage = 0 elseif math.abs(ahrs:get_position():alt()*0.01 - initial_height) > 3 then throttle, pitch_rate, yaw_rate = recover_alt() else running = false gcs:send_text(0, string.format("Recovered entry alt")) TRICK_ID:set(0) return end end throttle = throttle_controller() if loop_stage == 2 or loop_stage == 0 then level_type = 0 else level_type = 1 end if math.abs(pitch_deg) > 85 and math.abs(pitch_deg) < 95 then roll_rate = 0 else roll_rate = earth_frame_wings_level(level_type) end _set_target_throttle_rate_rpy(throttle, roll_rate, pitch_rate, yaw_rate) end ------------------------------------------------------------------------------------------- --trick should noramlly only have to change the notification text in this routine,initialize trick specific variables, and any parameters needing to be passed to do_trick(..) function update() if (TRICK_ID:get() == TRICK_NUMBER) then local current_mode = vehicle:get_mode() if arming:is_armed() and running == false then if not vehicle:nav_scripting_enable(current_mode) then return update, 50 end running = true initial_height = ahrs:get_position():alt()*0.01 initial_yaw_deg = math.deg(ahrs:get_yaw()) height_PI.reset() repeat_count = RPT_COUNT:get() -----------------------------------------------trick specific loop_stage = 0 target_vel = ahrs:get_velocity_NED():length() gcs:send_text(0, string.format("Loop/Return")) --change announcement as appropriate for trick ------------------------------------------------------- elseif running == true then do_loop(TRICK_RAT:get()) -- change arguments as appropriate for trick end else running = false end return update, 50 end return init,1000
gpl-3.0
shreyaspotnis/S4
modules/Sample2DBox.lua
7
7525
inspect = require('inspect') function Sample2DBox(argtable) if not argtable['Xlim'] then error('Must provide Xlim table: Xlim = { xmin, xmax }') end if not argtable['Ylim'] then error('Must provide Ylim table: Ylim = { ymin, ymax }') end if not argtable['UpdateFunc'] then error('Must provide UpdateFunc') end if not argtable['ComputeFunc'] then error('Must provide ComputeFunc') end local FunctionSampler1D = require('FunctionSampler1D') local FunctionSampler2D = require('FunctionSampler2D') local Xlim = argtable['Xlim'] local Ylim = argtable['Ylim'] local Ncores = argtable['Ncores'] or 1 local Fupdate = argtable['UpdateFunc'] local Fcompute = argtable['ComputeFunc'] local Sampler1D = argtable['Sampler1D'] or FunctionSampler1D.New() local Nedge_initial = argtable['NumUniformEdgeSamples'] or 16 local Nedge_max = argtable['MaxEdgeSamples'] or 128 local Ninterior = argtable['NumUniformInteriorSamples'] or 100 local dx = Xlim[2] - Xlim[1] local dy = Ylim[2] - Ylim[1] --------------------------------------------------------------------------- ---------- STAGE 0: Generate a list of cloned Simulation objects ---------- --------------------------------------------------------------------------- local Slist = { argtable['Simulation'] } if nil == Slist[0] then Slist = nil else for i = 2,Ncores do Slist[i] = Slist[0]:Clone() end end --------------------------------------------------------------------------- -------- STAGE 1: Perform uniform and adative sampling along edges -------- --------------------------------------------------------------------------- local corners = { -- A list of the 4 corner vertices { Xlim[1], Ylim[1] }, { Xlim[2], Ylim[1] }, { Xlim[2], Ylim[2] }, { Xlim[1], Ylim[2] } } local edge_endpoints = { -- indices into `corners' of the endpoints of 4 edges { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 1 } }; local edge_varying_dim = { 1, 2, 1, 2 } -- which dimension of the edge is varying local edge_sample_points = {} -- list of size 4, each a list of edge samples local edge_sample_values = {} -- Perform uniform sampling on each edge -- Here, each edge includes the beginning vertex but excludes the ending vertex for iedge = 1,4 do edge_sample_points[iedge] = {} edge_sample_values[iedge] = {} local icorner1 = edge_endpoints[iedge][1] -- index of starting vertex of edge local icorner2 = edge_endpoints[iedge][2] -- index of ending vertex of edge local ivardim = edge_varying_dim[iedge] -- 1 or 2 for which dimension of the edge is varying -- Reset the 1D sampler. -- The 1D sampler will have normalized x values (the t parameter below) Sampler1D:Clear() -- A local function to translate a list of parameter t values to xy coords local t2xy_and_update = function(tlist) local xylist = {} for i = 1,#tlist do local t = tlist[i] xylist[i] = { corners[icorner1][1], corners[icorner1][2] } xylist[i][ivardim] = ( (1-t) * corners[icorner1][ivardim] + t* corners[icorner2][ivardim] ) if Slist then Fupdate(Slist[i], xylist[i][1], xylist[i][2]) end end return xylist end -- Do the sampling in batches of `Ncores' points at a time local n_edge_batches = math.ceil(Nedge_initial/Ncores) for ibatch = 1,n_edge_batches do local tbatch = {} -- list of parameter values [0-1] along edge for current batch for icore = 1,Ncores do tbatch[icore] = (icore-1 + (ibatch-1)*Ncores) / (Ncores*n_edge_batches) end -- Translate from parameter values along edge to actual points along edge and update local xylist = t2xy_and_update(tbatch) local zlist = Fcompute(Slist, xylist) for i = 1,Ncores do table.insert(edge_sample_points[iedge], xylist[i]) table.insert(edge_sample_values[iedge], zlist[i]) Sampler1D:Add(tbatch[i], zlist[i]) end end -- Finish up with adaptive sampling along the edge while not Sampler1D:IsDone() and #edge_sample_points[iedge] < Nedge_max do local tbatch = Sampler1D:GetNext(Ncores) -- Note: tbatch can have fewer than Ncores items local xylist = t2xy_and_update(tbatch) local zlist = Fcompute(Slist, xylist) for i = 1,Ncores do table.insert(edge_sample_points[iedge], xylist[i]) table.insert(edge_sample_values[iedge], zlist[i]) Sampler1D:Add(tbatch[i], zlist[i]) end end end --------------------------------------------------------------------------- ----------- STAGE 2: Initialize a new FunctionSampler2D object ------------ --------------------------------------------------------------------------- local xy2uv = function(xy) return { (xy[1]-Xlim[1])/dx, (xy[2]-Ylim[1])/dy } end local uv2xy = function(uv) return { uv[1]*dx+Xlim[1], uv[2]*dy+Ylim[1] } end -- Add the four corners local uvlist = { xy2uv(edge_sample_points[1][1]), xy2uv(edge_sample_points[2][1]), xy2uv(edge_sample_points[3][1]), xy2uv(edge_sample_points[4][1]) } local Sampler2D = FunctionSampler2D.New{ { uvlist[1][1], uvlist[1][2], edge_sample_values[1][1] }, { uvlist[2][1], uvlist[2][2], edge_sample_values[2][1] }, { uvlist[3][1], uvlist[3][2], edge_sample_values[3][1] }, { uvlist[4][1], uvlist[4][2], edge_sample_values[4][1] } } -- Add the rest of the edge points for iedge = 1,4 do for i = 2,#edge_sample_points[iedge] do local uv = xy2uv(edge_sample_points[iedge][i]) Sampler2D:Add( uv[1], uv[2], edge_sample_values[iedge][i] ) end end --------------------------------------------------------------------------- ----------------- STAGE 3: Uniformly sample the interior ------------------ --------------------------------------------------------------------------- -- Produce a list of uv locations local uvlist = {} local xylist = {} local n_int_side = math.ceil(math.sqrt(Ninterior)) for i = 1,n_int_side do local ti = i/(n_int_side+1) for j = 1,n_int_side do local tj = j/(n_int_side+1) local uv = { ti, tj } table.insert(uvlist, uv) table.insert(xylist, uv2xy(uv)) end end -- Compute at the uv locations in chunks of size Ncores for i = 1,#xylist,Ncores do local xybatch = {} local uvbatch = {} local Sbatch = {} for j = 1,Ncores do if i+j-1 <= #xylist then table.insert(uvbatch, uvlist[i+j-1]) table.insert(xybatch, xylist[i+j-1]) if Slist then Sbatch[j] = Slist[j] Fupdate(Sbatch[j], xybatch[j][1], xybatch[j][2]) end end end local zbatch = Fcompute(Sbatch, xybatch) for j = 1,#xybatch do Sampler2D:Add(uvbatch[j][1], uvbatch[j][2], zbatch[j]) end end --------------------------------------------------------------------------- ----------------- STAGE 4: Adaptively sample the interior ----------------- --------------------------------------------------------------------------- while not Sampler2D:IsDone() do local uvbatch = Sampler2D:GetNext(Ncores) local xybatch = {} local Sbatch = {} for i = 1,#uvbatch do xybatch[i] = uv2xy(uvbatch[i]) if Slist then Sbatch[i] = Slist[i] Fupdate(Sbatch[i], xybatch[i][1], xybatch[i][2]) end end zbatch = Fcompute(Sbatch, xybatch) for i = 1,#xybatch do Sampler2D:Add(uvbatch[i][1], uvbatch[i][2], zbatch[i]) end end end function f(x,y) local z = math.sin(x*y) print(x,y,z) return z end function update(Slist) end function compute(Slist, xylist) local ret = {} for i = 1,#xylist do ret[i] = f(xylist[i][1], xylist[i][2]) end return ret end Sample2DBox{ Xlim = { 0, 5 }, Ylim = { 0, 5 }, Ncores = 4, UpdateFunc = update, ComputeFunc = compute }
gpl-2.0
alexandergall/snabbswitch
lib/luajit/testsuite/test/lib/ffi/jit_struct.lua
6
4085
local ffi = require("ffi") ffi.cdef[[ typedef struct { int a, b, c; } jit_struct_foo_t; typedef struct { int a, b, c; } jit_struct_foo2_t; typedef struct { int a[10]; int b[10]; } jit_struct_sarr_t; typedef struct jit_struct_chain_t { struct jit_struct_chain_t *next; int v; } jit_struct_chain_t; ]] do --- iteration variable as field name local s = ffi.new("jit_struct_foo_t") for j,k in ipairs{ "a", "b", "c" } do for i=1,100 do s[k] = s[k] + j end end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- constant field names local s = ffi.new("jit_struct_foo_t") for i=1,100 do s.a = s.a + 1 s.b = s.b + 2 s.c = s.c + 3 end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- constants from structure local s = ffi.new("jit_struct_foo_t") local s2 = ffi.new("jit_struct_foo2_t", 1, 2, 3) for i=1,100 do s.a = s.a + s2.a s.b = s.b + s2.b s.c = s.c + s2.c end assert(s.a == 100) assert(s.b == 200) assert(s.c == 300) end do --- adding to array elements local s = ffi.new("jit_struct_sarr_t") for i=1,100 do s.a[5] = s.a[5] + 1 s.b[5] = s.b[5] + 2 end assert(s.a[5] == 100) assert(s.b[5] == 200) end do --- double indexing local s = ffi.new([[ struct { struct { int x; int b[10]; } a[100]; }]]) s.a[10].b[4] = 10 s.a[95].b[4] = 95 local x = 0 for i=1,100 do x = x + s.a[i-1].b[4] -- reassociate offsets for base and index end assert(x == 105) end do --- structurally identical local s1 = ffi.new("struct { int a; }") local s2 = ffi.new("struct { int a; }") local x = 0 for j=1,2 do for i=1,100 do s2.a = i s1.a = 1 x = x + s2.a -- cannot forward across aliasing store end if j == 1 then assert(x == 5050) s2 = s1 x = 0 else assert(x == 100) end end end do --- structurally different local s1 = ffi.new("struct { int a; }") local s2 = ffi.new("struct { char a; }") local x = 0 for j=1,2 do for i=1,100 do s2.a = i s1.a = 1 x = x + s2.a -- can forward across aliasing store end if j == 1 then assert(x == 5050) s2 = s1 -- this will cause a side trace x = 0 else assert(x == 100) end end end do --- union local s = ffi.new("union { uint8_t a; int8_t b; }") local x = 0 for i=1,200 do s.a = i x = x + s.b -- same offset, but must not alias (except if sign-extended) end assert(x == 1412) end do --- circular chain local s1 = ffi.new("jit_struct_chain_t") local s2 = ffi.new("jit_struct_chain_t") local s3 = ffi.new("jit_struct_chain_t") s1.next = s2 s2.next = s3 s3.next = s1 local p = s1 for i=1,99 do p.v = i p = p.next end assert(s1.v == 97) assert(s2.v == 98) assert(s3.v == 99) end do --- int struct initialiser local ct = ffi.typeof("struct { int a,b,c; }") local x,y,z = 0,0,0 for i=1,100 do local s = ct(i, i+1) x = x + s.a y = y + s.b z = z + s.c end assert(x == 5050) assert(y == 5150) assert(z == 0) end do --- double struct initialiser local ct = ffi.typeof("struct { double a,b,c; }") local x,y,z = 0,0,0 for i=1,100 do local s = ct(i, i+1) x = x + s.a y = y + s.b z = z + s.c end assert(x == 5050) assert(y == 5150) assert(z == 0) end do --- pointer / int struct initialiser local s1 = ffi.new("jit_struct_chain_t") local s for i=1,100 do s = ffi.new("jit_struct_chain_t", s1, i) end assert(tonumber(ffi.cast("int", s.next)) == tonumber(ffi.cast("int", ffi.cast("jit_struct_chain_t *", s1)))) assert(s.v == 100) end do --- unstable pointer/int type struct initialiser local ct = ffi.typeof("struct { int *p; int y; }") local s for i=1,200 do if i == 100 then ct = ffi.typeof("jit_struct_chain_t") end s = ct(nil, 10) end assert(s.v == 10) end do --- upvalued int box local s = ffi.new("struct { int x; }", 42) local function f() for i=1,100 do s.x = i assert(s.x == i) end end f() end
apache-2.0
Danteoriginal/pvpgn-lua
lua/include/string.lua
7
1737
--[[ Copyright (C) 2014 HarpyWar (harpywar@gmail.com) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- Split text into table by delimeter -- Usage example: string.split("one,two",",") function string:split(str, sep) str = str or '%s+' local st, g = 1, self:gmatch("()("..str..")") local function getter(segs, seps, sep, cap1, ...) st = sep and seps + #sep return self:sub(segs, (seps or 0) - 1), cap1 or sep, ... end return function() if st then return getter(st, g()) end end end -- Check string is nil or empty -- bool -- Usage example: string:empty("") -> true, string:empty(nil) -> true function string:empty(str) return str == nil or str == '' end -- bool function string.starts(str, starts) if string:empty(str) then return false end return string.sub(str,1,string.len(starts))==starts end -- bool function string.ends(str, ends) if string:empty(str) then return false end return ends=='' or string.sub(str,-string.len(ends))==ends end -- Replace string -- Usage example: string.replace("hello world","world","Joe") -> "hello Joe" function string.replace(str, pattern, replacement) if string:empty(str) then return str end local s, n = string.gsub(str, pattern, replacement) return s end function string:trim(str) if string:empty(str) then return str end return (str:gsub("^%s*(.-)%s*$", "%1")) end -- Replace char in specified position of string function replace_char(pos, str, replacement) if string:empty(str) then return str end return str:sub(1, pos-1) .. replacement .. str:sub(pos+1) end -- return count of substr in str function substr_count(str, substr) local _, count = string.gsub(str, substr, "") return count end
gpl-2.0
xponen/Zero-K
units/trem.lua
5
6415
unitDef = { unitname = [[trem]], name = [[Tremor]], description = [[Heavy Saturation Artillery Tank]], acceleration = 0.05952, brakeRate = 0.124, buildCostEnergy = 1500, buildCostMetal = 1500, builder = false, buildPic = [[TREM.png]], buildTime = 1500, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[34 34 50]], collisionVolumeTest = 1, collisionVolumeType = [[cylZ]], corpse = [[DEAD]], customParams = { description_de = [[Schwerer Saturation Artillerie Panzer]], description_bp = [[Tanque de artilharia pesado]], description_fr = [[Artillerie Lourde]], description_pl = [[Ciezka artyleria]], helptext = [[The principle behind the Tremor is simple: flood an area with enough shots, and you'll hit something at least once. Slow, clumsy, vulnerable and extremely frightening, the Tremor works best against high-density target areas, where its saturation shots are most likely to do damage. It pulverizes shields in seconds and its shells smooth terrain.]], helptext_bp = [[O princípio por trás do Tremor é simples: encha uma área com tiros suficientes, e voç? acertará algo pelo menos uma vez. Lento, atrapalhado, vulnerável e extremamente assustador, Tremor funciona melhor contra áreas-alvo de alta densidade, onde seus tiros de saturaç?o tem maior probabilidade de causar dano.]], helptext_fr = [[Le principe du Tremor est simple: inonder une zone de tirs plasma gr?ce ? son triple canon, avec une chance de toucher quelquechose. Par d?finition impr?cis, le Tremor est l'outil indispensable de destruction de toutes les zones ? h'aute densit? d'ennemis.]], helptext_de = [[Das Prinzip hinter dem Tremor ist einfach: flute ein Areal mit genug Schüssen und du wirst irgendwas, wenigstens einmal, treffen. Langsam, schwerfällig, anfällig und extrem beängstigend ist der Tremor, weshalb er gegen dichbesiedelte Gebiete sinnvoll einzusetzen ist.]], helptext_pl = [[Tremor zalewa okolice gradem pociskow, co doskonale sprawdza sie przeciwko duzym zgrupowaniom wrogich jednostek i tarczom i wyrownuje teren.]], modelradius = [[17]], }, explodeAs = [[BIG_UNIT]], footprintX = 4, footprintZ = 4, highTrajectory = 1, iconType = [[tanklrarty]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 392, maxDamage = 2045, maxSlope = 18, maxVelocity = 1.7, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK4]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP]], objectName = [[cortrem.s3o]], seismicSignature = 4, selfDestructAs = [[BIG_UNIT]], sfxtypes = { explosiongenerators = { [[custom:wolvmuzzle1]], }, }, side = [[CORE]], sightDistance = 660, smoothAnim = true, trackOffset = 20, trackStrength = 8, trackStretch = 1, trackType = [[StdTank]], trackWidth = 38, turninplace = 0, turnRate = 312, workerTime = 0, weapons = { { def = [[PLASMA]], badTargetCategory = [[SWIM LAND SHIP HOVER]], mainDir = [[0 0 1]], maxAngleDif = 270, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]], }, }, weaponDefs = { PLASMA = { name = [[Rapid-Fire Plasma Artillery]], accuracy = 1400, areaOfEffect = 160, avoidFeature = false, avoidGround = false, craterBoost = 0, craterMult = 0, customParams = { gatherradius = [[192]], smoothradius = [[96]], smoothmult = [[0.25]], lups_noshockwave = [[1]], }, damage = { default = 135, planes = 135, subs = 7, }, explosionGenerator = [[custom:tremor]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, myGravity = 0.1, range = 1300, reloadtime = 0.36, soundHit = [[weapon/cannon/cannon_hit2]], soundStart = [[weapon/cannon/tremor_fire]], turret = true, weaponType = [[Cannon]], weaponVelocity = 420, }, }, featureDefs = { DEAD = { description = [[Wreckage - Tremor]], blocking = true, category = [[corpses]], damage = 2045, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[8]], hitdensity = [[100]], metal = 600, object = [[tremor_dead_new.s3o]], reclaimable = true, reclaimTime = 600, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Tremor]], blocking = false, category = [[heaps]], damage = 2045, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[2]], hitdensity = [[100]], metal = 300, object = [[debris2x2a.s3o]], reclaimable = true, reclaimTime = 300, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ trem = unitDef })
gpl-2.0
xuejian1354/barrier_breaker
feeds/luci/applications/luci-hd-idle/luasrc/model/cbi/hd_idle.lua
36
1043
--[[ LuCI hd-idle (c) 2008 Yanira <forum-2008@email.de> 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("nixio.fs") m = Map("hd-idle", "hd-idle", translate("hd-idle is a utility program for spinning-down external " .. "disks after a period of idle time.")) s = m:section(TypedSection, "hd-idle", translate("Settings")) s.anonymous = true s:option(Flag, "enabled", translate("Enable")) disk = s:option(Value, "disk", translate("Disk")) disk.rmempty = true for dev in nixio.fs.glob("/dev/[sh]d[a-z]") do disk:value(nixio.fs.basename(dev)) end s:option(Value, "idle_time_interval", translate("Idle-time")).default = 10 s.rmempty = true unit = s:option(ListValue, "idle_time_unit", translate("Idle-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) unit.rmempty = true return m
gpl-2.0
pavanky/arrayfire-lua
examples/image_processing/filters.lua
4
7300
--[[ /******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <cmath> #include <cstdio> #include <cstdlib> #include <arrayfire.h> using namespace af; array clamp(const array &in, float min = 0.0f, float max = 255.0f) { return ((in<min)*0.0f + (in>max)*255.0f + (in >= min && in <= max)*in); } array hurl(const array &in, int randomization, int repeat) { int w = in.dims(0); int h = in.dims(1); float f = randomization / 100.0f; int dim = (int)(f*w*h); array ret_val = in.copy(); array temp = moddims(ret_val, w*h, 3); for (int i = 0; i<repeat; ++i) { array idxs = (w*h) * randu(dim); array rndR = 255.0f * randu(dim); array rndG = 255.0f * randu(dim); array rndB = 255.0f * randu(dim); temp(idxs, 0) = rndR; temp(idxs, 1) = rndG; temp(idxs, 2) = rndB; } ret_val = moddims(temp, in.dims()); return ret_val; } array getRandomNeighbor(const array &in, int windW, int windH) { array rnd = 2.0f*randu(in.dims(0), in.dims(1)) - 1.0f; array sx = seq(in.dims(0)); array sy = seq(in.dims(1)); array vx = tile(sx, 1, in.dims(1)) + floor(rnd*windW); array vy = tile(sy.T(), in.dims(0), 1) + floor(rnd*windH); array vxx = clamp(vx, 0, in.dims(0)); array vyy = clamp(vy, 0, in.dims(1)); array in2 = moddims(in, vx.elements(), 3); return moddims(in2(vyy*in.dims(0) + vxx, span), in.dims()); } array spread(const array &in, int window_width, int window_height) { return getRandomNeighbor(in, window_width, window_height); } array pick(const array &in, int randomization, int repeat) { int w = in.dims(0); int h = in.dims(1); float f = randomization / 100.0f; int dim = (int)(f*w*h); array ret_val = in.copy(); for (int i = 0; i<repeat; ++i) { array idxs = (w*h) * randu(dim); array rnd = getRandomNeighbor(ret_val, 1, 1); array temp_src = moddims(rnd, w*h, 3); array temp_dst = moddims(ret_val, w*h, 3); temp_dst(idxs, span) = temp_src(idxs, span); ret_val = moddims(temp_dst, in.dims()); } return ret_val; } void prewitt(array &mag, array &dir, const array &in) { static float h1[] = { 1, 1, 1 }; static float h2[] = { -1, 0, 1 }; static array h1d(3, h1); static array h2d(3, h2); // Find the gradients array Gy = af::convolve(h2d, h1d, in) / 6; array Gx = af::convolve(h1d, h2d, in) / 6; // Find magnitude and direction mag = hypot(Gx, Gy); dir = atan2(Gy, Gx); } void sobelFilter(array &mag, array &dir, const array &in) { // Find the gradients array Gy, Gx; af::sobel(Gx, Gy, in); // Find magnitude and direction mag = hypot(Gx, Gy); dir = atan2(Gy, Gx); } void normalizeImage(array &in) { float min = af::min<float>(in); float max = af::max<float>(in); in = 255.0f*((in - min) / (max - min)); } array DifferenceOfGaussian(const array &in, int window_radius1, int window_radius2) { array ret_val; int w1 = 2 * window_radius1 + 1; int w2 = 2 * window_radius2 + 1; array g1 = gaussianKernel(w1, w1); array g2 = gaussianKernel(w2, w2); ret_val = (convolve(in, g1) - convolve(in, g2)); normalizeImage(ret_val); return ret_val; } array medianfilter(const array &in, int window_width, int window_height) { array ret_val(in.dims()); ret_val(span, span, 0) = medfilt(in(span, span, 0), window_width, window_height); ret_val(span, span, 1) = medfilt(in(span, span, 1), window_width, window_height); ret_val(span, span, 2) = medfilt(in(span, span, 2), window_width, window_height); return ret_val; } array gaussianblur(const array &in, int window_width, int window_height, int sigma) { array g = gaussianKernel(window_width, window_height, sigma, sigma); return convolve(in, g); } array emboss(const array &input, float azimuth, float elevation, float depth) { if (depth<1 || depth>100) { printf("Depth should be in the range of 1-100"); return input; } static float x[3] = { -1, 0, 1 }; static array hg(3, x); static array vg = hg.T(); array in = input; if (in.dims(2)>1) in = colorSpace(input, AF_GRAY, AF_RGB); else in = input; // convert angles to radians float phi = elevation*af::Pi / 180.0f; float theta = azimuth*af::Pi / 180.0f; // compute light pos in cartesian coordinates // and scale with maximum intensity // phi will effect the amount of we intend to put // on a pixel float pos[3]; pos[0] = 255.99f * cos(phi)*cos(theta); pos[1] = 255.99f * cos(phi)*sin(theta); pos[2] = 255.99f * sin(phi); // compute gradient vector array gx = convolve(in, vg); array gy = convolve(in, hg); float pxlz = (6 * 255.0f) / depth; array zdepth = constant(pxlz, gx.dims()); array vdot = gx*pos[0] + gy*pos[1] + pxlz*pos[2]; array outwd = vdot < 0.0f; array norm = vdot / sqrt(gx*gx + gy*gy + zdepth*zdepth); array color = outwd * 0.0f + (1 - outwd) * norm; return color; } int main(int argc, char **argv) { try { int device = argc > 1 ? atoi(argv[1]) : 0; af::setDevice(device); af::info(); array lena = loadImage(ASSETS_DIR "/examples/images/vegetable-woman.jpg", true); array prew_mag, prew_dir; array sob_mag, sob_dir; array lena1ch = colorSpace(lena, AF_GRAY, AF_RGB); prewitt(prew_mag, prew_dir, lena1ch); sobelFilter(sob_mag, sob_dir, lena1ch); array sprd = spread(lena, 3, 3); array hrl = hurl(lena, 10, 1); array pckng = pick(lena, 40, 2); array difog = DifferenceOfGaussian(lena, 1, 2); array bil = bilateral(hrl, 3.0f, 40.0f); array mf = medianfilter(hrl, 5, 5); array gb = gaussianblur(hrl, 3, 3, 0.8); array emb = emboss(lena, 45, 20, 10); af::Window wnd("Image Filters Demo"); std::cout << "Press ESC while the window is in focus to exit" << std::endl; while (!wnd.close()) { wnd.grid(2, 5); wnd(0, 0).image(hrl / 255, "Hurl noise"); wnd(1, 0).image(gb / 255, "Gaussian blur"); wnd(0, 1).image(bil / 255, "Bilateral filter on hurl noise"); wnd(1, 1).image(mf / 255, "Median filter on hurl noise"); wnd(0, 2).image(prew_mag / 255, "Prewitt edge filter"); wnd(1, 2).image(sob_mag / 255, "Sobel edge filter"); wnd(0, 3).image(sprd / 255, "Spread filter"); wnd(1, 3).image(pckng / 255, "Pick filter"); wnd(0, 4).image(difog / 255, "Difference of gaussians(3x3 and 5x5)"); wnd(1, 4).image(emb / 255, "Emboss effect"); wnd.show(); } } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } #ifdef WIN32 // pause in Windows if (!(argc == 2 && argv[1][0] == '-')) { printf("hit [enter]..."); fflush(stdout); getchar(); } #endif return 0; } ]]
bsd-3-clause
pavanky/arrayfire-lua
examples/graphics/fractal.lua
4
2876
--[[ /******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ ]] -- Standard library imports -- local abs = math.abs local sqrt = math.sqrt -- Modules -- local AF = require("arrayfire") -- Shorthands -- local Comp, WC = AF.CompareResult, AF.WrapConstant AF.main(function(argc, argv) local WIDTH = 400 -- Width of image local HEIGHT = 400 -- Width of image local function complex_grid (width, height, zoom, center) -- Generate sequences of length width, height local x = AF.array(AF.seq(height) - height / 2.0) local y = AF.array(AF.seq(width ) - width / 2.0) -- Tile the sequences to generate grid of image size local X = AF.tile(x:T(), y:elements(), 1) / zoom + center[1] local Y = AF.tile(y , 1, x:elements()) / zoom + center[2] -- Return the locations as a complex grid return AF.complex(X, Y) end local C, Z, mag local function AuxMandelbrot (env, maxval) local ii = env("get_step") -- Do the calculation Z = Z * Z + C -- Get indices where abs(Z) crosses maxval local cond = Comp(AF.abs(Z) > maxval):as("f32") mag = env(AF.max(mag, cond * ii)) -- If abs(Z) cross maxval, turn off those locations C = env(C * (1 - cond)) Z = env(Z * (1 - cond)) -- Ensuring the JIT does not become too large C:eval() Z:eval() end local function mandelbrot (in_arr, iter, maxval) C = in_arr:copy(); Z = C:copy() mag = AF.constant(0, C:dims()) AF.EnvLoopFromTo_Mode(1, iter - 1, "parent_gc", AuxMandelbrot, maxval) -- Normalize return mag / maxval end local function normalize (a) local mx = AF.max("f32", a) local mn = AF.min("f32", a) return (a-mn)/(mx-mn) end local iter = argc > 2 and tonumber(argv[2]) or 100 -- Seems to never be used... local console = argc > 2 and argv[2][0] == '-' print("** ArrayFire Fractals Demo **") local wnd = AF.Window(WIDTH, HEIGHT, "Fractal Demo"); wnd:setColorMap("AF_COLORMAP_SPECTRUM") local center = {-0.75, 0.1} -- Keep zooming out for each frame local _1000 = WC(1000) AF.EnvLoopFromTo(10, 399, function(env) local i = env("get_step") local zoom = i * i if i % 10 == 0 then AF.printf("iteration: %d zoom: %d", i, zoom) io.output():flush() -- n.b.: no braces in original end -- Generate the grid at the current zoom factor local c = complex_grid(WIDTH, HEIGHT, zoom, center) iter =sqrt(abs(2*sqrt(abs(1-sqrt(5*zoom)))))*100 -- Generate the mandelbrot image local mag = mandelbrot(c, iter, _1000) if not console then if wnd:close() then return "stop_loop" end local mag_norm = normalize(mag) wnd:image(mag_norm) end end) wnd:destroy() end)
bsd-3-clause
pablo93/TrinityCore
Data/Interface/FrameXML/SparkleFrame.lua
1
5808
-- YAY FOR SPARKLES~! SparkleFrame = CreateFrame("FRAME"); local Sparkle = SparkleFrame:CreateTexture(); function Sparkle:New (sparkleFrame, sparkleTemplate) if ( sparkleFrame.freeSparkles[1] ) then local sparkle = sparkleFrame.freeSparkles[1]; tremove(sparkleFrame.freeSparkles, 1); tinsert(sparkleFrame.sparkles, sparkle); return sparkle; end sparkleTemplate = sparkleTemplate or "SparkleTexture1" local name = sparkleFrame:GetName(); local sparkle; if ( name ) then sparkle = sparkleFrame:CreateTexture(name .. "Sparkle" .. sparkleFrame.numSparkles, "ARTWORK", sparkleTemplate) else sparkle = sparkleFrame:CreateTexture(nil, "ARTWORK", sparkleTemplate); end setmetatable(sparkle, self); self.__index = self; tinsert(sparkleFrame.sparkles, sparkle) sparkleFrame.numSparkles = sparkleFrame.numSparkles + 1; return sparkle; end function Sparkle:Free () local sparkleFrame = self:GetParent(); self:Hide(); for i = 1, self.numArgs do self["param" .. i] = nil; end self.elapsed = nil; self.loop = nil; self.Animate = nil; tinsert(sparkleFrame.freeSparkles, self); end function Sparkle:LinearTranslate (elapsed) -- Parameters for LinearTranslate: -- 1 - relativePoint, 2 - xStart, 3 - xStop, 4 - yStart, 5 - yStop, 6 - duration local relativePoint, xStart, xStop, yStart, yStop, duration = self.param1, self.param2, self.param3, self.param4, self.param5, self.param6; self:Show(); self.elapsed = self.elapsed + elapsed; local xRange = xStart - xStop; local yRange = yStart - yStop; local xDir = ( xStart < xStop and 1 ) or -1; local yDir = ( yStart < yStop and 1 ) or -1; local position = self.elapsed / duration; self:SetPoint("CENTER", "$parent", relativePoint, xStart + (math.abs(xRange * position)*xDir), yStart + (math.abs(yRange * position)*yDir)); if ( position >= 1 and self.loop ) then self.elapsed = 0; elseif ( position >= 1 ) then return true; end return false; end function Sparkle:Pulse (elapsed) -- Parameters for Sparkle: -- relativePoint, xPos, yPos, startAlpha, maxAlpha, endAlpha, fadeInDuration, holdDuration, fadeOutDuration local relativePoint, xPos, yPos = self.param1, self.param2, self.param3; local startAlpha, maxAlpha, endAlpha = self.param4, self.param5, self.param6; local fadeInDuration, holdDuration, fadeOutDuration = self.param7, self.param8, self.param9; self:Show(); self:SetPoint("CENTER", "$parent", relativePoint, xPos, yPos); self.elapsed = self.elapsed + elapsed; if ( self.elapsed <= fadeInDuration ) then local range = maxAlpha - startAlpha; local percentage = self.elapsed/fadeInDuration; self:SetAlpha(startAlpha + (range*percentage)); elseif ( self.elapsed <= holdDuration ) then self:SetAlpha(maxAlpha); elseif ( self.elapsed <= fadeOutDuration ) then local range = maxAlpha - endAlpha; local percentage = (self.elapsed-holdDuration)/(fadeOutDuration-holdDuration); self:SetAlpha(maxAlpha - (range*percentage)); elseif ( self.loop ) then self.elapsed = 0; else return true; end return false; end local cos = cos; local sin = sin; function Sparkle:RadialTranslate (elapsed) -- Parameters for RadialTranslate: -- relativePoint, radius, startDegree, stopDegree, duration local relativePoint, offsetX, offsetY, radius, startDegree, stopDegree, duration = self.param1, self.param2, self.param3, self.param4, self.param5, self.param6, self.param7; self:Show(); self.elapsed = self.elapsed + elapsed; local range = startDegree - stopDegree; local position = self.elapsed/duration local degree = startDegree + (range * position); local xPos = offsetX + (radius * cos(degree)); local yPos = offsetY + (radius * sin(degree)); self:SetPoint("CENTER", "$parent", relativePoint, xPos, yPos); if ( position >= 1 and self.loop ) then self.elapsed = 0; elseif ( position >= 1 ) then return true; end return false; end function SparkleFrame:New (parent) local sparkleFrame; if ( parent ) then sparkleFrame = CreateFrame("FRAME", parent:GetName() .. "SparkleFrame", parent); sparkleFrame:SetPoint("TOPLEFT"); sparkleFrame:SetPoint("BOTTOMRIGHT"); else sparkleFrame = CreateFrame("FRAME"); end setmetatable(sparkleFrame, self); self.__index = self; sparkleFrame.timeSinceLast = 0; sparkleFrame.updateTime = 0.0334 -- Roughly 30 frames per second. sparkleFrame.numSparkles = 0; sparkleFrame.freeSparkles = {}; sparkleFrame.sparkles = {}; sparkleFrame:SetScript("OnUpdate", sparkleFrame.OnUpdate); return sparkleFrame; end function SparkleFrame:SetFrameRate(framesPerSec) self.updateTime = 1/(framesPerSec or 30); end function SparkleFrame:OnUpdate(elapsed) self.timeSinceLast = self.timeSinceLast + elapsed; if ( self.timeSinceLast >= self.updateTime ) then for i, sparkle in next, self.sparkles do debugprofilestart() if ( sparkle:Animate(self.timeSinceLast) ) then sparkle:Free(); self.sparkles[i] = nil; end msg(debugprofilestop()); end self.timeSinceLast = 0; end end function SparkleFrame:StartAnimation (name, animationType, sparkleTemplate, loop, ...) if ( not Sparkle[animationType] ) then return; end local sparkle = Sparkle:New(self, sparkleTemplate); sparkle.numArgs = select("#", ...); for i = 1, sparkle.numArgs do sparkle["param"..i] = select(i, ...); end sparkle.name = name; sparkle.elapsed = 0; sparkle.loop = loop; sparkle.Animate = Sparkle[animationType]; end function SparkleFrame:EndAnimation (name) for i, sparkle in next, self.sparkles do if ( sparkle.name == name ) then sparkle:Free(i); self.sparkles[i] = nil; end end end function SparkleFrame:SetAnimationVertexColor (name, r, g, b, a) for i, sparkle in next, self.sparkles do if ( sparkle.name == name ) then sparkle:SetVertexColor(r, g, b, a); end end end
gpl-2.0
xponen/Zero-K
LuaRules/Gadgets/KotH.lua
1
5814
-- $Id$ -- ZK Version -- King of the Hill for ModOptions ------------------------------------- -- Set up an empty box on Spring Lobby (other clients might crash) ------ -- Set up the time to control the box in ModOptions -------------------- -------------------------------------------------------------------- function gadget:GetInfo() return { name = "King of the Hill", desc = "obvious", author = "Alchemist, Licho", date = "April 2009", license = "Public domain", layer = 1, enabled = true } end local blockedDefs = { [ UnitDefNames['terraunit'].id ] = true, [ UnitDefNames['wolverine_mine'].id ] = true, } --------------------------------------------------------------------------------- if(not Spring.GetModOptions()) then return false end local teamBoxes = {} for _, allyTeamID in ipairs(Spring.GetAllyTeamList()) do local teams = Spring.GetTeamList(allyTeamID) if (teams == nil or #teams == 0) then local x1, z1, x2, z2 = Spring.GetAllyTeamStartBox(allyTeamID) if (x1 ~= nil) then table.insert(teamBoxes, {x1, z1, x2, z2}) end end end --UNSYNCED------------------------------------------------------------------- if(not gadgetHandler:IsSyncedCode()) then local teams = {} local teamTimer = nil local teamControl = -2 local r, g, b = 255, 255, 255 local grace = 1 function gadget:Initialize() if(Spring.GetModOptions().zkmode ~= "kingofthehill") then gadgetHandler:RemoveGadget() end gadgetHandler:AddSyncAction("changeColor", setBoxColor) gadgetHandler:AddSyncAction("changeTime", updateTimers) end function gadget:DrawWorldPreUnit() gl.DepthTest(false) gl.Color(r, g, b, 0.4) for _, box in ipairs(teamBoxes) do gl.DrawGroundQuad(box[1], box[2], box[3], box[4], true) end gl.Color(1,1,1,1) end function DrawScreen() local vsx, vsy = gl.GetViewSizes() local posx = vsx * 0.5 if(grace > 0) then posy = vsy * 0.75 gl.Color(255, 255, 255, 1) if(grace % 60 < 10) then gl.Text("Grace period over in " .. math.floor(grace/60) .. ":0" .. math.floor(grace%60), posx, posy, 14, "ocn") else gl.Text("Grace period over in " .. math.floor(grace/60) .. ":" .. math.floor(grace%60), posx, posy, 14, "ocn") end end if (teamControl >= 0) then local posy = vsy * 0.25 gl.Color(255, 255, 255, 1) if(teamTimer % 60 < 10) then gl.Text("Team " .. teamControl + 1 .. " - " .. math.floor(teamTimer/60) .. ":0" .. math.floor(teamTimer%60), posx, posy, 12, "ocn") else gl.Text("Team " .. teamControl + 1 .. " - " .. math.floor(teamTimer/60) .. ":" .. math.floor(teamTimer%60), posx, posy, 12, "ocn") end end end function updateTimers(cmd, team, newTime, graceT) if(graceT) then grace = graceT else teamTimer = newTime teamControl = team end end function setBoxColor(cmd, team) if(team < 0) then r, g, b = 255, 255, 255 else r, g, b = Spring.GetTeamColor(team) end end end --------------------------------------------------------------------------------- --SYNCED----------------------------------------------------------------------- if(gadgetHandler:IsSyncedCode()) then local actualTeam = -1 local control = -1 local goalTime = 0 local timer = -1 local lastControl = nil local lastHolder = nil local grace = 0 local lG = 0 function gadget:Initialize() if(Spring.GetModOptions().zkmode ~= "kingofthehill") then gadgetHandler:RemoveGadget() end goalTime = (Spring.GetModOptions().hilltime or 0) * 60 lG = Spring.GetModOptions().gracetime if lG then grace = lG * 60 else grace = 0 end timer = goalTime end function gadget:GameStart() Spring.Echo("Goal time is " .. goalTime / 60 .. " minutes.") end function gadget:GameFrame(f) if(f%30 == 0 and f < grace * 30 + lG*30*60) then grace = grace - 1 SendToUnsynced("changeTime", nil, nil, grace) end if(f == grace*30 + lG*30*60) then SendToUnsynced("changeTime", nil, nil, grace) Spring.Echo("Grace period is over. GET THE HILL!") end if(f % 32 == 15 and f > grace*30 + lG*30*60) then local control = -2 local team = nil local present = false for _, box in ipairs(teamBoxes) do for _, u in ipairs(Spring.GetUnitsInRectangle(box[1], box[2], box[3], box[4])) do local ally = Spring.GetUnitAllyTeam(u) if (lastControl == ally) then present = true end if (control == -2) then if (not blockedDefs[Spring.GetUnitDefID(u)]) then control = ally team = Spring.GetUnitTeam(u) end else if (control ~= ally) then control = -1 break end end end end if(control ~= lastControl) then if (control == -1) then Spring.Echo("Control contested.") SendToUnsynced("changeColor", -1) else if (control == -2) then Spring.Echo("Team " .. control + 1 .. " lost control.") SendToUnsynced("changeColor", -1) timer = goalTime SendToUnsynced("changeTime", control, timer) else actualTeam = team if (lastHolder ~= control) then timer = goalTime lastHolder = control end Spring.Echo("Team " .. control + 1 .. " is now in control.") SendToUnsynced("changeColor", actualTeam) lastHolder = control end end end if (control >= 0) then timer = timer - 1 SendToUnsynced("changeTime", control, timer) end if(control >= 0 and timer == 0) then Spring.Echo("Team " .. control + 1 .. " has won!") gameOver(actualTeam) end lastControl = control end end function gameOver(team) for _, u in ipairs(Spring.GetAllUnits()) do if(not Spring.AreTeamsAllied(Spring.GetUnitTeam(u), team)) then Spring.DestroyUnit(u, true) end end end end
gpl-2.0
xuejian1354/barrier_breaker
feeds/luci/contrib/luadoc/lua/luadoc/init.lua
172
1333
------------------------------------------------------------------------------- -- LuaDoc main function. -- @release $Id: init.lua,v 1.4 2008/02/17 06:42:51 jasonsantos Exp $ ------------------------------------------------------------------------------- local require = require local util = require "luadoc.util" logger = {} module ("luadoc") ------------------------------------------------------------------------------- -- LuaDoc version number. _COPYRIGHT = "Copyright (c) 2003-2007 The Kepler Project" _DESCRIPTION = "Documentation Generator Tool for the Lua language" _VERSION = "LuaDoc 3.0.1" ------------------------------------------------------------------------------- -- Main function -- @see luadoc.doclet.html, luadoc.doclet.formatter, luadoc.doclet.raw -- @see luadoc.taglet.standard function main (files, options) logger = util.loadlogengine(options) -- load config file if options.config ~= nil then -- load specified config file dofile(options.config) else -- load default config file require("luadoc.config") end local taglet = require(options.taglet) local doclet = require(options.doclet) -- analyze input taglet.options = options taglet.logger = logger local doc = taglet.start(files) -- generate output doclet.options = options doclet.logger = logger doclet.start(doc) end
gpl-2.0
badboyam/Gp_Helper_bot
plugins/owners.lua
68
12477
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1]..':'..user_id redis:del(hash) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
alexandergall/snabbswitch
lib/ljsyscall/syscall/linux/arm/ffi.lua
25
1602
-- arm specific definitions return { ucontext = [[ typedef int greg_t, gregset_t[18]; typedef struct sigcontext { unsigned long trap_no, error_code, oldmask; unsigned long arm_r0, arm_r1, arm_r2, arm_r3; unsigned long arm_r4, arm_r5, arm_r6, arm_r7; unsigned long arm_r8, arm_r9, arm_r10, arm_fp; unsigned long arm_ip, arm_sp, arm_lr, arm_pc; unsigned long arm_cpsr, fault_address; } mcontext_t; typedef struct __ucontext { unsigned long uc_flags; struct __ucontext *uc_link; stack_t uc_stack; mcontext_t uc_mcontext; sigset_t uc_sigmask; unsigned long long uc_regspace[64]; } ucontext_t; ]], stat = [[ struct stat { unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; }; ]], statfs = [[ typedef uint32_t statfs_word; struct statfs64 { statfs_word f_type; statfs_word f_bsize; uint64_t f_blocks; uint64_t f_bfree; uint64_t f_bavail; uint64_t f_files; uint64_t f_ffree; kernel_fsid_t f_fsid; statfs_word f_namelen; statfs_word f_frsize; statfs_word f_flags; statfs_word f_spare[4]; } __attribute__((packed,aligned(4))); ]], }
apache-2.0
alexandergall/snabbswitch
src/dynasm.lua
20
37543
------------------------------------------------------------------------------ -- DynASM. A dynamic assembler for code generation engines. -- Originally designed and implemented for LuaJIT. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- See below for full copyright notice. ------------------------------------------------------------------------------ -- Application information. local _info = { name = "DynASM", description = "A dynamic assembler for code generation engines", version = "1.4.0_luamode", vernum = 10400, release = "2015-10-18", author = "Mike Pall", url = "http://luajit.org/dynasm.html", license = "MIT", copyright = [[ Copyright (C) 2005-2015 Mike Pall. All rights reserved. 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. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] ]], } -- Cache library functions. local type, pairs, ipairs = type, pairs, ipairs local pcall, error, assert = pcall, error, assert local select, tostring = select, tostring local _s = string local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub local format, rep, upper = _s.format, _s.rep, _s.upper local _t = table local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort local exit = os.exit local io = io local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr -- Helper to update a table with the elements another table. local function update(dst, src) if src then for k,v in pairs(src) do dst[k] = v end end return dst end ------------------------------------------------------------------------------ -- Program options. local g_opt -- Global state for current file. local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch local g_errcount -- Write buffer for output file. local g_wbuffer, g_capbuffer -- Map for defines (initially empty, chains to arch-specific map). local map_def -- Sections names. local map_sections -- The opcode map. Begins as an empty map set to inherit from map_initop, -- It's later changed to inherit from the arch-specific map, which itself is set -- to inherit from map_coreop. local map_op -- The initial opcode map to initialize map_op with on each global reset. local map_initop = {} -- Dummy action flush function. Replaced with arch-specific function later. local function dummy_wflush(term) end local wflush -- Init/reset the global state for processing a new file. local function reset() g_opt = {} g_opt.dumpdef = 0 g_opt.include = { "" } g_opt.lang = nil g_opt.comment = "//|" g_opt.endcomment = "" g_opt.cpp = true -- Write `#line` directives g_fname = nil g_curline = nil g_indent = "" g_lineno = 0 g_synclineno = -1 g_errcount = 0 g_arch = nil g_wbuffer = {} g_capbuffer = nil map_def = {} map_sections = {} map_op = setmetatable({}, { __index = map_initop }) wflush = dummy_wflush end ------------------------------------------------------------------------------ -- Write an output line (or callback function) to the buffer. local function wline(line, needindent) local buf = g_capbuffer or g_wbuffer buf[#buf+1] = needindent and g_indent..line or line g_synclineno = g_synclineno + 1 end -- Write assembler line as a comment, if requestd. local function wcomment(aline) if g_opt.comment then wline(g_opt.comment..aline..g_opt.endcomment, true) end end -- Resync CPP line numbers. local function wsync() if g_synclineno ~= g_lineno and g_opt.cpp then if not g_opt.lang == "lua" then wline("#line "..g_lineno..' "'..g_fname..'"') end g_synclineno = g_lineno end end -- Dump all buffered output lines. local function wdumplines(out, buf) for _,line in ipairs(buf) do if type(line) == "string" then assert(out:write(line, "\n")) else -- Special callback to dynamically insert lines after end of processing. line(out) end end end ------------------------------------------------------------------------------ -- Emit an error. Processing continues with next statement. local function werror(msg) error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0) end -- Emit a fatal error. Processing stops. local function wfatal(msg) g_errcount = "fatal" werror(msg) end -- Print a warning. Processing continues. local function wwarn(msg) stderr:write(format("%s:%s: warning: %s:\n%s\n", g_fname, g_lineno, msg, g_curline)) end -- Print caught error message. But suppress excessive errors. local function wprinterr(...) if type(g_errcount) == "number" then -- Regular error. g_errcount = g_errcount + 1 if g_errcount < 21 then -- Seems to be a reasonable limit. stderr:write(...) elseif g_errcount == 21 then stderr:write(g_fname, ":*: warning: too many errors (suppressed further messages).\n") end else -- Fatal error. stderr:write(...) return true -- Stop processing. end end ------------------------------------------------------------------------------ -- Map holding all option handlers. local opt_map = {} local opt_current -- Print error and exit with error status. local function opterror(...) stderr:write("dynasm.lua: ERROR: ", ...) stderr:write("\n") exit(1) end -- Get option parameter. local function optparam(args) local argn = args.argn local p = args[argn] if not p then opterror("missing parameter for option `", opt_current, "'.") end args.argn = argn + 1 return p end ------------------------------------------------------------------------------ -- Core pseudo-opcodes. local map_coreop = {} -- Forward declarations. local dostmt local readfile ------------------------------------------------------------------------------ -- Pseudo-opcode to define a substitution. map_coreop[".define_2"] = function(params, nparams) if not params then return nparams == 1 and "name" or "name, subst" end local name, def = params[1], params[2] or "1" if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end map_def[name] = def end map_coreop[".define_1"] = map_coreop[".define_2"] -- Define a substitution on the command line. function opt_map.D(args) local namesubst = optparam(args) local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$") if name then map_def[name] = subst elseif match(namesubst, "^[%a_][%w_]*$") then map_def[namesubst] = "1" else opterror("bad define") end end -- Undefine a substitution on the command line. function opt_map.U(args) local name = optparam(args) if match(name, "^[%a_][%w_]*$") then map_def[name] = nil else opterror("bad define") end end -- Helper for definesubst. local gotsubst local function definesubst_one(word) local subst = map_def[word] if subst then gotsubst = word; return subst else return word end end -- Iteratively substitute defines. local function definesubst(stmt) -- Limit number of iterations. for i=1,100 do gotsubst = false stmt = gsub(stmt, "#?[%w_]+", definesubst_one) if not gotsubst then break end end if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end return stmt end -- Dump all defines. local function dumpdefines(out, lvl) local t = {} for name in pairs(map_def) do t[#t+1] = name end sort(t) out:write("Defines:\n") for _,name in ipairs(t) do local subst = map_def[name] if g_arch then subst = g_arch.revdef(subst) end out:write(format(" %-20s %s\n", name, subst)) end out:write("\n") end ------------------------------------------------------------------------------ -- Support variables for conditional assembly. local condlevel = 0 local condstack = {} -- Evaluate condition with a Lua expression. Substitutions already performed. local function cond_eval(cond) local func, err if setfenv then func, err = loadstring("return "..cond, "=expr") else -- No globals. All unknown identifiers evaluate to nil. func, err = load("return "..cond, "=expr", "t", {}) end if func then if setfenv then setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil. end local ok, res = pcall(func) if ok then if res == 0 then return false end -- Oh well. return not not res end err = res end wfatal("bad condition: "..err) end -- Skip statements until next conditional pseudo-opcode at the same level. local function stmtskip() local dostmt_save = dostmt local lvl = 0 dostmt = function(stmt) local op = match(stmt, "^%s*(%S+)") if op == ".if" then lvl = lvl + 1 elseif lvl ~= 0 then if op == ".endif" then lvl = lvl - 1 end elseif op == ".elif" or op == ".else" or op == ".endif" then dostmt = dostmt_save dostmt(stmt) end end end -- Pseudo-opcodes for conditional assembly. map_coreop[".if_1"] = function(params) if not params then return "condition" end local lvl = condlevel + 1 local res = cond_eval(params[1]) condlevel = lvl condstack[lvl] = res if not res then stmtskip() end end map_coreop[".elif_1"] = function(params) if not params then return "condition" end if condlevel == 0 then wfatal(".elif without .if") end local lvl = condlevel local res = condstack[lvl] if res then if res == "else" then wfatal(".elif after .else") end else res = cond_eval(params[1]) if res then condstack[lvl] = res return end end stmtskip() end map_coreop[".else_0"] = function(params) if condlevel == 0 then wfatal(".else without .if") end local lvl = condlevel local res = condstack[lvl] condstack[lvl] = "else" if res then if res == "else" then wfatal(".else after .else") end stmtskip() end end map_coreop[".endif_0"] = function(params) local lvl = condlevel if lvl == 0 then wfatal(".endif without .if") end condlevel = lvl - 1 end -- Check for unfinished conditionals. local function checkconds() if g_errcount ~= "fatal" and condlevel ~= 0 then wprinterr(g_fname, ":*: error: unbalanced conditional\n") end end ------------------------------------------------------------------------------ -- Search for a file in the given path and open it for reading. local function pathopen(path, name) local dirsep = package and match(package.path, "\\") and "\\" or "/" for _,p in ipairs(path) do local fullname = p == "" and name or p..dirsep..name local fin = io.open(fullname, "r") if fin then g_fname = fullname return fin end end end -- Include a file. map_coreop[".include_1"] = function(params) if not params then return "filename" end local name = params[1] -- Save state. Ugly, I know. but upvalues are fast. local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent -- Read the included file. local fatal = readfile(pathopen(g_opt.include, name) or wfatal("include file `"..name.."' not found")) -- Restore state. g_synclineno = -1 g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi if fatal then wfatal("in include file") end end -- Make .include and conditionals initially available, too. map_initop[".include_1"] = map_coreop[".include_1"] map_initop[".if_1"] = map_coreop[".if_1"] map_initop[".elif_1"] = map_coreop[".elif_1"] map_initop[".else_0"] = map_coreop[".else_0"] map_initop[".endif_0"] = map_coreop[".endif_0"] ------------------------------------------------------------------------------ -- Support variables for macros. local mac_capture, mac_lineno, mac_name local mac_active = {} local mac_list = {} -- Pseudo-opcode to define a macro. map_coreop[".macro_*"] = function(mparams) if not mparams then return "name [, params...]" end -- Split off and validate macro name. local name = remove(mparams, 1) if not name then werror("missing macro name") end if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then wfatal("bad macro name `"..name.."'") end -- Validate macro parameter names. local mdup = {} for _,mp in ipairs(mparams) do if not match(mp, "^[%a_][%w_]*$") then wfatal("bad macro parameter name `"..mp.."'") end if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end mdup[mp] = true end -- Check for duplicate or recursive macro definitions. local opname = name.."_"..#mparams if map_op[opname] or map_op[name.."_*"] then wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)") end if mac_capture then wfatal("recursive macro definition") end -- Enable statement capture. local lines = {} mac_lineno = g_lineno mac_name = name mac_capture = function(stmt) -- Statement capture function. -- Stop macro definition with .endmacro pseudo-opcode. if not match(stmt, "^%s*.endmacro%s*$") then lines[#lines+1] = stmt return end mac_capture = nil mac_lineno = nil mac_name = nil mac_list[#mac_list+1] = opname -- Add macro-op definition. map_op[opname] = function(params) if not params then return mparams, lines end -- Protect against recursive macro invocation. if mac_active[opname] then wfatal("recursive macro invocation") end mac_active[opname] = true -- Setup substitution map. local subst = {} for i,mp in ipairs(mparams) do subst[mp] = params[i] end local mcom if g_opt.maccomment and g_opt.comment then mcom = " MACRO "..name.." ("..#mparams..")" wcomment("{"..mcom) end -- Loop through all captured statements for _,stmt in ipairs(lines) do -- Substitute macro parameters. local st = gsub(stmt, "[%w_]+", subst) st = definesubst(st) st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b. if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end -- Emit statement. Use a protected call for better diagnostics. local ok, err = pcall(dostmt, st) if not ok then -- Add the captured statement to the error. wprinterr(err, "\n", g_indent, "| ", stmt, "\t[MACRO ", name, " (", #mparams, ")]\n") end end if mcom then wcomment("}"..mcom) end mac_active[opname] = nil end end end -- An .endmacro pseudo-opcode outside of a macro definition is an error. map_coreop[".endmacro_0"] = function(params) wfatal(".endmacro without .macro") end -- Dump all macros and their contents (with -PP only). local function dumpmacros(out, lvl) sort(mac_list) out:write("Macros:\n") for _,opname in ipairs(mac_list) do local name = sub(opname, 1, -3) local params, lines = map_op[opname]() out:write(format(" %-20s %s\n", name, concat(params, ", "))) if lvl > 1 then for _,line in ipairs(lines) do out:write(" |", line, "\n") end out:write("\n") end end out:write("\n") end -- Check for unfinished macro definitions. local function checkmacros() if mac_capture then wprinterr(g_fname, ":", mac_lineno, ": error: unfinished .macro `", mac_name ,"'\n") end end ------------------------------------------------------------------------------ -- Support variables for captures. local cap_lineno, cap_name local cap_buffers = {} local cap_used = {} -- Start a capture. map_coreop[".capture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end if cap_name then wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno) end cap_name = name cap_lineno = g_lineno -- Create or continue a capture buffer and start the output line capture. local buf = cap_buffers[name] if not buf then buf = {}; cap_buffers[name] = buf end g_capbuffer = buf g_synclineno = 0 end -- Stop a capture. map_coreop[".endcapture_0"] = function(params) wflush() if not cap_name then wfatal(".endcapture without a valid .capture") end cap_name = nil cap_lineno = nil g_capbuffer = nil g_synclineno = 0 end -- Dump a capture buffer. map_coreop[".dumpcapture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end cap_used[name] = true wline(function(out) local buf = cap_buffers[name] if buf then wdumplines(out, buf) end end) g_synclineno = 0 end -- Dump all captures and their buffers (with -PP only). local function dumpcaptures(out, lvl) out:write("Captures:\n") for name,buf in pairs(cap_buffers) do out:write(format(" %-20s %4s)\n", name, "("..#buf)) if lvl > 1 then local bar = rep("=", 76) out:write(" ", bar, "\n") for _,line in ipairs(buf) do out:write(" ", line, "\n") end out:write(" ", bar, "\n\n") end end out:write("\n") end -- Check for unfinished or unused captures. local function checkcaptures() if cap_name then wprinterr(g_fname, ":", cap_lineno, ": error: unfinished .capture `", cap_name,"'\n") return end for name in pairs(cap_buffers) do if not cap_used[name] then wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n") end end end ------------------------------------------------------------------------------ -- Pseudo-opcode to define code sections. -- TODO: Data sections, BSS sections. Needs extra C code and API. map_coreop[".section_*"] = function(params) if not params then return "name..." end if #map_sections > 0 then werror("duplicate section definition") end wflush() for sn,name in ipairs(params) do local opname = "."..name.."_0" if not match(name, "^[%a][%w_]*$") or map_op[opname] or map_op["."..name.."_*"] then werror("bad section name `"..name.."'") end map_sections[#map_sections+1] = name if g_opt.lang == "lua" then wline(format("local DASM_SECTION_%s\t= %d", upper(name), sn-1)) else wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1)) end map_op[opname] = function(params) g_arch.section(sn-1) end end if g_opt.lang == "lua" then wline(format("local DASM_MAXSECTION\t= %d", #map_sections)) else wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections)) end end -- Dump all sections. local function dumpsections(out, lvl) out:write("Sections:\n") for _,name in ipairs(map_sections) do out:write(format(" %s\n", name)) end out:write("\n") end ------------------------------------------------------------------------------ -- Replacement for customized Lua, which lacks the package library. local prefix = "" if not require then function require(name) local fp = assert(io.open(prefix..name..".lua")) local s = fp:read("*a") assert(fp:close()) return assert(loadstring(s, "@"..name..".lua"))() end end -- Load architecture-specific module. local function loadarch(arch) if not match(arch, "^[%w_]+$") then return "bad arch name" end local ok, m_arch = pcall(require, "dasm_"..arch) if not ok then return "cannot load module: "..m_arch end g_arch = m_arch wflush = m_arch.passcb(wline, werror, wfatal, wwarn) m_arch.setup(arch, g_opt) local arch_map_op arch_map_op, map_def = m_arch.mergemaps(map_coreop, map_def) map_op = setmetatable(map_op, { __index = arch_map_op }) end -- Dump architecture description. function opt_map.dumparch(args) local name = optparam(args) if not g_arch then local err = loadarch(name) if err then opterror(err) end end local t = {} for name in pairs(map_coreop) do t[#t+1] = name end for name in pairs(map_op) do t[#t+1] = name end sort(t) local out = stdout local _arch = g_arch._info out:write(format("%s version %s, released %s, %s\n", _info.name, _info.version, _info.release, _info.url)) g_arch.dumparch(out) local pseudo = true out:write("Pseudo-Opcodes:\n") for _,sname in ipairs(t) do local name, nparam = match(sname, "^(.+)_([0-9%*])$") if name then if pseudo and sub(name, 1, 1) ~= "." then out:write("\nOpcodes:\n") pseudo = false end local f = map_op[sname] local s if nparam ~= "*" then nparam = nparam + 0 end if nparam == 0 then s = "" elseif type(f) == "string" then s = map_op[".template__"](nil, f, nparam) else s = f(nil, nparam) end if type(s) == "table" then for _,s2 in ipairs(s) do out:write(format(" %-12s %s\n", name, s2)) end else out:write(format(" %-12s %s\n", name, s)) end end end out:write("\n") exit(0) end -- Pseudo-opcode to set the architecture. -- Only initially available (map_op is replaced when called). map_initop[".arch_1"] = function(params) if not params then return "name" end local err = loadarch(params[1]) if err then wfatal(err) end if g_opt.lang == "lua" then wline(format("if dasm._VERSION ~= %d then", _info.vernum)) wline(' error("Version mismatch between DynASM and included encoding engine")') wline("end") else wline(format("#if DASM_VERSION != %d", _info.vernum)) wline('#error "Version mismatch between DynASM and included encoding engine"') wline("#endif") end end -- Dummy .arch pseudo-opcode to improve the error report. map_coreop[".arch_1"] = function(params) if not params then return "name" end if g_arch._info.arch ~= params[1] then wfatal("invalid .arch statement. arch already loaded: `", g_arch._info.arch, "`.") end end ------------------------------------------------------------------------------ -- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'. map_coreop[".nop_*"] = function(params) if not params then return "[ignored...]" end end -- Pseudo-opcodes to raise errors. map_coreop[".error_1"] = function(params) if not params then return "message" end werror(params[1]) end map_coreop[".fatal_1"] = function(params) if not params then return "message" end wfatal(params[1]) end -- Dump all user defined elements. local function dumpdef(out) local lvl = g_opt.dumpdef if lvl == 0 then return end dumpsections(out, lvl) dumpdefines(out, lvl) if g_arch then g_arch.dumpdef(out, lvl) end dumpmacros(out, lvl) dumpcaptures(out, lvl) end ------------------------------------------------------------------------------ -- Helper for splitstmt. local splitlvl local function splitstmt_one(c) if c == "(" then splitlvl = ")"..splitlvl elseif c == "[" then splitlvl = "]"..splitlvl elseif c == "{" then splitlvl = "}"..splitlvl elseif c == ")" or c == "]" or c == "}" then if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end splitlvl = sub(splitlvl, 2) elseif splitlvl == "" then return " \0 " end return c end -- Split statement into (pseudo-)opcode and params. local function splitstmt(stmt) -- Convert label with trailing-colon into .label statement. local label = match(stmt, "^%s*(.+):%s*$") if label then return ".label", {label} end -- Split at commas and equal signs, but obey parentheses and brackets. splitlvl = "" stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one) if splitlvl ~= "" then werror("unbalanced () or []") end -- Split off opcode. local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$") if not op then werror("bad statement syntax") end -- Split parameters. local params = {} for p in gmatch(other, "%s*(%Z+)%z?") do params[#params+1] = gsub(p, "%s+$", "") end if #params > 16 then werror("too many parameters") end params.op = op return op, params end -- Process a single statement. dostmt = function(stmt) -- Ignore empty statements. if match(stmt, "^%s*$") then return end -- Capture macro defs before substitution. if mac_capture then return mac_capture(stmt) end stmt = definesubst(stmt) -- Emit C code without parsing the line. if sub(stmt, 1, 1) == "|" then local tail = sub(stmt, 2) wflush() if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end return end -- Split into (pseudo-)opcode and params. local op, params = splitstmt(stmt) -- Get opcode handler (matching # of parameters or generic handler). local f = map_op[op.."_"..#params] or map_op[op.."_*"] if not f then if not g_arch then wfatal("first statement must be .arch") end -- Improve error report. for i=0,9 do if map_op[op.."_"..i] then werror("wrong number of parameters for `"..op.."'") end end werror("unknown statement `"..op.."'") end -- Call opcode handler or special handler for template strings. if type(f) == "string" then map_op[".template__"](params, f) else f(params) end end -- Process a single line. local function doline(line) if g_opt.flushline then wflush() end -- Assembler line? local indent, aline = match(line, "^(%s*)%|(.*)$") if not aline then -- No, plain C code line, need to flush first. wflush() wsync() wline(line, false) return end g_indent = indent -- Remember current line indentation. -- Emit C code (even from macros). Avoids echo and line parsing. if sub(aline, 1, 1) == "|" then if not mac_capture then wsync() elseif g_opt.comment then wsync() wcomment(aline) end dostmt(aline) return end -- Echo assembler line as a comment. if g_opt.comment then wsync() wcomment(aline) end -- Strip assembler comments. aline = gsub(aline, "//.*$", "") if g_opt.lang == "lua" then aline = gsub(aline, "%-%-.*$", "") end -- Split line into statements at semicolons. if match(aline, ";") then for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end else dostmt(aline) end end ------------------------------------------------------------------------------ -- Write DynASM header. local function dasmhead(out) if not g_opt.comment then return end if g_opt.lang == "lua" then out:write(format([[ -- -- This file has been pre-processed with DynASM. -- %s -- DynASM version %s, DynASM %s version %s -- DO NOT EDIT! The original file is in "%s". -- ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname)) else out:write(format([[ /* ** This file has been pre-processed with DynASM. ** %s ** DynASM version %s, DynASM %s version %s ** DO NOT EDIT! The original file is in "%s". */ ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname)) end end -- Read input file. readfile = function(fin) -- Process all lines. for line in fin:lines() do g_lineno = g_lineno + 1 g_curline = line local ok, err = pcall(doline, line) if not ok and wprinterr(err, "\n") then return true end end wflush() -- Close input file. assert(fin == stdin or fin:close()) end -- Write output file. local function writefile(outfile) local fout -- Open output file. if outfile == nil or outfile == "-" then fout = stdout elseif type(outfile) == "string" then fout = assert(io.open(outfile, "w")) else fout = outfile end -- Write all buffered lines wdumplines(fout, g_wbuffer) -- Close output file. assert(fout == stdout or fout:close()) -- Optionally dump definitions. dumpdef(fout == stdout and stderr or stdout) end -- Translate an input file to an output file. local function translate(infile, outfile) -- Put header. wline(dasmhead) -- Read input file. local fin if infile == "-" then g_fname = "(stdin)" fin = stdin elseif type(infile) == "string" then g_fname = infile fin = assert(io.open(infile, "r")) else g_fname = "=(translate)" fin = infile end readfile(fin) -- Check for errors. if not g_arch then wprinterr(g_fname, ":*: error: missing .arch directive\n") end checkconds() checkmacros() checkcaptures() if g_errcount ~= 0 then stderr:write(g_fname, ":*: info: ", g_errcount, " error", (type(g_errcount) == "number" and g_errcount > 1) and "s" or "", " in input file -- no output file generated.\n") dumpdef(stderr) exit(1) end -- Write output file. writefile(outfile) end ------------------------------------------------------------------------------ -- Print help text. function opt_map.help() stdout:write("DynASM -- ", _info.description, ".\n") stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n") stdout:write[[ Usage: dynasm [OPTION]... INFILE.dasc|INFILE.dasl|- -h, --help Display this help text. -V, --version Display version and copyright information. -o, --outfile FILE Output file name (default is stdout). -I, --include DIR Add directory to the include search path. -l, --lang C|Lua Generate C or Lua code (default C for dasc, Lua for dasl). -c, --ccomment Use /* */ comments for assembler lines. -C, --cppcomment Use // comments for assembler lines (default). -N, --nocomment Suppress assembler lines in output. -M, --maccomment Show macro expansions as comments (default off). -L, --nolineno Suppress CPP line number information in output. -F, --flushline Flush action list for every line. -D NAME[=SUBST] Define a substitution. -U NAME Undefine a substitution. -P, --dumpdef Dump defines, macros, etc. Repeat for more output. -A, --dumparch ARCH Load architecture ARCH and dump description. ]] exit(0) end -- Print version information. function opt_map.version() stdout:write(format("%s version %s, released %s\n%s\n\n%s", _info.name, _info.version, _info.release, _info.url, _info.copyright)) exit(0) end -- Misc. options. function opt_map.lang(args) g_opt.lang = optparam(args):lower() end function opt_map.outfile(args) g_opt.outfile = optparam(args) end function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end function opt_map.nocomment() g_opt.comment = false end function opt_map.maccomment() g_opt.maccomment = true end function opt_map.nolineno() g_opt.cpp = false end function opt_map.flushline() g_opt.flushline = true end function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end ------------------------------------------------------------------------------ -- Short aliases for long options. local opt_alias = { h = "help", ["?"] = "help", V = "version", o = "outfile", I = "include", l = "lang", c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment", L = "nolineno", F = "flushline", P = "dumpdef", A = "dumparch", } -- Parse single option. local function parseopt(opt, args) opt_current = #opt == 1 and "-"..opt or "--"..opt local f = opt_map[opt] or opt_map[opt_alias[opt]] if not f then opterror("unrecognized option `", opt_current, "'. Try `--help'.\n") end f(args) end local languages = {c = true, lua = true} local langext = {dasc = "c", dasl = "lua"} --Set language options (Lua or C code gen) based on file extension. local function setlang(infile) -- Infer language from file extension, if `lang` not set. if not g_opt.lang and type(infile) == "string" then g_opt.lang = langext[match(infile, "%.([^%.]+)$")] or "c" end -- Check that the `lang` option is valid. if not languages[g_opt.lang] then opterror("invalid language `", tostring(g_opt.lang), "`.") end -- Adjust comment options for Lua mode. if g_opt.lang == "lua" then if g_opt.comment then g_opt.cpp = false g_opt.comment = "--|" g_opt.endcomment = "" end -- Set initial defines only available in Lua mode. local ffi = require("ffi") map_def.ARCH = ffi.arch --for `.arch ARCH` map_def[upper(ffi.arch)] = 1 --for `.if X86 ...` map_def.OS = ffi.os --for `.if OS == 'Windows'` map_def[upper(ffi.os)] = 1 --for `.if WINDOWS ...` end end -- Parse arguments. local function parseargs(args) --Reset globals. reset() -- Process all option arguments. args.argn = 1 repeat local a = args[args.argn] if not a then break end local lopt, opt = match(a, "^%-(%-?)(.+)") if not opt then break end args.argn = args.argn + 1 if lopt == "" then -- Loop through short options. for o in gmatch(opt, ".") do parseopt(o, args) end else -- Long option. parseopt(opt, args) end until false -- Check for proper number of arguments. local nargs = #args - args.argn + 1 if nargs ~= 1 then if nargs == 0 then if g_opt.dumpdef > 0 then return dumpdef(stdout) end end opt_map.help() end local infile = args[args.argn] -- Set language options. setlang(infile) -- Translate a single input file to a single output file -- TODO: Handle multiple files? translate(infile, g_opt.outfile) end ------------------------------------------------------------------------------ if ... == "dynasm" then -- use as module -- Make a reusable translate() function with support for setting options. local translate = function(infile, outfile, opt) reset() update(g_opt, opt) setlang(infile) if g_opt.subst then for name, subst in pairs(g_opt.subst) do map_def[name] = tostring(subst) end end translate(infile, outfile) end -- Dummy file:close() method. local function dummyclose() return true end -- Create a pseudo-file object that implements the file:lines() method -- which reads data from a string. local function string_infile(s) local lines = function() local term = match(s, "\r\n") and "\r\n" or match(s, "\r") and "\r" or match(s, "\n") and "\n" or "" return gmatch(s, "([^\n\r]*)"..term) end return {lines = lines, close = dummyclose} end -- Create a pseudo-file object that implements the file:write() method -- which forwards each non-empty value to a function. local function func_outfile(func) local function write(_, ...) for i = 1, select('#', ...) do local v = select(i, ...) assert(type(v) == "string" or type(v) == "number", "invalid value") local s = tostring(v) if #s > 0 then func(s) end end return true end return {write = write, close = dummyclose} end -- Create a pseudo-file object that accumulates writes to a table. local function table_outfile(t) return func_outfile(function(s) t[#t+1] = s end) end -- Translate an input file to a string. local function translate_tostring(infile, opt) local t = {} translate(infile, table_outfile(t), opt) return table.concat(t) end -- Create an iterator that translates an input file -- and returns the translated file in chunks. local function translate_toiter(infile, opt) return coroutine.wrap(function() translate(infile, func_outfile(coroutine.yield), opt) end) end -- Load a dasl file and return it as a Lua chunk. local function dasl_loadfile(infile, opt) local opt = update({lang = "lua"}, opt) local read = translate_toiter(infile, opt) local filename = type(infile) == "string" and infile or "=(load)" return load(read, filename) end -- Load a dasl string and return it as a Lua chunk. local function dasl_loadstring(s, opt) return dasl_loadfile(string_infile(s), opt) end -- Register a module loader for *.dasl files. insert(package.loaders, function(modname) local daslpath = gsub(gsub(package.path, "%.lua;", ".dasl;"), "%.lua$", ".dasl") local path, reason = package.searchpath(modname, daslpath) if not path then return reason end return function() local chunk = assert(dasl_loadfile(path, {comment = false})) return chunk(modname) end end) -- Make and return the DynASM API. return { --low-level intf. translate = translate, string_infile = string_infile, func_outfile = func_outfile, table_outfile = table_outfile, translate_tostring = translate_tostring, translate_toiter = translate_toiter, --hi-level intf. loadfile = dasl_loadfile, loadstring = dasl_loadstring, } else -- use as standalone script -- Add the directory dynasm.lua resides in to the Lua module search path. local arg = arg if arg and arg[0] then prefix = match(arg[0], "^(.*[/\\])") if package and prefix then package.path = prefix.."?.lua;"..package.path end end -- Start DynASM. parseargs{...} end ------------------------------------------------------------------------------
apache-2.0
Xamla/torch-pcl
PointCloud.lua
1
10732
local ffi = require 'ffi' local torch = require 'torch' local utils = require 'pcl.utils' local pcl = require 'pcl.PointTypes' local PointCloud = torch.class('pcl.PointCloud', pcl) local func_by_type = {} local function init() local PointCloud_method_names = { 'new', 'clone', 'delete', 'getHeaderSeq', 'setHeaderSeq', 'getHeaderStamp_sec', 'getHeaderStamp_nsec', 'setHeaderStamp', 'getHeaderFrameId', 'setHeaderFrameId', 'getWidth', 'getHeight', 'getIsDense', 'setIsDense', 'at1D', 'at2D', 'clear', 'reserve', 'size', 'empty', 'isOrganized', 'push_back', 'insert', 'erase', 'points', 'sensorOrientation', 'sensorOrigin', 'transform', 'transformWithNormals', 'getMinMax3D', 'compute3DCentroid', 'computeCovarianceMatrix', 'add', 'fromPCLPointCloud2', 'toPCLPointCloud2', 'loadPCDFile', 'savePCDFile', 'loadPLYFile', 'savePLYFile', 'loadOBJFile', 'savePNGFile', 'readXYZfloat', 'readRGBAfloat', 'readRGBAbyte', 'writeRGBAfloat', 'writeRGBAbyte', 'writeRGBfloat', 'writeRGBbyte', 'addNormals', 'copyXYZ', 'copyXYZI', 'copyXYZRGBA', 'copyXYZNormal', 'copyXYZINormal', 'copyXYZRGBNormal', 'copyNormal' } local supported_types = {} supported_types[pcl.PointXYZ] = 'XYZ' supported_types[pcl.PointXYZI] = 'XYZI' supported_types[pcl.PointXYZRGBA] = 'XYZRGBA' supported_types[pcl.PointNormal] = 'XYZNormal' supported_types[pcl.PointXYZINormal] = 'XYZINormal' supported_types[pcl.PointXYZRGBNormal] = 'XYZRGBNormal' supported_types[pcl.Normal] = 'Normal' supported_types[pcl.FPFHSignature33] = 'FPFHSignature33' supported_types[pcl.VFHSignature308] = 'VFHSignature308' supported_types[pcl.Boundary] = 'Boundary' supported_types[pcl.Label] = 'Label' for k,v in pairs(supported_types) do func_by_type[k] = utils.create_typed_methods('pcl_PointCloud_TYPE_KEY_', PointCloud_method_names, v) end func_by_type[pcl.Normal] = utils.create_typed_methods('pcl_PointCloud_TYPE_KEY_', PointCloud_method_names, 'Normal') end init() function PointCloud:__init(pointType, width, height) if type(pointType) == 'number' then width = pointType pointType = pcl.PointXYZ end pointType = pcl.pointType(pointType) width = width or 0 rawset(self, 'f', func_by_type[pointType]) self.pointType = pointType if torch.isTensor(width) then width = width:float() local sz = width:size() local w,h if width:nDimension() == 3 then w, h = sz[2], sz[1] elseif width:nDimension() == 2 then w, h = sz[1], 1 end self.o = self.f.new(w, h) self:points():copy(width) elseif type(width) == 'cdata' then self.o = width else height = height or width and width > 0 and 1 or 0 self.o = self.f.new(width, height) end end function PointCloud:cdata() return self.o end function PointCloud:readXYZ(t) local t = t or torch.FloatTensor() if torch.type(t) == 'torch.FloatTensor' then self.f.readXYZfloat(self.o, t:cdata()) else error('torch.FloatTensor expected') end return t end function PointCloud:readRGBA(t) local t = t or torch.FloatTensor() if torch.type(t) == 'torch.FloatTensor' then self.f.readRGBAfloat(self.o, t:cdata()) elseif torch.type(t) == 'torch.ByteTensor' then self.f.readRGBAbyte(self.o, t:cdata()) else error('unsupported tensor type') end return t end function PointCloud:writeRGBA(t) if torch.type(t) == 'torch.FloatTensor' then self.f.writeRGBAfloat(self.o, t:cdata()) elseif torch.type(t) == 'torch.ByteTensor' then self.f.writeRGBAbyte(self.o, t:cdata()) else error('unsupported tensor type') end end function PointCloud:writeRGB(t, setAlpha, alpha) if torch.type(t) == 'torch.FloatTensor' then self.f.writeRGBfloat(self.o, t:cdata(), setAlpha or false, alpha or 1) elseif torch.type(t) == 'torch.ByteTensor' then self.f.writeRGBbyte(self.o, t:cdata(), setAlpha or false, alpha or 255) else error('unsupported tensor type') end end function PointCloud:clone() local clone = self.f.clone(self.o) return PointCloud.new(self.pointType, clone) end function PointCloud:__index(idx) local v = rawget(self, idx) if not v then v = PointCloud[idx] if not v then local f, o = rawget(self, 'f'), rawget(self, 'o') if type(idx) == 'number' then v = f.at1D(o, idx-1) elseif type(idx) == 'table' then v = f.at2D(o, idx[1]-1, idx[2]-1) end end end return v end function PointCloud:__newindex(idx, v) local f, o = rawget(self, 'f'), rawget(self, 'o') if type(idx) == 'number' then f.at1D(o, idx-1):set(v) elseif type(idx) == 'table' then f.at2D(o, idx[1]-1, idx[2]-1):set(v) else rawset(self, idx, v) end end function PointCloud:__len() return self:size() end function PointCloud:getHeaderSeq() return self.f.getHeaderSeq(self.o) end function PointCloud:setHeaderSeq(value) self.f.setHeaderSeq(self.o, value) end function PointCloud:getHeaderStamp() return self.f.getHeaderStamp_sec(self.o), self.f.getHeaderStamp_nsec(self.o) end function PointCloud:setHeaderStamp(sec, nsec) self.f.setHeaderStamp(self.o, sec, nsec) end function PointCloud:getHeaderFrameId() return ffi.string(self.f.getHeaderFrameId(self.o)) end function PointCloud:setHeaderFrameId(value) self.f.setHeaderFrameId(self.o, value or '') end function PointCloud:getWidth() return self.f.getWidth(self.o) end function PointCloud:getHeight() return self.f.getHeight(self.o) end function PointCloud:getIsDense() return self.f.getIsDense(self.o) end function PointCloud:setIsDense(value) self.f.setIsDense(self.o, value) end function PointCloud:clear() self.f.clear(self.o) end function PointCloud:reserve(n) self.f.reserve(self.o, n) end function PointCloud:size() return self.f.size(self.o); end function PointCloud:empty() return self.f.empty(self.o) end function PointCloud:isOrganized() return self.f.isOrganized(self.o) end function PointCloud:push_back(pt) self.f.push_back(self.o, pt); end function PointCloud:insert(pos, pt, n) self.f.insert(self.o, pos-1, n or 1, pt) end function PointCloud:erase(begin_pos, end_pos) self.f.erase(self.o, begin_pos-1, (end_pos or begin_pos + 1)-1) end function PointCloud:points() local t = torch.FloatTensor() local buf = self.f.points(self.o) t:cdata().storage = buf.storage t:resize(buf.height, buf.width, buf.dim) return t end function PointCloud:pointsXYZ() return self:points()[{{},{},{1,3}}] end function PointCloud:sensorOrigin() local t = torch.FloatTensor() local s = self.f.sensorOrigin(self.o) t:cdata().storage = s t:resize(4) return t end function PointCloud:sensorOrientation() local t = torch.FloatTensor() local s = self.f.sensorOrientation(self.o) t:cdata().storage = s t:resize(4) return t end function PointCloud:transform(mat, output) if torch.isTypeOf(mat, pcl.affine.Transform) then mat = mat:totensor() end output = output or self if self.pointType.hasNormal then self.f.transformWithNormals(self.o, mat:cdata(), output:cdata()) else self.f.transform(self.o, mat:cdata(), output:cdata()) end return output end function PointCloud:getMinMax3D() local min, max = self.pointType(), self.pointType() self.f.getMinMax3D(self.o, min, max) return min, max end function PointCloud:compute3DCentroid() local centroid = torch.FloatTensor() self.f.compute3DCentroid(self.o, centroid:cdata()) return centroid end function PointCloud:computeCovarianceMatrix(centroid) local covariance = torch.FloatTensor() if not centroid then centroid = self:compute3DCentroid() end self.f.computeCovarianceMatrix(self.o, utils.cdata(centroid), covariance:cdata()) return covariance, centroid end function PointCloud:add(other) self.f.add(self.o, other.o) end function PointCloud:removeNaN(output, removed_indices) if torch.isTypeOf(output, pcl.Indices) then return pcl.filter.removeNaNFromPointCloud(self, nil, output) else return pcl.filter.removeNaNFromPointCloud(self, output or self, removed_indices) end end function PointCloud:fromPCLPointCloud2(src_msg) if not torch.isTypeOf(src_msg, pcl.PCLPointCloud2) then error("Invalid type of argument 'src_msg': pcl.PCLPointCloud2 expected.") end self.f.fromPCLPointCloud2(self.o, src_msg:cdata()) end function PointCloud:toPCLPointCloud2(dst_msg) dst_msg = dst_msg or pcl.PCLPointCloud2() self.f.toPCLPointCloud2(self.o, dst_msg:cdata()) return dst_msg end function PointCloud:loadPCDFile(fn) return self.f.loadPCDFile(self.o, fn) end function PointCloud:savePCDFile(fn, binary) return self.f.savePCDFile(self.o, fn, binary or true) end function PointCloud:loadPLYFile(fn) return self.f.loadPLYFile(self.o, fn) end function PointCloud:savePLYFile(fn, binary) return self.f.savePLYFile(self.o, fn, binary or true) end function PointCloud:loadOBJFile(fn) return self.f.loadOBJFile(self.o, fn) end function PointCloud:savePNGFile(fn, field_name) return self.f.savePNGFile(self.o, fn, field_name or 'rgb') end function PointCloud:addNormals(normals, output) if not output then output = pcl.PointCloud(utils.getNormalTypeFor(self.pointType)) end self.f.addNormals(self.o, normals:cdata(), output:cdata()) return output end function PointCloud:__tostring() return string.format('PointCloud<%s> (w: %d, h: %d, organized: %s, dense: %s)', pcl.getPointTypeName(self.pointType), self:getWidth(), self:getHeight(), self:isOrganized(), self:getIsDense() ) end function PointCloud:apply(func) local p = self:points() local count = p:nElement() local data = p:data() local pt = self.pointType() local point_size = ffi.sizeof(pt) local stride = point_size / #pt local j=1 for i=0,count-1,stride do ffi.copy(pt, data + i, point_size) local r = func(pt, j) -- pass point and index to function if r then ffi.copy(data + i, r, point_size) end j = j + 1 end end function PointCloud.copy(cloud_in, indices, cloud_out) if torch.isTypeOf(indices, pcl.PointCloud) then cloud_out = indices indices = nil end if not cloud_out then cloud_out = pcl.PointCloud(cloud_in.pointType) end local copy = cloud_in.f["copy" .. (utils.type_key_map[cloud_out.pointType] or '')] if not copy then print("copy" .. (utils.type_key_map[cloud_out.pointType] or '')) error("Copy to destination point cloud type not supported.") end copy(cloud_in:cdata(), utils.cdata(indices), cloud_out:cdata()) return cloud_out end
bsd-3-clause
Xamla/torch-pcl
EuclideanClusterExtraction.lua
1
2736
local ffi = require 'ffi' local torch = require 'torch' local utils = require 'pcl.utils' local pcl = require 'pcl.PointTypes' local EuclideanClusterExtraction = torch.class('pcl.EuclideanClusterExtraction', pcl) local EuclideanClusterExtraction_func_by_type = {} local function init() local EuclideanClusterExtraction_method_names = { 'new', 'delete', 'EuclideanClusterExtraction_ptr', 'setInputCloud', 'setIndices', 'setSearchMethod_Octree', 'setSearchMethod_KdTree', 'setClusterTolerance', 'getClusterTolerance', 'setMinClusterSize', 'getMinClusterSize', 'setMaxClusterSize', 'getMaxClusterSize', 'extract' } for k,v in pairs(utils.type_key_map) do EuclideanClusterExtraction_func_by_type[k] = utils.create_typed_methods("pcl_EuclideanClusterExtraction_TYPE_KEY_", EuclideanClusterExtraction_method_names, v) end end init() function EuclideanClusterExtraction:__init(pointType) self.pointType = pcl.pointType(pointType or pcl.PointXYZ) self.f = EuclideanClusterExtraction_func_by_type[self.pointType] self.h = self.f.new() self.p = self.f.EuclideanClusterExtraction_ptr(self.h) end function EuclideanClusterExtraction:handle() return self.h end function EuclideanClusterExtraction:EuclideanClusterExtraction_ptr() return self.p end function EuclideanClusterExtraction:setInputCloud(cloud) self.f.setInputCloud(self.p, cloud:cdata()) end function EuclideanClusterExtraction:setIndices(indices) self.f.setIndices(self.p, indices:cdata()) end function EuclideanClusterExtraction:setSearchMethod(search) if torch.isTypeOf(search, pcl.KdTree) then self.f.setSearchMethod_KdTree(self.p, search:cdata()) elseif torch.isTypeOf(search, pcl.Octree) then self.f.setSearchMethod_Octree(self.p, search:cdata()) else error("unsupported search method") end end function EuclideanClusterExtraction:setClusterTolerance(cluster_tolerance) self.f.setClusterTolerance(self.p, cluster_tolerance) end function EuclideanClusterExtraction:getClusterTolerance() return self.f.getClusterTolerance(self.p) end function EuclideanClusterExtraction:setMinClusterSize(min_cluster_size) self.f.setMinClusterSize(self.p, min_cluster_size) end function EuclideanClusterExtraction:getMinClusterSize() return self.f.getMinClusterSize(self.p) end function EuclideanClusterExtraction:setMaxClusterSize(max_cluster_size) self.f.setMaxClusterSize(self.p, max_cluster_size) end function EuclideanClusterExtraction:getMaxClusterSize() return self.f.getMaxClusterSize(self.p) end function EuclideanClusterExtraction:extract(clusters) clusters = clusters or pcl.IndicesVector() self.f.extract(self.p, clusters:cdata()) return clusters end
bsd-3-clause
jackywgw/ntopng_test
scripts/lua/host_top_peers_protocols.lua
10
2411
-- -- (C) 2014-15-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" sendHTTPHeader('application/json') interface.select(ifname) host_info = url2hostinfo(_GET) flows = interface.getFlowPeers(host_info["host"],host_info["vlan"]) tot = 0 peers = {} peers_proto = {} ndpi = {} for key, value in pairs(flows) do flow = flows[key] if(flow.client == _GET["host"]) then peer = flow.server .. '@' .. flow['server.vlan'] else peer = flow.client .. '@' .. flow['client.vlan'] end v = flow.rcvd + flow.sent if(peers[peer] == nil) then peers[peer] = 0 end peers[peer] = peers[peer] + v if(ndpi[flow["proto.ndpi"]] == nil) then ndpi[flow["proto.ndpi"]] = 0 end ndpi[flow["proto.ndpi"]] = ndpi[flow["proto.ndpi"]] + v if(peers_proto[peer] == nil) then peers_proto[peer] = {} end if(peers_proto[peer][flow["proto.ndpi"]] == nil) then peers_proto[peer][flow["proto.ndpi"]] = 0 end peers_proto[peer][flow["proto.ndpi"]] = peers_proto[peer][flow["proto.ndpi"]] + v tot = tot + v end _peers = { } for key, value in pairs(peers) do _peers[value] = key end _ndpi = { } n = 0 for key, value in pairs(ndpi) do _ndpi[value] = key n = n + 1 end -- Print up to this number of entries max_num_peers = 10 print "[\n" num = 0 for value,peer in pairsByKeys(_peers, rev) do if(peers_proto[peer] ~= nil) then n = 0 for value,proto in pairsByKeys(_ndpi, rev) do if(peers_proto[peer][proto] ~= nil) then if((n+num) > 0) then print ",\n" end host = interface.getHostInfo(peer) if(host ~= nil) then if(host["name"] == nil) then host["name"] = ntop.getResolvedAddress(hostinfo2hostkey(host)) end print("\t { \"host\": \"" .. peer .."\", \"name\": \"".. host.name.."\", \"url\": \"<A HREF='"..ntop.getHttpPrefix().."/lua/host_details.lua?host=".. hostinfo2hostkey(host) .."'>"..host.name .."</A>\", \"l7proto\": \"".. proto .."\", \"l7proto_url\": \"<A HREF="..ntop.getHttpPrefix().."/lua/flows_stats.lua?host=".. hostinfo2hostkey(host) .."&application="..proto..">"..proto.."</A>\", \"traffic\": ".. math.log10(peers_proto[peer][proto]) .. " }") n = n + 1 end end end num = num + 1 if(num == max_num_peers) then break end end end print "\n]"
gpl-3.0
Elanis/SciFi-Pack-Addon-Gamemode
gamemodes/scifipack/gamemode/spawnmenu/toolpanel.lua
2
2194
include( 'controlpanel.lua' ) local PANEL = {} AccessorFunc( PANEL, "m_TabID", "TabID" ) --[[--------------------------------------------------------- Name: Paint -----------------------------------------------------------]] function PANEL:Init() self.List = vgui.Create( "DCategoryList", self ) self.List:Dock( LEFT ) self.List:SetWidth( 130 ) self.Content = vgui.Create( "DCategoryList", self ) self.Content:Dock( FILL ) self.Content:DockMargin( 6, 0, 0, 0 ) self:SetWide( 390 ) if ( ScrW() > 1280 ) then self:SetWide( 460 ) end end --[[--------------------------------------------------------- Name: LoadToolsFromTable -----------------------------------------------------------]] function PANEL:LoadToolsFromTable( inTable ) local inTable = table.Copy( inTable ) for k, v in pairs( inTable ) do if ( istable( v ) ) then -- Remove these from the table so we can -- send the rest of the table to the other -- function local Name = v.ItemName local Label = v.Text v.ItemName = nil v.Text = nil self:AddCategory( Name, Label, v ) end end end --[[--------------------------------------------------------- Name: AddCategory -----------------------------------------------------------]] function PANEL:AddCategory( Name, Label, tItems ) local Category = self.List:Add( Label ) Category:SetCookieName( "ToolMenu." .. tostring( Name ) ) local bAlt = true local tools = {} for k, v in pairs( tItems ) do tools[ language.GetPhrase( v.Text:sub( 2 ) ) ] = v end for k, v in SortedPairs( tools ) do local item = Category:Add( v.Text ) item.DoClick = function( button ) spawnmenu.ActivateTool( button.Name ) end item.ControlPanelBuildFunction = v.CPanelFunction item.Command = v.Command item.Name = v.ItemName item.Controls = v.Controls item.Text = v.Text end self:InvalidateLayout() end function PANEL:SetActive( cp ) local kids = self.Content:GetCanvas():GetChildren() for k, v in pairs( kids ) do v:SetVisible( false ) end self.Content:AddItem( cp ) cp:SetVisible( true ) cp:Dock( TOP ) end vgui.Register( "ToolPanel", PANEL, "Panel" )
gpl-2.0
kiarash14/spam
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
xponen/Zero-K
effects/nanobomb.lua
25
1716
-- nanobomb return { ["nanobomb"] = { usedefaultexplosions = false, groundflash = { alwaysvisible = false, circlealpha = 1, circlegrowth = 10, flashalpha = 0.5, flashsize = 100, ttl = 15, color = { [1] = 0, [2] = 1, [3] = 0, }, }, ring = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.9, alwaysvisible = true, colormap = [[0 1 0 0 0 1 0.75 1 0 0.75 0.5 1 0.75 1 0.75 1 0 0 0 0]], directional = false, emitrot = 90, emitrotspread = 5, emitvector = [[0, 1, 0]], gravity = [[0, 0.2, 0]], numparticles = 64, particlelife = 10, particlelifespread = 5, particlesize = 4, particlesizespread = 4, particlespeed = 16, particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 8, sizemod = 0.5, texture = [[smokesmall]], }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.5, color = [[0,1,0.5]], expansionspeed = 15, ttl = 10, }, }, }, }
gpl-2.0
xponen/Zero-K
units/armrock.lua
1
7015
unitDef = { unitname = [[armrock]], name = [[Rocko]], description = [[Skirmisher Bot (Direct-Fire)]], acceleration = 0.32, brakeRate = 0.2, buildCostEnergy = 90, buildCostMetal = 90, buildPic = [[ARMROCK.png]], buildTime = 90, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 -5 0]], collisionVolumeScales = [[26 39 26]], collisionVolumeType = [[CylY]], corpse = [[DEAD]], customParams = { description_bp = [[Robô escaramuçador]], description_de = [[Skirmisher Roboter (Direkt-Feuer)]], description_fi = [[Kahakoitsijarobotti]], description_fr = [[Robot Tirailleur]], description_it = [[Robot Da Scaramuccia]], description_es = [[Robot Escaramuzador]], description_pl = [[Bot harcownik]], helptext = [[The Rocko's low damage, low speed unguided rockets are redeemed by their range. They are most effective in a line formation, firing at maximum range and kiting the enemy. Counter them by attacking them with fast units which can close range and dodge their missiles.]], helptext_bp = [[Rocko é o robô escaramuçador básico de Nova. Seu pouco poder de fogo e a baixa velocidade de seus foguetes s?o compensados por seu alcançe. Eles sao mais efetivos posicionados em linha, atirando da distância máxima. Se protega deles atacando-os com unidades rápidas ou construindo uma barreira a frente de suas defesas.]], helptext_de = [[Rockos geringer Schaden und die geringe Geschwindigkeit der Raketen wird durch seine Reichweite aufgehoben. Sie sind an Fronten sehr effektiv, da sie dort mit maximaler Reichweite agieren können. Kontere sie, indem du schnelle Einheiten schickst oder Verteidigung hinter einer Terraformmauer baust.]], helptext_es = [[El bajo da?o y la baja velocidad de los cohetes sin gu?a del Rocko son redimidos por su alcance. Son m?s efectivos en una l?nea, disparando al m?ximo alcance. Se contrastan atac?ndolos con unidades r?pidas o poiniendo tus defensas detr?s de un muro de terraform.]], helptext_fi = [[Rockon hitaat, ohjaamattomat ja suhteellisen heikot raketit hy?tyv?t pitk?st? kantamastaan. Rockot ovat tehokkaimmillaan riviss?, kaukaisia kohteita ampuessaan. Torju nopealiikkeisill? yksik?ill? tai muokkaamalla maastoa puolustuslinjojen edest?.]], helptext_fr = [[La faible puissance de feux et la lenteur des roquettes non guid?s du Rocko son conpens?es par sa port?e de tire. Ils sont le plus ?fficace en formation de ligne, en tirant ? port?e maximale. Contrez le en attaquant avec des unit?s rapide ou bien placer vos d?fenses derriere un mure t?rraform?.]], helptext_it = [[Il basso danno e la bassa velocita dei razzi non guidati del Rocko riscattati dal suo raggio. Sono al meglio in una linea, attaccando dal suo raggio massimo. Si contrastano attaccandoli con unita veloci, o mettendo le tue difese dietro di un muro di terraform.]], helptext_pl = [[Rocko jest uzbrojony w powolne rakiety, ktore mimo niskich obrazen i braku samonaprowadzania maja duzy zasieg. Najlepiej sprawdzaja sie stojac w linii prostopadlej do celu, atakujac z maksymalnej odleglosci i nie dajac sie zlapac przeciwnikom. Mozna je pokonac lekkimi jednostkami, ktore sa w stanie unikac ich rakiet, dogonic je i zniszczyc.]], modelradius = [[13]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[kbotskirm]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 450, maxSlope = 36, maxVelocity = 2.2, maxWaterDepth = 20, minCloakDistance = 75, modelCenterOffset = [[0 6 0]], movementClass = [[KBOT2]], moveState = 0, noChaseCategory = [[TERRAFORM FIXEDWING SUB]], objectName = [[sphererock.s3o]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:rockomuzzle]], }, }, sightDistance = 523, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 18, turnRate = 2200, upright = true, weapons = { { def = [[BOT_ROCKET]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { BOT_ROCKET = { name = [[Rocket]], areaOfEffect = 48, burnblow = true, cegTag = [[missiletrailredsmall]], craterBoost = 0, craterMult = 0, damage = { default = 180, planes = 180, subs = 9, }, fireStarter = 70, flightTime = 2.45, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[wep_m_ajax.s3o]], noSelfDamage = true, predictBoost = 1, range = 455, reloadtime = 3.8, smokeTrail = true, soundHit = [[weapon/missile/sabot_hit]], soundHitVolume = 8, soundStart = [[weapon/missile/sabot_fire]], soundStartVolume = 7, startVelocity = 190, texture2 = [[darksmoketrail]], tracks = false, turret = true, weaponAcceleration = 190, weaponType = [[MissileLauncher]], weaponVelocity = 190, }, }, featureDefs = { DEAD = { description = [[Wreckage - Rocko]], blocking = true, damage = 450, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, metal = 36, object = [[rocko_d.3ds]], reclaimable = true, reclaimTime = 36, }, HEAP = { description = [[Debris - Rocko]], blocking = false, damage = 450, energy = 0, footprintX = 2, footprintZ = 2, metal = 18, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 18, }, }, } return lowerkeys({ armrock = unitDef })
gpl-2.0
xponen/Zero-K
LuaUI/Widgets/gui_group_recall_fix.lua
6
2942
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Default Group Recall Fix", desc = "Fix to the group recall problem.", author = "msafwan, GoogleFrog", date = "30 Jan 2014", license = "GNU GPL, v2 or later", layer = 1002, handler = true, enabled = true, } end include("keysym.h.lua") -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- options_path = 'Settings/Camera/Control Group Zoom' options_order = { 'enabletimeout', 'timeoutlength'} options = { enabletimeout = { name = "Enable Timeout", type = 'bool', value = true, desc = "When enabled, the key must be pressed twice in quick sucession to zoom to a control group.", }, timeoutlength = { name = "Double Press Speed", type = "number", value = 0.4, min = 0, max = 5, step = 0.1, }, } local spGetUnitGroup = Spring.GetUnitGroup local spGetGroupList = Spring.GetGroupList local spGetTimer = Spring.GetTimer local spDiffTimers = Spring.DiffTimers local spGetSelectedUnits = Spring.GetSelectedUnits local previousGroup = 99 local currentIteration = 1 local previousKey = 99 local previousTime = spGetTimer() local groupNumber = { [KEYSYMS.N_1] = 1, [KEYSYMS.N_2] = 2, [KEYSYMS.N_3] = 3, [KEYSYMS.N_4] = 4, [KEYSYMS.N_5] = 5, [KEYSYMS.N_6] = 6, [KEYSYMS.N_7] = 7, [KEYSYMS.N_8] = 8, [KEYSYMS.N_9] = 9, } local function GroupRecallFix(key, modifier, isRepeat) if (not modifier.ctrl and not modifier.alt and not modifier.meta) then --check key for group. Reference: unit_auto_group.lua by Licho local group if (key ~= nil and groupNumber[key]) then group = groupNumber[key] end if (group ~= nil) then local selectedUnit = spGetSelectedUnits() local groupCount = spGetGroupList() --get list of group with number of units in them -- First check that the selectio and group in question are the same size. if groupCount[group] ~= #selectedUnit then previousKey = key previousTime = spGetTimer() return false end -- Check each unit for membership of the required group for i=1,#selectedUnit do local unitGroup = spGetUnitGroup(selectedUnit[i]) if unitGroup ~= group then previousKey = key previousTime = spGetTimer() return false end end if previousKey == key and (spDiffTimers(spGetTimer(),previousTime) < options.timeoutlength.value) then previousTime = spGetTimer() return false end previousKey = key previousTime = spGetTimer() return true end end end function widget:KeyPress(key, modifier, isRepeat) if options.enabletimeout.value then return GroupRecallFix(key, modifier, isRepeat) end end
gpl-2.0
snail23/snailui
elements/tags.lua
1
3252
-- -- Copyright (C) 2012-2016 Snail <https://github.com/snail23/snailui/> -- -- 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, see <http://www.gnu.org/licenses/>. -- oUF.Tags.Events["SnailUI:DemonicFury"] = "UNIT_POWER" oUF.Tags.Events["SnailUI:EclipseDirection"] = "ECLIPSE_DIRECTION_CHANGE" oUF.Tags.Events["SnailUI:Health"] = "UNIT_HEALTH UNIT_HEAL_PREDICTION" oUF.Tags.Events["SnailUI:Power"] = "UNIT_POWER" oUF.Tags.Events["SnailUI:SmallHealth"] = "UNIT_HEALTH UNIT_HEAL_PREDICTION" oUF.Tags.Methods["SnailUI:DemonicFury"] = function(Unit) return UnitPower("Player", SPELL_POWER_DEMONIC_FURY) end oUF.Tags.Methods["SnailUI:EclipseDirection"] = function(Unit) local Direction = GetEclipseDirection() if Direction == "moon" then return "<-" elseif Direction == "sun" then return "->" end return nil end oUF.Tags.Methods["SnailUI:Health"] = function(Unit) local Health = Trim(GetUnitName(Unit, false)) if math.floor(((UnitHealth(Unit) / UnitHealthMax(Unit)) * 100) + 0.5) < 100 then if UnitGetIncomingHeals(Unit) then if Options.EnableHealthNumbers then Health = ShortNumber(math.min(UnitHealth(Unit) + UnitGetIncomingHeals(Unit), UnitHealthMax(Unit))) else Health = math.floor(((math.min(UnitHealth(Unit) + UnitGetIncomingHeals(Unit), UnitHealthMax(Unit)) / UnitHealthMax(Unit)) * 100) + 0.5) .. "%" end else if Options.EnableHealthNumbers then Health = ShortNumber(UnitHealth(Unit)) else Health = math.floor(((UnitHealth(Unit) / UnitHealthMax(Unit)) * 100) + 0.5) .. "%" end end end if UnitIsDead(Unit) then Health = Trim(GetUnitName(Unit, false), " | Dead") end if UnitIsGhost(Unit) then Health = Trim(GetUnitName(Unit, false), " | Ghost") end if UnitIsAFK(Unit) then Health = Trim(GetUnitName(Unit, false), " | AFK") end if not UnitIsConnected(Unit) then Health = Trim(GetUnitName(Unit, false), " | D/C") end return Health end oUF.Tags.Methods["SnailUI:Power"] = function(Unit) return ShortNumber(UnitPower(Unit)) end oUF.Tags.Methods["SnailUI:SmallHealth"] = function(Unit) local Health = Trim2(GetUnitName(Unit, false)) if math.floor(((UnitHealth(Unit) / UnitHealthMax(Unit)) * 100) + 0.5) < 100 then if UnitGetIncomingHeals(Unit) then Health = math.floor((((UnitHealth(Unit) + UnitGetIncomingHeals(Unit)) / UnitHealthMax(Unit)) * 100) + 0.5) .. "%" else Health = math.floor(((UnitHealth(Unit) / UnitHealthMax(Unit)) * 100) + 0.5) .. "%" end end if UnitIsDead(Unit) then Health = "DEA" end if UnitIsGhost(Unit) then Health = "GHO" end if UnitIsAFK(Unit) then Health = "AFK" end if not UnitIsConnected(Unit) then Health = "D/C" end return Health end
gpl-2.0
Xandaros/Starfall
lua/starfall/libs_sh/vectors.lua
1
7142
SF.Vectors = {} --- Vector type -- @shared local vec_methods, vec_metamethods = SF.Typedef( "Vector" ) local wrap, unwrap = SF.CreateWrapper( vec_metamethods, true, false, debug.getregistry().Vector ) SF.DefaultEnvironment.Vector = function ( ... ) return wrap( Vector( ... ) ) end SF.Vectors.Wrap = wrap SF.Vectors.Unwrap = unwrap SF.Vectors.Methods = vec_methods SF.Vectors.Metatable = vec_metamethods --- __newindex metamethod function vec_metamethods.__newindex ( t, k, v ) if type( k ) == "number" then if k >= 1 and k <= 3 then SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v ) end elseif k == "x" or k == "y" or k == "z" then SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v ) else rawset( t, k, v ) end end local _p = vec_metamethods.__index --- __index metamethod function vec_metamethods.__index ( t, k ) if type( k ) == "number" then if k >= 1 and k <= 3 then return unwrap( t )[ k ] end else if k == "x" or k == "y" or k == "z" then return unwrap( t )[ k ] end end return _p[ k ] end --- tostring metamethod -- @return string representing the vector. function vec_metamethods:__tostring () return unwrap( self ):__tostring() end --- multiplication metamethod -- @param n Scalar to multiply against vector -- @return Scaled vector. function vec_metamethods:__mul ( n ) SF.CheckType( n, "number" ) return wrap( unwrap( self ):__mul( n ) ) end --- division metamethod -- @param n Scalar to divide the Vector by -- @return Scaled vector. function vec_metamethods:__div ( n ) SF.CheckType( n, "number" ) return SF.WrapObject( unwrap( self ):__div( n ) ) end --- add metamethod -- @param v Vector to add -- @return Resultant vector after addition operation. function vec_metamethods:__add ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return wrap( unwrap( self ):__add( unwrap( v ) ) ) end --- sub metamethod -- @param v Vector to subtract -- @return Resultant vector after subtraction operation. function vec_metamethods:__sub ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return wrap( unwrap( self ):__sub( unwrap( v ) ) ) end --- unary minus metamethod -- @returns negated vector. function vec_metamethods:__unm () return wrap( unwrap( self ):__unm() ) end --- equivalence metamethod -- @returns bool if both sides are equal. function vec_metamethods:__eq ( ... ) return SF.Sanitize( unwrap( self ):__eq( SF.Unsanitize( ... ) ) ) end --- Add vector - Modifies self. -- @param v Vector to add -- @return nil function vec_methods:add ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) unwrap( self ):Add( unwrap( v ) ) end --- Get the vector's angle. -- @return Angle function vec_methods:getAngle () return SF.WrapObject( unwrap( self ):Angle() ) end --- Returns the Angle between two vectors. -- @param v Second Vector -- @return Angle function vec_methods:getAngleEx ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return SF.WrapObject( unwrap( self ):AngleEx( unwrap( v ) ) ) end --- Calculates the cross product of the 2 vectors, creates a unique perpendicular vector to both input vectors. -- @param v Second Vector -- @return Vector function vec_methods:cross ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return wrap( unwrap( self ):Cross( unwrap( v ) ) ) end --- Returns the pythagorean distance between the vector and the other vector. -- @param v Second Vector -- @return Number function vec_methods:getDistance ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return unwrap( self ):Distance( unwrap( v ) ) end --- Returns the squared distance of 2 vectors, this is faster Vector:getDistance as calculating the square root is an expensive process. -- @param v Second Vector -- @return Number function vec_methods:getDistanceSqr ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return unwrap( self ):DistToSqr( unwrap( v ) ) end --- Dot product is the cosine of the angle between both vectors multiplied by their lengths. A.B = ||A||||B||cosA. -- @param v Second Vector -- @return Number function vec_methods:dot ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) return unwrap( self ):Dot( unwrap( v ) ) end --- Returns a new vector with the same direction by length of 1. -- @return Vector Normalised function vec_methods:getNormalized () return wrap( unwrap( self ):GetNormalized() ) end --- Is this vector and v equal within tolerance t. -- @param v Second Vector -- @param t Tolerance number. -- @return bool True/False. function vec_methods:isEqualTol ( v, t ) SF.CheckType( v, SF.Types[ "Vector" ] ) SF.CheckType( t, "number" ) return unwrap( self ):IsEqualTol( unwrap( v ), t ) end --- Are all fields zero. -- @return bool True/False function vec_methods:isZero () return unwrap( self ):IsZero() end --- Get the vector's Length. -- @return number Length. function vec_methods:getLength () return unwrap( self ):Length() end --- Get the vector's length squared ( Saves computation by skipping the square root ). -- @return number length squared. function vec_methods:getLengthSqr () return unwrap( self ):LengthSqr() end --- Returns the length of the vector in two dimensions, without the Z axis. -- @return number length function vec_methods:getLength2D () return unwrap( self ):Length2D() end --- Returns the length squared of the vector in two dimensions, without the Z axis. ( Saves computation by skipping the square root ) -- @return number length squared. function vec_methods:getLength2DSqr () return unwrap( self ):Length2DSqr() end --- Scalar Multiplication of the vector. Self-Modifies. -- @param n Scalar to multiply with. -- @return nil function vec_methods:mul ( n ) SF.CheckType( n, "number" ) unwrap( self ):Mul( n ) end --- Set's all vector fields to 0. -- @return nil function vec_methods:setZero () unwrap( self ):Zero() end --- Normalise the vector, same direction, length 0. Self-Modifies. -- @return nil function vec_methods:normalize () unwrap( self ):Normalize() end --- Rotate the vector by Angle a. Self-Modifies. -- @param a Angle to rotate by. -- @return nil. function vec_methods:rotate ( a ) SF.CheckType( a, SF.Types[ "Angle" ] ) unwrap( self ):Rotate( SF.UnwrapObject( a ) ) end --- Copies the values from the second vector to the first vector. Self-Modifies. -- @param v Second Vector -- @return nil function vec_methods:set ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) unwrap( self ):Set( unwrap( v ) ) end --- Subtract v from this Vector. Self-Modifies. -- @param v Second Vector. -- @return nil function vec_methods:sub ( v ) SF.CheckType( v, SF.Types[ "Vector" ] ) unwrap( self ):Sub( unwrap( v ) ) end --- Translates the vectors position into 2D user screen coordinates. Self-Modifies. -- @return nil function vec_methods:toScreen () return unwrap( self ):ToScreen() end --- Returns whenever the given vector is in a box created by the 2 other vectors. -- @param v1 Vector used to define AABox -- @param v2 Second Vector to define AABox -- @return bool True/False. function vec_methods:withinAABox ( v1, v2 ) SF.CheckType( v1, SF.Types[ "Vector" ] ) SF.CheckType( v2, SF.Types[ "Vector" ] ) return unwrap( self ):WithinAABox( unwrap( v1 ), unwrap( v2 ) ) end
bsd-3-clause
Vermeille/kong
spec/03-plugins/06-jwt/03-access_spec.lua
3
11081
local cjson = require "cjson" local helpers = require "spec.helpers" local fixtures = require "spec.03-plugins.06-jwt.fixtures" local jwt_encoder = require "kong.plugins.jwt.jwt_parser" local PAYLOAD = { iss = nil, nbf = os.time(), iat = os.time(), exp = os.time() + 3600 } describe("Plugin: jwt (access)", function() local jwt_secret, base64_jwt_secret, rsa_jwt_secret_1, rsa_jwt_secret_2 local proxy_client, admin_client setup(function() assert(helpers.start_kong()) proxy_client = helpers.proxy_client() admin_client = helpers.admin_client() local api1 = assert(helpers.dao.apis:insert {name = "tests-jwt1", request_host = "jwt.com", upstream_url = "http://mockbin.com"}) local api2 = assert(helpers.dao.apis:insert {name = "tests-jwt2", request_host = "jwt2.com", upstream_url = "http://mockbin.com"}) local api3 = assert(helpers.dao.apis:insert {name = "tests-jwt3", request_host = "jwt3.com", upstream_url = "http://mockbin.com"}) local api4 = assert(helpers.dao.apis:insert {name = "tests-jwt4", request_host = "jwt4.com", upstream_url = "http://mockbin.com"}) local api5 = assert(helpers.dao.apis:insert {name = "tests-jwt5", request_host = "jwt5.com", upstream_url = "http://mockbin.com"}) local consumer1 = assert(helpers.dao.consumers:insert {username = "jwt_tests_consumer"}) local consumer2 = assert(helpers.dao.consumers:insert {username = "jwt_tests_base64_consumer"}) local consumer3 = assert(helpers.dao.consumers:insert {username = "jwt_tests_rsa_consumer_1"}) local consumer4 = assert(helpers.dao.consumers:insert {username = "jwt_tests_rsa_consumer_2"}) assert(helpers.dao.plugins:insert {name = "jwt", config = {}, api_id = api1.id}) assert(helpers.dao.plugins:insert {name = "jwt", config = {uri_param_names = {"token", "jwt"}}, api_id = api2.id}) assert(helpers.dao.plugins:insert {name = "jwt", config = {claims_to_verify = {"nbf", "exp"}}, api_id = api3.id}) assert(helpers.dao.plugins:insert {name = "jwt", config = {key_claim_name = "aud"}, api_id = api4.id}) assert(helpers.dao.plugins:insert {name = "jwt", config = {secret_is_base64 = true}, api_id = api5.id}) jwt_secret = assert(helpers.dao.jwt_secrets:insert {consumer_id = consumer1.id}) base64_jwt_secret = assert(helpers.dao.jwt_secrets:insert {consumer_id = consumer2.id}) rsa_jwt_secret_1 = assert(helpers.dao.jwt_secrets:insert { consumer_id = consumer3.id, algorithm = "RS256", rsa_public_key = fixtures.rs256_public_key }) rsa_jwt_secret_2 = assert(helpers.dao.jwt_secrets:insert { consumer_id = consumer4.id, algorithm = "RS256", rsa_public_key = fixtures.rs256_public_key }) end) teardown(function() if proxy_client then proxy_client:close() end if admin_client then admin_client:close() end helpers.stop_kong() end) describe("refusals", function() it("returns 401 Unauthorized if no JWT is found in the request", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "jwt.com" } }) assert.res_status(401, res) end) it("returns 401 if the claims do not contain the key to identify a secret", function() local jwt = jwt_encoder.encode(PAYLOAD, "foo") local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = assert.res_status(401, res) assert.equal([[{"message":"No mandatory 'iss' in claims"}]], body) end) it("returns 403 Forbidden if the iss does not match a credential", function() PAYLOAD.iss = "123456789" local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = assert.res_status(403, res) assert.equal([[{"message":"No credentials found for given 'iss'"}]], body) end) it("returns 403 Forbidden if the signature is invalid", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, "foo") local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = assert.res_status(403, res) assert.equal([[{"message":"Invalid signature"}]], body) end) it("returns 403 Forbidden if the alg does not match the credential", function() local header = {typ = "JWT", alg = 'RS256'} local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret, 'HS256', header) local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = assert.res_status(403, res) assert.equal([[{"message":"Invalid algorithm"}]], body) end) end) describe("HS256", function() it("proxies the request with token and consumer headers if it was verified", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_consumer", body.headers["x-consumer-username"]) end) it("proxies the request if secret key is stored in a field other than iss", function() PAYLOAD.aud = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt4.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_consumer", body.headers["x-consumer-username"]) end) it("proxies the request if secret is base64", function() PAYLOAD.iss = base64_jwt_secret.key local original_secret = base64_jwt_secret.secret local base64_secret = ngx.encode_base64(base64_jwt_secret.secret) local res = assert(admin_client:send { method = "PATCH", path = "/consumers/jwt_tests_base64_consumer/jwt/"..base64_jwt_secret.id, body = { key = base64_jwt_secret.key, secret = base64_secret}, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(200, res) local jwt = jwt_encoder.encode(PAYLOAD, original_secret) local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt5.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_base64_consumer", body.headers["x-consumer-username"]) end) it("finds the JWT if given in URL parameters", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt="..jwt, headers = { ["Host"] = "jwt.com" } }) assert.res_status(200, res) end) it("finds the JWT if given in a custom URL parameter", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?token="..jwt, headers = { ["Host"] = "jwt2.com" } }) assert.res_status(200, res) end) end) describe("RS256", function() it("verifies JWT", function() PAYLOAD.iss = rsa_jwt_secret_1.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs256_private_key, 'RS256') local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_1", body.headers["x-consumer-username"]) end) it("identifies Consumer", function() PAYLOAD.iss = rsa_jwt_secret_2.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs256_private_key, 'RS256') local authorization = "Bearer "..jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_2", body.headers["x-consumer-username"]) end) end) describe("JWT private claims checks", function() it("requires the checked fields to be in the claims", function() local payload = { iss = jwt_secret.key } local jwt = jwt_encoder.encode(payload, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt="..jwt, headers = { ["Host"] = "jwt3.com" } }) local body = assert.res_status(403, res) assert.equal('{"nbf":"must be a number","exp":"must be a number"}', body) end) it("checks if the fields are valid", function() local payload = { iss = jwt_secret.key, exp = os.time() - 10, nbf = os.time() - 10 } local jwt = jwt_encoder.encode(payload, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt="..jwt, headers = { ["Host"] = "jwt3.com" } }) local body = assert.res_status(403, res) assert.equal('{"exp":"token expired"}', body) end) end) end)
apache-2.0
alexandergall/snabbswitch
src/lib/numa.lua
2
8845
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Call bind_to_cpu(1) to bind the current Snabb process to CPU 1 (for -- example), to bind its memory to the corresponding NUMA node, to -- migrate mapped pages to that NUMA node, and to arrange to warn if -- you use a PCI device from a remote NUMA node. See README.numa.md -- for full API documentation. local S = require("syscall") local pci = require("lib.hardware.pci") local lib = require("core.lib") local bound_cpu local bound_numa_node local node_path = '/sys/devices/system/node/node' local MAX_CPU = 1023 local function warn(fmt, ...) io.stderr:write(string.format("Warning: ".. fmt .. "\n", ...)) io.stderr:flush() end local function die(fmt, ...) error(string.format(fmt, ...)) end local function trim (str) return str:gsub("^%s", ""):gsub("%s$", "") end function parse_cpuset (cpus) local ret = {} cpus = trim(cpus) if #cpus == 0 then return ret end for range in cpus:split(',') do local lo, hi = range:match("^%s*([^%-]*)%s*-%s*([^%-%s]*)%s*$") if lo == nil then lo = range:match("^%s*([^%-]*)%s*$") end assert(lo ~= nil, 'invalid range: '..range) lo = assert(tonumber(lo), 'invalid range begin: '..lo) assert(lo == math.floor(lo), 'invalid range begin: '..lo) if hi ~= nil then hi = assert(tonumber(hi), 'invalid range end: '..hi) assert(hi == math.floor(hi), 'invalid range end: '..hi) assert(lo < hi, 'invalid range: '..range) else hi = lo end for cpu=lo,hi do table.insert(ret, cpu) end end return lib.set(unpack(ret)) end local function parse_cpuset_from_file (path) local fd = assert(io.open(path)) if not fd then return {} end local ret = parse_cpuset(fd:read("*all")) fd:close() return ret end function node_cpus (node) return parse_cpuset_from_file(node_path..node..'/cpulist') end function isolated_cpus (node) return parse_cpuset_from_file('/sys/devices/system/cpu/isolated') end function cpu_get_numa_node (cpu) local node = 0 while true do local node_dir = S.open(node_path..node, 'rdonly, directory') if not node_dir then return 0 end -- default NUMA node local found = S.readlinkat(node_dir, 'cpu'..cpu) node_dir:close() if found then return node end node = node + 1 end end local function supports_numa () local node0 = S.open(node_path..tostring(0), 'rdonly, directory') if not node0 then return false end node0:close() return true end function has_numa () local node1 = S.open(node_path..tostring(1), 'rdonly, directory') if not node1 then return false end node1:close() return true end function pci_get_numa_node (addr) addr = pci.qualified(addr) local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node')) local node = assert(tonumber(file:read())) -- node can be -1. return math.max(0, node) end function choose_numa_node_for_pci_addresses (addrs, require_affinity) local chosen_node, chosen_because_of_addr for _, addr in ipairs(addrs) do local node = pci_get_numa_node(addr) if not node or node == chosen_node then -- Keep trucking. elseif not chosen_node then chosen_node = node chosen_because_of_addr = addr else local warn = warn if require_affinity then warn = die end warn("PCI devices %s and %s have different NUMA node affinities", chosen_because_of_addr, addr) end end return chosen_node end function check_affinity_for_pci_addresses (addrs) local policy = S.get_mempolicy() if policy.mode == S.c.MPOL_MODE['default'] then if has_numa() then warn('No NUMA memory affinity.\n'.. 'Pass --cpu to bind to a CPU and its NUMA node.') end elseif (policy.mode ~= S.c.MPOL_MODE['bind'] and policy.mode ~= S.c.MPOL_MODE['preferred']) then warn("NUMA memory policy already in effect, but it's not --membind or --preferred.") else local node = S.getcpu().node local node_for_pci = choose_numa_node_for_pci_addresses(addrs) if node_for_pci and node ~= node_for_pci then warn("Bound NUMA node does not have affinity with PCI devices.") end end end local irqbalanced_checked = false local function assert_irqbalanced_disabled (warn) if irqbalanced_checked then return end irqbalanced_checked = true for path in os.getenv('PATH'):split(':') do if S.stat(path..'/irqbalance') then if S.stat('/etc/default/irqbalance') then for line in io.lines('/etc/default/irqbalance') do if line:match('^ENABLED=0') then return end end end warn('Irqbalanced detected; this will hurt performance! %s', 'Consider uninstalling via "sudo apt-get remove irqbalance" and rebooting.') end end end local function check_cpu_performance_tuning (cpu, strict) local warn = warn if strict then warn = die end assert_irqbalanced_disabled(warn) local path = '/sys/devices/system/cpu/cpu'..cpu..'/cpufreq/scaling_governor' local gov = assert(io.open(path)):read() if not gov:match('performance') then warn('Expected performance scaling governor for CPU %s, but got "%s"', cpu, gov) end if not isolated_cpus()[cpu] then warn('Expected dedicated core, but CPU %s is not in isolcpus set', cpu) end end function unbind_cpu () local cpu_set = S.sched_getaffinity() cpu_set:zero() for i = 0, MAX_CPU do cpu_set:set(i) end assert(S.sched_setaffinity(0, cpu_set)) bound_cpu = nil end function bind_to_cpu (cpu, skip_perf_checks) local function contains (t, e) for k,v in ipairs(t) do if tonumber(v) == tonumber(e) then return true end end return false end if not cpu then return unbind_cpu() end if cpu == bound_cpu then return end assert(not bound_cpu, "already bound") if type(cpu) ~= 'table' then cpu = {cpu} end assert(S.sched_setaffinity(0, cpu), ("Couldn't set affinity for cpuset %s"):format(table.concat(cpu, ','))) local cpu_and_node = S.getcpu() assert(contains(cpu, cpu_and_node.cpu)) bound_cpu = cpu_and_node.cpu bind_to_numa_node (cpu_and_node.node) if not skip_perf_checks then check_cpu_performance_tuning(bound_cpu) end end function unbind_numa_node () if supports_numa() then assert(S.set_mempolicy('default')) end bound_numa_node = nil end function bind_to_numa_node (node, policy) if node == bound_numa_node then return end if not node then return unbind_numa_node() end assert(not bound_numa_node, "already bound") if supports_numa() then assert(S.set_mempolicy(policy or 'preferred', node)) -- Migrate any pages that might have the wrong affinity. local from_mask = assert(S.get_mempolicy(nil, nil, nil, 'mems_allowed')).mask local ok, err = S.migrate_pages(0, from_mask, node) if not ok then warn("Failed to migrate pages to NUMA node %d: %s\n", node, tostring(err)) end end bound_numa_node = node end function prevent_preemption(priority) assert(S.sched_setscheduler(0, "fifo", priority or 1), 'Failed to enable real-time scheduling. Try running as root.') end function selftest () local cpus = parse_cpuset("0-5,7") for i=0,5 do assert(cpus[i]) end assert(not cpus[6]) assert(cpus[7]) do local count = 0 for k,v in pairs(cpus) do count = count + 1 end assert(count == 7) end assert(parse_cpuset("1")[1]) function test_cpu(cpu) local node = cpu_get_numa_node(cpu) bind_to_cpu(cpu, 'skip-perf-checks') assert(bound_cpu == cpu) assert(bound_numa_node == node) assert(S.getcpu().cpu == cpu) assert(S.getcpu().node == node) bind_to_cpu(nil) assert(bound_cpu == nil) assert(bound_numa_node == node) assert(S.getcpu().node == node) bind_to_numa_node(nil) assert(bound_cpu == nil) assert(bound_numa_node == nil) end function test_pci_affinity (pciaddr) check_affinity_for_pci_addresses({pciaddr}) local node = choose_numa_node_for_pci_addresses({pciaddr}, true) bind_to_numa_node(node) assert(bound_numa_node == node) check_affinity_for_pci_addresses({pciaddr}) bind_to_numa_node(nil) assert(bound_numa_node == nil) end print('selftest: numa') local cpu_set = S.sched_getaffinity() for cpuid = 0, MAX_CPU do if cpu_set:get(cpuid) then test_cpu(cpuid) end end local pciaddr = os.getenv("SNABB_PCI0") if pciaddr then test_pci_affinity(pciaddr) end print('selftest: numa: ok') end
apache-2.0
dvv/luvit-engine.io
lib/req/codec.lua
1
3068
local Table = require('table') local UTF8 = require('unicode').utf8 --- -- Packet types. -- local packets = { open = 'o', close = 'c', ping = 'p', pong = 'P', message = 'm', error = 'e', noop = '0', } -- provide inverse map, to ease lookup for k, v in pairs(packets) do packets[v] = k end --- -- Premade error packet. -- local err = { type = 'error', data = 'parser error' } --- -- Encodes a packet. -- -- <packet type id> [ `:` <data> ] -- -- Example: -- -- 5:hello world -- 3 -- 4 -- -- @api private -- local function encodePacket(packet) local encoded = packets[packet.type] if not encoded then return '0' end -- data fragment is optional if packet.data ~= nil then encoded = encoded .. packet.data end return tostring(encoded) end --- -- Decodes a packet. -- -- @return {Object} with `type` and `data` (if any) -- @api private -- local function decodePacket(data) local typ = data:sub(1, 1) if not packets[typ] then -- parser error - ignoring packet return err end if #data > 1 then return { type = packets[typ], data = data:sub(2) } else return { type = packets[typ] } end end --- -- Encodes multiple messages (payload). -- -- <length>:data -- -- Example: -- -- 11:hello world2:hi -- -- @param {Array} packets -- @api private -- function encodePayload(packets) if #packets == 0 then return '0:' end local encoded = { } for i, packet in ipairs(packets) do local message = encodePacket(packet) Table.insert(encoded, UTF8.len(message)) Table.insert(encoded, ':') Table.insert(encoded, message) end return Table.concat(encoded) end --- -- Decodes data when a payload is maybe expected. -- -- @param {String} data -- @return {Array} packets -- @api public -- -- -- TODO: streaming, as Lua strings are not good at mangling -- function decodePayload(data) local ret = { err } if data == '' then -- parser error - ignoring payload return ret end local packets = { } local buf = data local n, msg, packet -- FIXME: lua is not good at mutable strings. Consider lbuffers while #buf do local colon = (buf:find(':', 1, true)) if not colon then break end n = tonumber(buf:sub(1, colon - 1)) if not n then -- parser error - ignoring payload return ret end msg = UTF8.sub(buf, colon + 1, colon + n) if n ~= UTF8.len(msg) then -- parser error - ignoring payload return ret end buf = UTF8.sub(buf, colon + n + 1) if #msg then packet = decodePacket(msg) if err.type == packet.type and err.data == packet.data then -- parser error in individual packet - ignoring payload return ret end Table.insert(packets, packet) end end if #buf ~= 0 then -- parser error - ignoring payload return ret end return packets end -- module return { packets = packets, encode_packet = encodePacket, decode_packet = decodePacket, encode = encodePayload, decode = decodePayload, }
mit
alexandergall/snabbswitch
lib/luajit/testsuite/test/lib/ffi/ffi_callback.lua
6
4662
local ffi = require("ffi") ffi.cdef[[ void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const uint8_t *, const uint8_t *)); ]] do local cb = ffi.cast("int (*)(int, int, int)", function(a, b, c) return a+b+c end) assert(cb(10, 99, 13) == 122) -- Don't compile call to blacklisted function. for i=1,200 do if i > 60 then assert(cb(10, 99, 13) == 122) end end end do assert(ffi.cast("int64_t (*)(int64_t, int64_t, int64_t)", function(a, b, c) return a+b+c end)(12345678901234567LL, 70000000000000001LL, 10000000909090904LL) == 12345678901234567LL+70000000000000001LL+10000000909090904LL) assert(ffi.cast("double (*)(double, float, double)", function(a, b, c) return a+b+c end)(7.125, -123.25, 9999.33) == 7.125-123.25+9999.33) assert(ffi.cast("double (*)(int, double)", function(a, b) return a+b end)(12345, 7.125) == 12345 + 7.125) assert(ffi.cast("float (*)(double, float, double)", function(a, b, c) return a+b+c end)(7.125, -123.25, 9999.33) == 9883.205078125) assert(ffi.cast("int (*)(int, int, int, int, int, int, int, int, int, int)", function(a, b, c, d, e, f, g, h, i, j) return a+b+c+d+e+f+g+h+i+j end)(-42, 17, 12345, 9987, -100, 11, 51, 0x12345678, 338, -78901234) == -42+17+12345+9987-100+11+51+0x12345678+338-78901234) assert(ffi.cast("double (*)(double, double, double, double, double, double, double, double, double, double)", function(a, b, c, d, e, f, g, h, i, j) return a+b+c+d+e+f+g+h+i+j end)(-42.5, 17.125, 12345.5, 9987, -100.625, 11, 51, 0x12345678, 338, -78901234.75) == -42.5+17.125+12345.5+9987-100.625+11+51+0x12345678+338-78901234.75) end -- Target-specific tests. if jit.arch == "x86" then assert(ffi.cast("__fastcall int (*)(int, int, int)", function(a, b, c) return a+b+c end)(10, 99, 13) == 122) assert(ffi.cast("__stdcall int (*)(int, int, int)", function(a, b, c) return a+b+c end)(10, 99, 13) == 122) -- Test reordering. assert(ffi.cast("int64_t __fastcall (*)(int64_t, int, int)", function(a, b, c) return a+b+c end)(12345678901234567LL, 12345, 989797123) == 12345678901234567LL+12345+989797123) end -- Error handling. do local function f() return end -- Error for result conversion triggered here. local ok, err = pcall(ffi.cast("int (*)(void)", f)) assert(ok == false) assert(string.match(err, ":"..debug.getinfo(f, "S").lastlinedefined..":")) assert(pcall(ffi.cast("int (*)(void)", function() end)) == false) assert(pcall(ffi.cast("int (*)(void)", function() error("test") end)) == false) assert(pcall(ffi.cast("int (*)(void)", function(a) return a+1 end)) == false) assert(pcall(ffi.cast("int (*)(int,int,int,int, int,int,int,int, int)", function() error("test") end), 1,1,1,1, 1,1,1,1, 1) == false) assert(pcall(ffi.cast("int (*)(int,int,int,int, int,int,int,int, int)", function() error("test") end), 1,1,1,1, 1,1,1,1, 1) == false) end do local function cmp(pa, pb) local a, b = pa[0], pb[0] if a < b then return -1 elseif a > b then return 1 else return 0 end end local arr = ffi.new("uint8_t[?]", 256) for i=0,255 do arr[i] = math.random(0, 255) end ffi.C.qsort(arr, 256, 1, cmp) for i=0,254 do assert(arr[i] <= arr[i+1]) end end if ffi.abi"win" then ffi.cdef[[ typedef int (__stdcall *WNDENUMPROC)(void *hwnd, intptr_t l); int EnumWindows(WNDENUMPROC func, intptr_t l); int SendMessageA(void *hwnd, uint32_t msg, int w, intptr_t l); enum { WM_GETTEXT = 13 }; ]] local C = ffi.C local buf = ffi.new("char[?]", 256) local lbuf = ffi.cast("intptr_t", buf) local count = 0 C.EnumWindows(function(hwnd, l) if C.SendMessageA(hwnd, C.WM_GETTEXT, 255, lbuf) ~= 0 then count = count + 1 end return true end, 0) assert(count > 10) end do local cb = ffi.cast("int(*)(void)", function() return 1 end) assert(cb() == 1) cb:free() assert(pcall(cb) == false) assert(pcall(cb.free, cb) == false) assert(pcall(cb.set, cb, function() end) == false) cb = ffi.cast("int(*)(void)", function() return 2 end) assert(cb() == 2) cb:set(function() return 3 end) assert(cb() == 3) end do local ft = ffi.typeof("void(*)(void)") local function f() end local t = {} for i=1,4 do for i=1,400 do t[i] = ft(f) end for i=1,400 do t[i]:free() end end end do assert(ffi.cast("int (*)()", function() return string.byte"A" end)() == 65) end do local f = ffi.cast("void (*)(void)", function() debug.traceback() end) debug.sethook(function() debug.sethook(nil, "", 0); f() end, "", 1) local x end
apache-2.0
rogerpueyo/luci
modules/luci-base/luasrc/dispatcher.lua
1
34280
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local util = require "luci.util" local http = require "luci.http" local nixio = require "nixio", require "nixio.util" module("luci.dispatcher", package.seeall) context = util.threadlocal() uci = require "luci.model.uci" i18n = require "luci.i18n" _M.fs = fs -- Index table local index = nil local function check_fs_depends(spec) local fs = require "nixio.fs" for path, kind in pairs(spec) do if kind == "directory" then local empty = true for entry in (fs.dir(path) or function() end) do empty = false break end if empty then return false end elseif kind == "executable" then if fs.stat(path, "type") ~= "reg" or not fs.access(path, "x") then return false end elseif kind == "file" then if fs.stat(path, "type") ~= "reg" then return false end end end return true end local function check_uci_depends_options(conf, s, opts) local uci = require "luci.model.uci" if type(opts) == "string" then return (s[".type"] == opts) elseif opts == true then for option, value in pairs(s) do if option:byte(1) ~= 46 then return true end end elseif type(opts) == "table" then for option, value in pairs(opts) do local sval = s[option] if type(sval) == "table" then local found = false for _, v in ipairs(sval) do if v == value then found = true break end end if not found then return false end elseif value == true then if sval == nil then return false end else if sval ~= value then return false end end end end return true end local function check_uci_depends_section(conf, sect) local uci = require "luci.model.uci" for section, options in pairs(sect) do local stype = section:match("^@([A-Za-z0-9_%-]+)$") if stype then local found = false uci:foreach(conf, stype, function(s) if check_uci_depends_options(conf, s, options) then found = true return false end end) if not found then return false end else local s = uci:get_all(conf, section) if not s or not check_uci_depends_options(conf, s, options) then return false end end end return true end local function check_uci_depends(conf) local uci = require "luci.model.uci" for config, values in pairs(conf) do if values == true then local found = false uci:foreach(config, nil, function(s) found = true return false end) if not found then return false end elseif type(values) == "table" then if not check_uci_depends_section(config, values) then return false end end end return true end local function check_acl_depends(require_groups, groups) if type(require_groups) == "table" and #require_groups > 0 then local writable = false for _, group in ipairs(require_groups) do local read = false local write = false if type(groups) == "table" and type(groups[group]) == "table" then for _, perm in ipairs(groups[group]) do if perm == "read" then read = true elseif perm == "write" then write = true end end end if not read and not write then return nil elseif write then writable = true end end return writable end return true end local function check_depends(spec) if type(spec.depends) ~= "table" then return true end if type(spec.depends.fs) == "table" then local satisfied = false local alternatives = (#spec.depends.fs > 0) and spec.depends.fs or { spec.depends.fs } for _, alternative in ipairs(alternatives) do if check_fs_depends(alternative) then satisfied = true break end end if not satisfied then return false end end if type(spec.depends.uci) == "table" then local satisfied = false local alternatives = (#spec.depends.uci > 0) and spec.depends.uci or { spec.depends.uci } for _, alternative in ipairs(alternatives) do if check_uci_depends(alternative) then satisfied = true break end end if not satisfied then return false end end return true end local function target_to_json(target, module) local action if target.type == "call" then action = { ["type"] = "call", ["module"] = module, ["function"] = target.name, ["parameters"] = target.argv } elseif target.type == "view" then action = { ["type"] = "view", ["path"] = target.view } elseif target.type == "template" then action = { ["type"] = "template", ["path"] = target.view } elseif target.type == "cbi" then action = { ["type"] = "cbi", ["path"] = target.model, ["config"] = target.config } elseif target.type == "form" then action = { ["type"] = "form", ["path"] = target.model } elseif target.type == "firstchild" then action = { ["type"] = "firstchild" } elseif target.type == "firstnode" then action = { ["type"] = "firstchild", ["recurse"] = true } elseif target.type == "arcombine" then if type(target.targets) == "table" then action = { ["type"] = "arcombine", ["targets"] = { target_to_json(target.targets[1], module), target_to_json(target.targets[2], module) } } end elseif target.type == "alias" then action = { ["type"] = "alias", ["path"] = table.concat(target.req, "/") } elseif target.type == "rewrite" then action = { ["type"] = "rewrite", ["path"] = table.concat(target.req, "/"), ["remove"] = target.n } end if target.post and action then action.post = target.post end return action end local function tree_to_json(node, json) local fs = require "nixio.fs" local util = require "luci.util" if type(node.nodes) == "table" then for subname, subnode in pairs(node.nodes) do local spec = { title = util.striptags(subnode.title), order = subnode.order } if subnode.leaf then spec.wildcard = true end if subnode.cors then spec.cors = true end if subnode.setuser then spec.setuser = subnode.setuser end if subnode.setgroup then spec.setgroup = subnode.setgroup end if type(subnode.target) == "table" then spec.action = target_to_json(subnode.target, subnode.module) end if type(subnode.file_depends) == "table" then for _, v in ipairs(subnode.file_depends) do spec.depends = spec.depends or {} spec.depends.fs = spec.depends.fs or {} local ft = fs.stat(v, "type") if ft == "dir" then spec.depends.fs[v] = "directory" elseif v:match("/s?bin/") then spec.depends.fs[v] = "executable" else spec.depends.fs[v] = "file" end end end if type(subnode.uci_depends) == "table" then for k, v in pairs(subnode.uci_depends) do spec.depends = spec.depends or {} spec.depends.uci = spec.depends.uci or {} spec.depends.uci[k] = v end end if type(subnode.acl_depends) == "table" then for _, acl in ipairs(subnode.acl_depends) do spec.depends = spec.depends or {} spec.depends.acl = spec.depends.acl or {} spec.depends.acl[#spec.depends.acl + 1] = acl end end if (subnode.sysauth_authenticator ~= nil) or (subnode.sysauth ~= nil and subnode.sysauth ~= false) then if subnode.sysauth_authenticator == "htmlauth" then spec.auth = { login = true, methods = { "cookie:sysauth" } } elseif subname == "rpc" and subnode.module == "luci.controller.rpc" then spec.auth = { login = false, methods = { "query:auth", "cookie:sysauth" } } elseif subnode.module == "luci.controller.admin.uci" then spec.auth = { login = false, methods = { "param:sid" } } end elseif subnode.sysauth == false then spec.auth = {} end if not spec.action then spec.title = nil end spec.satisfied = check_depends(spec) json.children = json.children or {} json.children[subname] = tree_to_json(subnode, spec) end end return json end function build_url(...) local path = {...} local url = { http.getenv("SCRIPT_NAME") or "" } local p for _, p in ipairs(path) do if p:match("^[a-zA-Z0-9_%-%.%%/,;]+$") then url[#url+1] = "/" url[#url+1] = p end end if #path == 0 then url[#url+1] = "/" end return table.concat(url, "") end function error404(message) http.status(404, "Not Found") message = message or "Not Found" local function render() local template = require "luci.template" template.render("error404") end if not util.copcall(render) then http.prepare_content("text/plain") http.write(message) end return false end function error500(message) util.perror(message) if not context.template_header_sent then http.status(500, "Internal Server Error") http.prepare_content("text/plain") http.write(message) else require("luci.template") if not util.copcall(luci.template.render, "error500", {message=message}) then http.prepare_content("text/plain") http.write(message) end end return false end local function determine_request_language() local conf = require "luci.config" assert(conf.main, "/etc/config/luci seems to be corrupt, unable to find section 'main'") local lang = conf.main.lang or "auto" if lang == "auto" then local aclang = http.getenv("HTTP_ACCEPT_LANGUAGE") or "" for aclang in aclang:gmatch("[%w_-]+") do local country, culture = aclang:match("^([a-z][a-z])[_-]([a-zA-Z][a-zA-Z])$") if country and culture then local cc = "%s_%s" %{ country, culture:lower() } if conf.languages[cc] then lang = cc break elseif conf.languages[country] then lang = country break end elseif conf.languages[aclang] then lang = aclang break end end end if lang == "auto" then lang = i18n.default end i18n.setlanguage(lang) end function httpdispatch(request, prefix) http.context.request = request local r = {} context.request = r local pathinfo = http.urldecode(request:getenv("PATH_INFO") or "", true) if prefix then for _, node in ipairs(prefix) do r[#r+1] = node end end local node for node in pathinfo:gmatch("[^/%z]+") do r[#r+1] = node end determine_request_language() local stat, err = util.coxpcall(function() dispatch(context.request) end, error500) http.close() --context._disable_memtrace() end local function require_post_security(target, args) if type(target) == "table" and target.type == "arcombine" and type(target.targets) == "table" then return require_post_security((type(args) == "table" and #args > 0) and target.targets[2] or target.targets[1], args) end if type(target) == "table" then if type(target.post) == "table" then local param_name, required_val, request_val for param_name, required_val in pairs(target.post) do request_val = http.formvalue(param_name) if (type(required_val) == "string" and request_val ~= required_val) or (required_val == true and request_val == nil) then return false end end return true end return (target.post == true) end return false end function test_post_security() if http.getenv("REQUEST_METHOD") ~= "POST" then http.status(405, "Method Not Allowed") http.header("Allow", "POST") return false end if http.formvalue("token") ~= context.authtoken then http.status(403, "Forbidden") luci.template.render("csrftoken") return false end return true end local function session_retrieve(sid, allowed_users) local sdat = util.ubus("session", "get", { ubus_rpc_session = sid }) local sacl = util.ubus("session", "access", { ubus_rpc_session = sid }) if type(sdat) == "table" and type(sdat.values) == "table" and type(sdat.values.token) == "string" and (not allowed_users or util.contains(allowed_users, sdat.values.username)) then uci:set_session_id(sid) return sid, sdat.values, type(sacl) == "table" and sacl or {} end return nil, nil, nil end local function session_setup(user, pass) local login = util.ubus("session", "login", { username = user, password = pass, timeout = tonumber(luci.config.sauth.sessiontime) }) local rp = context.requestpath and table.concat(context.requestpath, "/") or "" if type(login) == "table" and type(login.ubus_rpc_session) == "string" then util.ubus("session", "set", { ubus_rpc_session = login.ubus_rpc_session, values = { token = sys.uniqueid(16) } }) io.stderr:write("luci: accepted login on /%s for %s from %s\n" %{ rp, user or "?", http.getenv("REMOTE_ADDR") or "?" }) return session_retrieve(login.ubus_rpc_session) end io.stderr:write("luci: failed login on /%s for %s from %s\n" %{ rp, user or "?", http.getenv("REMOTE_ADDR") or "?" }) end local function check_authentication(method) local auth_type, auth_param = method:match("^(%w+):(.+)$") local sid, sdat if auth_type == "cookie" then sid = http.getcookie(auth_param) elseif auth_type == "param" then sid = http.formvalue(auth_param) elseif auth_type == "query" then sid = http.formvalue(auth_param, true) end return session_retrieve(sid) end local function get_children(node) local children = {} if not node.wildcard and type(node.children) == "table" then for name, child in pairs(node.children) do children[#children+1] = { name = name, node = child, order = child.order or 1000 } end table.sort(children, function(a, b) if a.order == b.order then return a.name < b.name else return a.order < b.order end end) end return children end local function find_subnode(root, prefix, recurse, descended) local children = get_children(root) if #children > 0 and (not descended or recurse) then local sub_path = { unpack(prefix) } if recurse == false then recurse = nil end for _, child in ipairs(children) do sub_path[#prefix+1] = child.name local res_path = find_subnode(child.node, sub_path, recurse, true) if res_path then return res_path end end end if descended then if not recurse or root.action.type == "cbi" or root.action.type == "form" or root.action.type == "view" or root.action.type == "template" or root.action.type == "arcombine" then return prefix end end end local function merge_trees(node_a, node_b) for k, v in pairs(node_b) do if k == "children" then node_a.children = node_a.children or {} for name, spec in pairs(v) do node_a.children[name] = merge_trees(node_a.children[name] or {}, spec) end else node_a[k] = v end end if type(node_a.action) == "table" and node_a.action.type == "firstchild" and node_a.children == nil then node_a.satisfied = false end return node_a end local function apply_tree_acls(node, acl) if type(node.children) == "table" then for _, child in pairs(node.children) do apply_tree_acls(child, acl) end end local perm if type(node.depends) == "table" then perm = check_acl_depends(node.depends.acl, acl["access-group"]) else perm = true end if perm == nil then node.satisfied = false elseif perm == false then node.readonly = true end end function menu_json(acl) local tree = context.tree or createtree() local lua_tree = tree_to_json(tree, { action = { ["type"] = "firstchild", ["recurse"] = true } }) local json_tree = createtree_json() local menu_tree = merge_trees(lua_tree, json_tree) if acl then apply_tree_acls(menu_tree, acl) end return menu_tree end local function init_template_engine(ctx) local tpl = require "luci.template" local media = luci.config.main.mediaurlbase if not pcall(tpl.Template, "themes/%s/header" % fs.basename(media)) then media = nil for name, theme in pairs(luci.config.themes) do if name:sub(1,1) ~= "." and pcall(tpl.Template, "themes/%s/header" % fs.basename(theme)) then media = theme end end assert(media, "No valid theme found") end local function _ifattr(cond, key, val, noescape) if cond then local env = getfenv(3) local scope = (type(env.self) == "table") and env.self if type(val) == "table" then if not next(val) then return '' else val = util.serialize_json(val) end end val = tostring(val or (type(env[key]) ~= "function" and env[key]) or (scope and type(scope[key]) ~= "function" and scope[key]) or "") if noescape ~= true then val = util.pcdata(val) end return string.format(' %s="%s"', tostring(key), val) else return '' end end tpl.context.viewns = setmetatable({ write = http.write; include = function(name) tpl.Template(name):render(getfenv(2)) end; translate = i18n.translate; translatef = i18n.translatef; export = function(k, v) if tpl.context.viewns[k] == nil then tpl.context.viewns[k] = v end end; striptags = util.striptags; pcdata = util.pcdata; media = media; theme = fs.basename(media); resource = luci.config.main.resourcebase; ifattr = function(...) return _ifattr(...) end; attr = function(...) return _ifattr(true, ...) end; url = build_url; }, {__index=function(tbl, key) if key == "controller" then return build_url() elseif key == "REQUEST_URI" then return build_url(unpack(ctx.requestpath)) elseif key == "FULL_REQUEST_URI" then local url = { http.getenv("SCRIPT_NAME") or "", http.getenv("PATH_INFO") } local query = http.getenv("QUERY_STRING") if query and #query > 0 then url[#url+1] = "?" url[#url+1] = query end return table.concat(url, "") elseif key == "token" then return ctx.authtoken else return rawget(tbl, key) or _G[key] end end}) return tpl end function dispatch(request) --context._disable_memtrace = require "luci.debug".trap_memtrace("l") local ctx = context local auth, cors, suid, sgid local menu = menu_json() local page = menu local requested_path_full = {} local requested_path_node = {} local requested_path_args = {} local required_path_acls = {} for i, s in ipairs(request) do if type(page.children) ~= "table" or not page.children[s] then page = nil break end if not page.children[s].satisfied then page = nil break end page = page.children[s] auth = page.auth or auth cors = page.cors or cors suid = page.setuser or suid sgid = page.setgroup or sgid if type(page.depends) == "table" and type(page.depends.acl) == "table" then for _, group in ipairs(page.depends.acl) do local found = false for _, item in ipairs(required_path_acls) do if item == group then found = true break end end if not found then required_path_acls[#required_path_acls + 1] = group end end end requested_path_full[i] = s requested_path_node[i] = s if page.wildcard then for j = i + 1, #request do requested_path_args[j - i] = request[j] requested_path_full[j] = request[j] end break end end local tpl = init_template_engine(ctx) ctx.args = requested_path_args ctx.path = requested_path_node ctx.dispatched = page ctx.requestpath = ctx.requestpath or requested_path_full ctx.requestargs = ctx.requestargs or requested_path_args ctx.requested = ctx.requested or page if type(auth) == "table" and type(auth.methods) == "table" and #auth.methods > 0 then local sid, sdat, sacl for _, method in ipairs(auth.methods) do sid, sdat, sacl = check_authentication(method) if sid and sdat and sacl then break end end if not (sid and sdat and sacl) and auth.login then local user = http.getenv("HTTP_AUTH_USER") local pass = http.getenv("HTTP_AUTH_PASS") if user == nil and pass == nil then user = http.formvalue("luci_username") pass = http.formvalue("luci_password") end if user and pass then sid, sdat, sacl = session_setup(user, pass) end if not sid then context.path = {} http.status(403, "Forbidden") http.header("X-LuCI-Login-Required", "yes") local scope = { duser = "root", fuser = user } local ok, res = util.copcall(tpl.render_string, [[<% include("themes/" .. theme .. "/sysauth") %>]], scope) if ok then return res end return tpl.render("sysauth", scope) end http.header("Set-Cookie", 'sysauth=%s; path=%s; SameSite=Strict; HttpOnly%s' %{ sid, build_url(), http.getenv("HTTPS") == "on" and "; secure" or "" }) http.redirect(build_url(unpack(ctx.requestpath))) return end if not sid or not sdat or not sacl then http.status(403, "Forbidden") http.header("X-LuCI-Login-Required", "yes") return end ctx.authsession = sid ctx.authtoken = sdat.token ctx.authuser = sdat.username ctx.authacl = sacl end if #required_path_acls > 0 then local perm = check_acl_depends(required_path_acls, ctx.authacl and ctx.authacl["access-group"]) if perm == nil then http.status(403, "Forbidden") return end page.readonly = not perm end local action = (page and type(page.action) == "table") and page.action or {} if action.type == "arcombine" then action = (#requested_path_args > 0) and action.targets[2] or action.targets[1] end if cors and http.getenv("REQUEST_METHOD") == "OPTIONS" then luci.http.status(200, "OK") luci.http.header("Access-Control-Allow-Origin", http.getenv("HTTP_ORIGIN") or "*") luci.http.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") return end if require_post_security(action) then if not test_post_security() then return end end if sgid then sys.process.setgroup(sgid) end if suid then sys.process.setuser(suid) end if action.type == "view" then tpl.render("view", { view = action.path }) elseif action.type == "call" then local ok, mod = util.copcall(require, action.module) if not ok then error500(mod) return end local func = mod[action["function"]] assert(func ~= nil, 'Cannot resolve function "' .. action["function"] .. '". Is it misspelled or local?') assert(type(func) == "function", 'The symbol "' .. action["function"] .. '" does not refer to a function but data ' .. 'of type "' .. type(func) .. '".') local argv = (type(action.parameters) == "table" and #action.parameters > 0) and { unpack(action.parameters) } or {} for _, s in ipairs(requested_path_args) do argv[#argv + 1] = s end local ok, err = util.copcall(func, unpack(argv)) if not ok then error500(err) end elseif action.type == "firstchild" then local sub_request = find_subnode(page, requested_path_full, action.recurse) if sub_request then dispatch(sub_request) else tpl.render("empty_node_placeholder", getfenv(1)) end elseif action.type == "alias" then local sub_request = {} for name in action.path:gmatch("[^/]+") do sub_request[#sub_request + 1] = name end for _, s in ipairs(requested_path_args) do sub_request[#sub_request + 1] = s end dispatch(sub_request) elseif action.type == "rewrite" then local sub_request = { unpack(request) } for i = 1, action.remove do table.remove(sub_request, 1) end local n = 1 for s in action.path:gmatch("[^/]+") do table.insert(sub_request, n, s) n = n + 1 end for _, s in ipairs(requested_path_args) do sub_request[#sub_request + 1] = s end dispatch(sub_request) elseif action.type == "template" then tpl.render(action.path, getfenv(1)) elseif action.type == "cbi" then _cbi({ config = action.config, model = action.path }, unpack(requested_path_args)) elseif action.type == "form" then _form({ model = action.path }, unpack(requested_path_args)) else local root = find_subnode(menu, {}, true) if not root then error404("No root node was registered, this usually happens if no module was installed.\n" .. "Install luci-mod-admin-full and retry. " .. "If the module is already installed, try removing the /tmp/luci-indexcache file.") else error404("No page is registered at '/" .. table.concat(requested_path_full, "/") .. "'.\n" .. "If this url belongs to an extension, make sure it is properly installed.\n" .. "If the extension was recently installed, try removing the /tmp/luci-indexcache file.") end end end local function hash_filelist(files) local fprint = {} local n = 0 for i, file in ipairs(files) do local st = fs.stat(file) if st then fprint[n + 1] = '%x' % st.ino fprint[n + 2] = '%x' % st.mtime fprint[n + 3] = '%x' % st.size n = n + 3 end end return nixio.crypt(table.concat(fprint, "|"), "$1$"):sub(5):gsub("/", ".") end local function read_cachefile(file, reader) local euid = sys.process.info("uid") local fuid = fs.stat(file, "uid") local mode = fs.stat(file, "modestr") if euid ~= fuid or mode ~= "rw-------" then return nil end return reader(file) end function createindex() local controllers = { } local base = "%s/controller/" % util.libpath() local _, path for path in (fs.glob("%s*.lua" % base) or function() end) do controllers[#controllers+1] = path end for path in (fs.glob("%s*/*.lua" % base) or function() end) do controllers[#controllers+1] = path end local cachefile if indexcache then cachefile = "%s.%s.lua" %{ indexcache, hash_filelist(controllers) } local res = read_cachefile(cachefile, function(path) return loadfile(path)() end) if res then index = res return res end for file in (fs.glob("%s.*.lua" % indexcache) or function() end) do fs.unlink(file) end end index = {} for _, path in ipairs(controllers) do local modname = "luci.controller." .. path:sub(#base+1, #path-4):gsub("/", ".") local mod = require(modname) assert(mod ~= true, "Invalid controller file found\n" .. "The file '" .. path .. "' contains an invalid module line.\n" .. "Please verify whether the module name is set to '" .. modname .. "' - It must correspond to the file path!") local idx = mod.index if type(idx) == "function" then index[modname] = idx end end if cachefile then local f = nixio.open(cachefile, "w", 600) f:writeall(util.get_bytecode(index)) f:close() end end function createtree_json() local json = require "luci.jsonc" local tree = {} local schema = { action = "table", auth = "table", cors = "boolean", depends = "table", order = "number", setgroup = "string", setuser = "string", title = "string", wildcard = "boolean" } local files = {} local cachefile for file in (fs.glob("/usr/share/luci/menu.d/*.json") or function() end) do files[#files+1] = file end if indexcache then cachefile = "%s.%s.json" %{ indexcache, hash_filelist(files) } local res = read_cachefile(cachefile, function(path) return json.parse(fs.readfile(path) or "") end) if res then return res end for file in (fs.glob("%s.*.json" % indexcache) or function() end) do fs.unlink(file) end end for _, file in ipairs(files) do local data = json.parse(fs.readfile(file) or "") if type(data) == "table" then for path, spec in pairs(data) do if type(spec) == "table" then local node = tree for s in path:gmatch("[^/]+") do if s == "*" then node.wildcard = true break end node.children = node.children or {} node.children[s] = node.children[s] or {} node = node.children[s] end if node ~= tree then for k, t in pairs(schema) do if type(spec[k]) == t then node[k] = spec[k] end end node.satisfied = check_depends(spec) end end end end end if cachefile then local f = nixio.open(cachefile, "w", 600) f:writeall(json.stringify(tree)) f:close() end return tree end -- Build the index before if it does not exist yet. function createtree() if not index then createindex() end local ctx = context local tree = {nodes={}, inreq=true} ctx.treecache = setmetatable({}, {__mode="v"}) ctx.tree = tree local scope = setmetatable({}, {__index = luci.dispatcher}) for k, v in pairs(index) do scope._NAME = k setfenv(v, scope) v() end return tree end function assign(path, clone, title, order) local obj = node(unpack(path)) obj.nodes = nil obj.module = nil obj.title = title obj.order = order setmetatable(obj, {__index = _create_node(clone)}) return obj end function entry(path, target, title, order) local c = node(unpack(path)) c.target = target c.title = title c.order = order c.module = getfenv(2)._NAME return c end -- enabling the node. function get(...) return _create_node({...}) end function node(...) local c = _create_node({...}) c.module = getfenv(2)._NAME c.auto = nil return c end function lookup(...) local i, path = nil, {} for i = 1, select('#', ...) do local name, arg = nil, tostring(select(i, ...)) for name in arg:gmatch("[^/]+") do path[#path+1] = name end end for i = #path, 1, -1 do local node = context.treecache[table.concat(path, ".", 1, i)] if node and (i == #path or node.leaf) then return node, build_url(unpack(path)) end end end function _create_node(path) if #path == 0 then return context.tree end local name = table.concat(path, ".") local c = context.treecache[name] if not c then local last = table.remove(path) local parent = _create_node(path) c = {nodes={}, auto=true, inreq=true} parent.nodes[last] = c context.treecache[name] = c end return c end -- Subdispatchers -- function firstchild() return { type = "firstchild" } end function firstnode() return { type = "firstnode" } end function alias(...) return { type = "alias", req = { ... } } end function rewrite(n, ...) return { type = "rewrite", n = n, req = { ... } } end function call(name, ...) return { type = "call", argv = {...}, name = name } end function post_on(params, name, ...) return { type = "call", post = params, argv = { ... }, name = name } end function post(...) return post_on(true, ...) end function template(name) return { type = "template", view = name } end function view(name) return { type = "view", view = name } end function _cbi(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local util = require "luci.util" local config = self.config or {} local maps = cbi.load(self.model, ...) local state = nil local function has_uci_access(config, level) local rv = util.ubus("session", "access", { ubus_rpc_session = context.authsession, scope = "uci", object = config, ["function"] = level }) return (type(rv) == "table" and rv.access == true) or false end local i, res for i, res in ipairs(maps) do if util.instanceof(res, cbi.SimpleForm) then io.stderr:write("Model %s returns SimpleForm but is dispatched via cbi(),\n" % self.model) io.stderr:write("please change %s to use the form() action instead.\n" % table.concat(context.request, "/")) end res.flow = config local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end local function _resolve_path(path) return type(path) == "table" and build_url(unpack(path)) or path end if config.on_valid_to and state and state > 0 and state < 2 then http.redirect(_resolve_path(config.on_valid_to)) return end if config.on_changed_to and state and state > 1 then http.redirect(_resolve_path(config.on_changed_to)) return end if config.on_success_to and state and state > 0 then http.redirect(_resolve_path(config.on_success_to)) return end if config.state_handler then if not config.state_handler(state, maps) then return end end http.header("X-CBI-State", state or 0) if not config.noheader then tpl.render("cbi/header", {state = state}) end local redirect local messages local applymap = false local pageaction = true local parsechain = { } local writable = false for i, res in ipairs(maps) do if res.apply_needed and res.parsechain then local c for _, c in ipairs(res.parsechain) do parsechain[#parsechain+1] = c end applymap = true end if res.redirect then redirect = redirect or res.redirect end if res.pageaction == false then pageaction = false end if res.message then messages = messages or { } messages[#messages+1] = res.message end end for i, res in ipairs(maps) do local is_readable_map = has_uci_access(res.config, "read") local is_writable_map = has_uci_access(res.config, "write") writable = writable or is_writable_map res:render({ firstmap = (i == 1), redirect = redirect, messages = messages, pageaction = pageaction, parsechain = parsechain, readable = is_readable_map, writable = is_writable_map }) end if not config.nofooter then tpl.render("cbi/footer", { flow = config, pageaction = pageaction, redirect = redirect, state = state, autoapply = config.autoapply, trigger_apply = applymap, writable = writable }) end end function cbi(model, config) return { type = "cbi", post = { ["cbi.submit"] = true }, config = config, model = model } end function arcombine(trg1, trg2) return { type = "arcombine", env = getfenv(), targets = {trg1, trg2} } end function _form(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local maps = luci.cbi.load(self.model, ...) local state = nil local i, res for i, res in ipairs(maps) do local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end http.header("X-CBI-State", state or 0) tpl.render("header") for i, res in ipairs(maps) do res:render() end tpl.render("footer") end function form(model) return { type = "form", post = { ["cbi.submit"] = true }, model = model } end translate = i18n.translate -- This function does not actually translate the given argument but -- is used by build/i18n-scan.pl to find translatable entries. function _(text) return text end
apache-2.0
Vermeille/kong
kong/plugins/response-transformer/migrations/cassandra.lua
12
1582
return { { name = "2016-03-10-160000_resp_trans_schema_changes", up = function(_, _, factory) local plugins, err = factory.plugins:find_all {name = "response-transformer"} if err then return err end for _, plugin in ipairs(plugins) do for _, action in ipairs {"remove", "add", "append", "replace"} do plugin.config[action] = plugin.config[action] or {} for _, location in ipairs {"json", "headers"} do plugin.config[action][location] = plugin.config[action][location] or {} end end local _, err = factory.plugins:update(plugin, plugin, {full = true}) if err then return err end end end, down = function(_, _, factory) local plugins, err = factory.plugins:find_all {name = "response-transformer"} if err then return err end for _, plugin in ipairs(plugins) do plugin.config.replace = nil plugin.config.append = nil for _, action in ipairs {"remove", "add"} do for _, location in ipairs {"json", "headers"} do if plugin.config[action] ~= nil and next(plugin.config[action][location]) == nil then plugin.config[action][location] = nil end end if next(plugin.config[action]) == nil then plugin.config[action] = nil end end local _, err = factory.plugins:update(plugin, plugin, {full = true}) if err then return err end end end } }
apache-2.0
xponen/Zero-K
gamedata/modularcomms/weapons/beamlaser.lua
1
2118
local name = "commweapon_beamlaser" local weaponDef = { name = [[Beam Laser]], areaOfEffect = 12, beamTime = 0.1, coreThickness = 0.5, craterBoost = 0, craterMult = 0, customParams = { slot = [[5]], muzzleEffectShot = [[custom:BEAMWEAPON_MUZZLE_BLUE]], altforms = { green = { explosionGenerator = [[custom:flash1green]], customParams = { muzzleEffectShot = [[custom:BEAMWEAPON_MUZZLE_GREEN]] }, rgbColor = [[0 1 0]], }, red = { explosionGenerator = [[custom:flash1red]], customParams = { muzzleEffectShot = [[custom:BEAMWEAPON_MUZZLE_RED]] }, rgbColor = [[1 0 0]], }, yellow = { explosionGenerator = [[custom:flash1yellow]], customParams = { muzzleEffectShot = [[custom:BEAMWEAPON_MUZZLE_YELLOW]] }, rgbColor = [[1 1 0]], }, white = { explosionGenerator = [[custom:flash1white]], customParams = { muzzleEffectShot = [[custom:BEAMWEAPON_MUZZLE_WHITE]] }, rgbColor = [[1 1 1]], }, } }, damage = { default = 15.5, subs = 0.8, }, duration = 0.11, edgeEffectiveness = 0.99, explosionGenerator = [[custom:flash1blue]], fireStarter = 70, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 3, minIntensity = 1, noSelfDamage = true, range = 300, reloadtime = 0.11, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/pulse_laser3]], soundTrigger = true, targetMoveError = 0.05, texture1 = [[largelaser]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 3, tolerance = 10000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 900, } return name, weaponDef
gpl-2.0
kiarash14/tg5
plugins/getplug.lua
13
2392
local function run(msg, matches) if matches[1] == "getplug" then local file = matches[2] if is_sudo(msg) then --sudo only ! local receiver = get_receiver(msg) send_document(receiver, "./plugins/"..file..".lua", ok_cb, false) else return nil end end end return { patterns = { "^[!/](getplug) (.*)$" }, run = run } -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
xponen/Zero-K
LuaUI/Widgets/chili/Controls/colorbars.lua
25
2469
--//============================================================================= Colorbars = Control:Inherit{ classname = "colorbars", color = {1,1,1,1}, defaultWidth = 100, defaultHeight = 20, OnChange = {}, } local this = Colorbars local inherited = this.inherited --//============================================================================= function Colorbars:SetColor(c) self:CallListeners(self.OnChange,c) self.value = c self:Invalidate() end --//============================================================================= local GL_LINE_LOOP = GL.LINE_LOOP local GL_LINES = GL.LINES local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local glTranslate = gl.Translate local glVertex = gl.Vertex local glRect = gl.Rect local glColor = gl.Color local glBeginEnd = gl.BeginEnd function Colorbars:DrawControl() glPushMatrix() glTranslate(self.x,self.y,0) local barswidth = self.width - (self.height + 4) local color = self.color local step = self.height/7 --bars local rX1,rY1,rX2,rY2 = 0,0*step,color[1]*barswidth,1*step local gX1,gY1,gX2,gY2 = 0,2*step,color[2]*barswidth,3*step local bX1,bY1,bX2,bY2 = 0,4*step,color[3]*barswidth,5*step local aX1,aY1,aX2,aY2 = 0,6*step,(color[4] or 1)*barswidth,7*step glColor(1,0,0,1) glRect(rX1,rY1,rX2,rY2) glColor(0,1,0,1) glRect(gX1,gY1,gX2,gY2) glColor(0,0,1,1) glRect(bX1,bY1,bX2,bY2) glColor(1,1,1,1) glRect(aX1,aY1,aX2,aY2) glColor(self.color) glRect(barswidth + 2,self.height,self.width - 2,0) gl.BeginEnd(GL.TRIANGLE_STRIP, theme.DrawBorder_, barswidth + 2,0,self.width - barswidth - 4,self.height, 1, self.borderColor, self.borderColor2) glPopMatrix() end --//============================================================================= function Colorbars:HitTest() return self end function Colorbars:MouseDown(x,y) local step = self.height/7 local yp = y/step local r = yp%2 local barswidth = self.width - (self.height + 4) if (x<=barswidth)and(r<=1) then local barIdx = (yp-r)/2 + 1 local newvalue = x/barswidth if (newvalue>1) then newvalue=1 elseif (newvalue<0) then newvalue=0 end self.color[barIdx] = newvalue self:SetColor(self.color) return self end end function Colorbars:MouseMove(x,y,dx,dy,button) if (button==1) then return self:MouseDown(x,y) end end --//=============================================================================
gpl-2.0
alexandergall/snabbswitch
src/lib/fibers/op.lua
6
5519
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Concurrent ML operations. module(..., package.seeall) local fiber = require('lib.fibers.fiber') -- A suspension represents an instantiation of an operation that a fiber -- has to wait on because it can't complete directly. Some other event -- will cause the operation to complete and cause the fiber to resume. -- Since a suspension has a run method, it is also a task and so can be -- scheduled directly. local Suspension = {} Suspension.__index = Suspension local CompleteTask = {} CompleteTask.__index = CompleteTask function Suspension:waiting() return self.state == 'waiting' end function Suspension:complete(wrap, val) assert(self:waiting()) self.state = 'synchronized' self.wrap = wrap self.val = val self.sched:schedule(self) end function Suspension:complete_and_run(wrap, val) assert(self:waiting()) self.state = 'synchronized' return self.fiber:resume(wrap, val) end function Suspension:complete_task(wrap, val) return setmetatable({suspension=self, wrap=wrap, val=val}, CompleteTask) end function Suspension:run() -- Task method. assert(not self:waiting()) return self.fiber:resume(self.wrap, self.val) end local function new_suspension(sched, fiber) return setmetatable( { state='waiting', sched=sched, fiber=fiber }, Suspension) end -- A complete task is a task that when run, completes a suspension, if -- the suspension hasn't been completed already. There can be multiple -- complete tasks for a given suspension, if the suspension can complete -- in multiple ways (e.g. via a choice op). function CompleteTask:run() if self.suspension:waiting() then -- Use complete-and-run so that the fiber runs in this turn. self.suspension:complete_and_run(self.wrap, self.val) end end -- A complete task can also be cancelled, which makes it complete with a -- call to "error". function CompleteTask:cancel(reason) if self.suspension:waiting() then self.suspension:complete(error, reason or 'cancelled') end end -- An operation represents the potential for synchronization with some -- external party. An operation has to be instantiated by its "perform" -- method, as if it were a thunk. Note that Concurrent ML uses the term -- "event" for "operation", and "synchronize" with "perform". -- Base operations are the standard kind of operation. A base operation -- has three fields, which are all functions: "wrap_fn", which is called -- on the result of a successfully performed operation; "try_fn", which -- attempts to directly complete this operation in a non-blocking way; -- and "block_fn", which is called after a fiber has suspended, and -- which arranges to resume the fiber when the operation completes. local BaseOp = {} BaseOp.__index = BaseOp function new_base_op(wrap_fn, try_fn, block_fn) if wrap_fn == nil then wrap_fn = function(val) return val end end return setmetatable( { wrap_fn=wrap_fn, try_fn=try_fn, block_fn=block_fn }, BaseOp) end -- Choice operations represent a non-deterministic choice between a -- number of sub-operations. Performing a choice operation will perform -- at most one of its sub-operations. local ChoiceOp = {} ChoiceOp.__index = ChoiceOp local function new_choice_op(base_ops) return setmetatable( { base_ops=base_ops }, ChoiceOp) end -- Given a set of operations, return a new operation that if it -- succeeds, will succeed with one and only one of the sub-operations. function choice(...) local ops = {} -- Build a flattened list of choices that are all base ops. for _, op in ipairs({...}) do if op.base_ops then for _, op in ipairs(op.base_ops) do table.insert(ops, op) end else table.insert(ops, op) end end if #ops == 1 then return ops[1] end return new_choice_op(ops) end -- :wrap method -- -- Return a new operation that, if and when it succeeds, will apply F to -- the values yielded by performing the wrapped operation, and yield the -- result as the values of the wrapped operation. function BaseOp:wrap(f) local wrap_fn, try_fn, block_fn = self.wrap_fn, self.try_fn, self.block_fn return new_base_op(function(val) return f(wrap_fn(val)) end, try_fn, block_fn) end function ChoiceOp:wrap(f) local ops = {} for _, op in ipairs(self.base_ops) do table.insert(ops, op:wrap(f)) end return new_choice_op(ops) end -- :perform method -- -- Attempt to perform an operation, and return the resulting value (if -- any). If the operation can complete immediately, then return -- directly. Otherwise suspend the current fiber and continue only when -- the operation completes. local function block_base_op(sched, fiber, op) op.block_fn(new_suspension(sched, fiber), op.wrap_fn) end function BaseOp:perform() local success, val = self.try_fn() if success then return self.wrap_fn(val) end local wrap, val = fiber.suspend(block_base_op, self) return wrap(val) end local function block_choice_op(sched, fiber, ops) local suspension = new_suspension(sched, fiber) for _,op in ipairs(ops) do op.block_fn(suspension, op.wrap_fn) end end function ChoiceOp:perform() local ops = self.base_ops local base = math.random(#ops) for i=1,#ops do local op = ops[((i + base) % #ops) + 1] local success, val = op.try_fn() if success then return op.wrap_fn(val) end end local wrap, val = fiber.suspend(block_choice_op, ops) return wrap(val) end
apache-2.0
adib1380/inviter-2
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
RafiB/dotfiles
config/config.symlink/awesome/rc.lua
1
20099
-- Standard awesome library local gears = require("gears") local awful = require("awful") awful.rules = require("awful.rules") awful.autofocus = require("awful.autofocus") local wibox = require("wibox") local beautiful = require("beautiful") local naughty = require("naughty") local menubar = require("menubar") local vicious = require("vicious") local lain = require("lain") -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function (err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = err }) in_error = false end) end -- }}} -- {{{ Variable definitions home = os.getenv("HOME") confdir = home .. "/.config/awesome" themes = confdir .. "/themes" active_theme = themes .. "/blueberry" -- Themes define colours, icons, and wallpapers beautiful.init(active_theme.."/theme.lua") -- Custom Widgets local battery0 = require("battery0") local battery1 = require("battery1") local clock = require("clock") local cpu = require("cpu") local network = require("network") local ram = require("ram") local volume = require("volume") local menu = require("menu") -- This is used later as the default terminal and editor to run. terminal = "x-terminal-emulator" -- terminal = "urxvt" editor = os.getenv("EDITOR") or "vim" editor_cmd = terminal .. " -e " .. editor -- Default modkey. -- Usually, Mod4 is the key with a logo between Control and Alt. -- If you do not like this or do not have such a key, -- I suggest you to remap Mod4 to another key using xmodmap or other tools. -- However, you can use another modifier like Mod1, but it may interact with others. modkey = "Mod4" lain.layout.centerfair.ncol = 2 -- Table of layouts to cover with awful.layout.inc, order matters. local layouts = { lain.layout.centerwork, lain.layout.centerfair, awful.layout.suit.tile, lain.layout.uselesstile, awful.layout.suit.tile.bottom, lain.layout.uselesstile.bottom, awful.layout.suit.fair.horizontal, lain.layout.uselessfair.horizontal, awful.layout.suit.fair, lain.layout.uselessfair, awful.layout.suit.spiral.dwindle, awful.layout.suit.max, awful.layout.suit.max.fullscreen, awful.layout.suit.magnifier, } -- }}} -- {{{ Wallpaper if beautiful.wallpaper then for s = 1, screen.count() do gears.wallpaper.maximized(beautiful.wallpaper, s, true) end end -- }}} -- {{{ Tags -- Define a tag table which hold all screen tags. tags = {} for s = 1, screen.count() do -- Each screen has its own tag table. tags[s] = awful.tag({'1 coding ⌨', '2 shell', '3 web', '4 mail ✉', '5 music ♬', '6 im ☺', '7 other'}, s, layouts[1]) -- ⌬ ⌘ , '⏍', '⊛', '⚙' end -- Make lain.layout.centerfair nicer awful.tag.incnmaster(2) -- }}} -- Menubar configuration menubar.utils.terminal = terminal -- Set the terminal for applications that require it -- }}} -- {{{ Spacers rbracket = wibox.widget.textbox() rbracket:set_text(']') lbracket = wibox.widget.textbox() lbracket:set_text('[') line = wibox.widget.textbox() line:set_text('|') space = wibox.widget.textbox() space:set_text(' ') -- }}} -- {{{ Wibox -- -- Create a wibox for each screen and add it top_wibox = {} bottom_wibox = {} mypromptbox = {} mylayoutbox = {} mytaglist = {} mytaglist.buttons = awful.util.table.join( awful.button({ }, 1, awful.tag.viewonly), awful.button({ modkey }, 1, awful.client.movetotag), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, awful.client.toggletag), awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end), awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end) ) mytasklist = {} mytasklist.buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following -- :isvisible() makes no sense c.minimized = false if not c:isvisible() then awful.tag.viewonly(c:tags()[1]) end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end), awful.button({ }, 3, function () if instance then instance:hide() instance = nil else instance = awful.menu.clients({ width=250 }) end end), awful.button({ }, 4, function () awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end), awful.button({ }, 5, function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end)) for s = 1, screen.count() do -- Create a promptbox for each screen mypromptbox[s] = awful.widget.prompt() -- Create an imagebox widget which will contains an icon indicating which layout we're using. -- We need one layoutbox per screen. mylayoutbox[s] = awful.widget.layoutbox(s) mylayoutbox[s]:buttons(awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end), awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end))) -- Create a taglist widget mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, mytaglist.buttons) -- Create a tasklist widget mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons) -- Create the wibox top_wibox[s] = awful.wibox({ position = "top", screen = s }) bottom_wibox[s] = awful.wibox({ position = "bottom", screen = s}) -- Widgets that are aligned to the left local top_left_layout = wibox.layout.fixed.horizontal() top_left_layout:add(menu.launcher) top_left_layout:add(mytaglist[s]) top_left_layout:add(mypromptbox[s]) -- Widgets that are aligned to the right local top_right_layout = wibox.layout.fixed.horizontal() top_right_layout:add(network.downicon) top_right_layout:add(network.downwidget) top_right_layout:add(network.upicon) top_right_layout:add(network.upwidget) top_right_layout:add(cpu.icon) top_right_layout:add(cpu.widget) top_right_layout:add(ram.icon) top_right_layout:add(ram.widget) top_right_layout:add(battery1.icon) top_right_layout:add(battery1.widget) top_right_layout:add(battery0.icon) top_right_layout:add(battery0.widget) top_right_layout:add(volume.icon) top_right_layout:add(volume.widget) top_right_layout:add(space) top_right_layout:add(clock.widget) top_right_layout:add(space) top_right_layout:add(mylayoutbox[s]) -- Now bring it all together (with the tasklist in the middle) local top_layout = wibox.layout.align.horizontal() top_layout:set_left(top_left_layout) top_layout:set_right(top_right_layout) local bottom_left_layout = wibox.layout.fixed.horizontal() -- nothing for now local bottom_right_layout = wibox.layout.fixed.horizontal() if s == 1 then bottom_right_layout:add(wibox.widget.systray()) end local bottom_layout = wibox.layout.align.horizontal() bottom_layout:set_left(bottom_left_layout) bottom_layout:set_middle(mytasklist[s]) bottom_layout:set_right(bottom_right_layout) top_wibox[s]:set_widget(top_layout) bottom_wibox[s]:set_widget(bottom_layout) end -- }}} -- {{{ Mouse bindings root.buttons(awful.util.table.join( -- awful.button({ }, 3, function () mymainmenu:toggle() end), -- awful.button({ }, 4, awful.tag.viewnext), -- awful.button({ }, 5, awful.tag.viewprev) )) -- }}} -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "Left", awful.tag.viewprev ), awful.key({ modkey, }, "Right", awful.tag.viewnext ), awful.key({ modkey, }, "Escape", awful.tag.history.restore), awful.key({ modkey, }, "h", function () awful.client.focus.byidx( 1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "t", function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end), -- Layout manipulation awful.key({ modkey, "Shift" }, "h", function () awful.client.swap.byidx( 1) end), awful.key({ modkey, "Shift" }, "t", function () awful.client.swap.byidx( -1) end), awful.key({ modkey, "Control" }, "h", function () awful.screen.focus_relative( 1) end), awful.key({ modkey, "Control" }, "t", function () awful.screen.focus_relative(-1) end), awful.key({ modkey, }, "g", awful.client.urgent.jumpto), awful.key({ modkey, }, "Tab", function () awful.client.focus.history.previous() if client.focus then client.focus:raise() end end), -- Standard program awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end), -- awful.key({ modkey, "Control" }, "r", awesome.restart), awful.key({ modkey, "Control" }, "p", function() awful.util.spawn_with_shell("echo 'awesome.restart()' | awesome-client") end), awful.key({ modkey, "Shift" }, "'", awesome.quit), awful.key({ modkey, }, "n", function () awful.tag.incmwfact( 0.05) end), awful.key({ modkey, }, "d", function () awful.tag.incmwfact(-0.05) end), awful.key({ modkey, "Shift" }, "d", function () awful.tag.incnmaster( 1) end), awful.key({ modkey, "Shift" }, "n", function () awful.tag.incnmaster(-1) end), awful.key({ modkey, "Control" }, "d", function () awful.tag.incncol( 1) end), awful.key({ modkey, "Control" }, "n", function () awful.tag.incncol(-1) end), awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end), awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end), awful.key({ modkey, "Control" }, "b", awful.client.restore), -- Prompt awful.key({ modkey }, "r", function () mypromptbox[mouse.screen]:run() end), awful.key({ modkey }, "x", function () awful.prompt.run({ prompt = "Run Lua code: " }, mypromptbox[mouse.screen].widget, awful.util.eval, nil, awful.util.getdir("cache") .. "/history_eval") end), awful.key({ }, "XF86AudioRaiseVolume", function() awful.util.spawn("amixer -c 0 -q sset Master 9%+", false) end), awful.key({ }, "XF86AudioLowerVolume", function () awful.util.spawn("amixer -c 0 -q sset Master 9%-", false) end), awful.key({ }, "XF86AudioMute", function () awful.util.spawn("amixer -c 0 -q -D pulse set Master toggle", false) end), awful.key({ }, "XF86MonBrightnessUp", function () awful.util.spawn("brightness -inc 15", false) end), awful.key({ }, "XF86MonBrightnessDown", function () awful.util.spawn("brightness -dec 15", false) end), awful.key({ "Mod1", "Control" }, "l", function () awful.util.spawn("gnome-screensaver-command -l") end), -- Menubar awful.key({ modkey }, "p", function() menubar.show() end) ) clientkeys = awful.util.table.join( awful.key({ modkey, }, "u", function (c) c.fullscreen = not c.fullscreen end), awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end), awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ), awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end), awful.key({ modkey, }, "r", awful.client.movetoscreen ), awful.key({ modkey, }, "y", function (c) c.ontop = not c.ontop end), awful.key({ modkey, }, "b", function (c) -- The client currently has the input focus, so it cannot be -- minimized, since minimized clients can't have the focus. c.minimized = true end), awful.key({ modkey, }, "m", function (c) c.maximized_horizontal = not c.maximized_horizontal c.maximized_vertical = not c.maximized_vertical end) ) -- Compute the maximum number of digit we need, limited to 9 keynumber = 0 for s = 1, screen.count() do keynumber = math.min(9, math.max(#tags[s], keynumber)) end -- Bind all key numbers to tags. -- Be careful: we use keycodes to make it works on any keyboard layout. -- This should map on the top row of your keyboard, usually 1 to 9. for i = 1, keynumber do globalkeys = awful.util.table.join(globalkeys, awful.key({ modkey }, "#" .. i + 9, function () local screen = mouse.screen if tags[screen][i] then awful.tag.viewonly(tags[screen][i]) end end), awful.key({ modkey, "Control" }, "#" .. i + 9, function () local screen = mouse.screen if tags[screen][i] then awful.tag.viewtoggle(tags[screen][i]) end end), awful.key({ modkey, "Shift" }, "#" .. i + 9, function () if client.focus and tags[client.focus.screen][i] then awful.client.movetotag(tags[client.focus.screen][i]) end end), awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9, function () if client.focus and tags[client.focus.screen][i] then awful.client.toggletag(tags[client.focus.screen][i]) end end)) end clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize)) -- Set keys root.keys(globalkeys) -- }}} -- {{{ Rules awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, keys = clientkeys, buttons = clientbuttons, size_hints_honor = false, maximized_vertical = false, maximized_horizontal = false, } }, { rule = { class = "MPlayer" }, properties = { floating = true } }, { rule = { class = "pinentry" }, properties = { floating = true } }, { rule = { class = "gimp" }, properties = { floating = true } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal("manage", function (c, startup) -- Enable sloppy focus c:connect_signal("mouse::enter", function(c) if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier and awful.client.focus.filter(c) then client.focus = c end end) if not startup then -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- awful.client.setslave(c) -- Put windows in a smart way, only if they does not set an initial position. if not c.size_hints.user_position and not c.size_hints.program_position then awful.placement.no_overlap(c) awful.placement.no_offscreen(c) end end local titlebars_enabled = false if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(awful.titlebar.widget.iconwidget(c)) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(awful.titlebar.widget.floatingbutton(c)) right_layout:add(awful.titlebar.widget.maximizedbutton(c)) right_layout:add(awful.titlebar.widget.stickybutton(c)) right_layout:add(awful.titlebar.widget.ontopbutton(c)) right_layout:add(awful.titlebar.widget.closebutton(c)) -- The title goes in the middle local title = awful.titlebar.widget.titlewidget(c) title:buttons(awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) )) -- Now bring it all together local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_right(right_layout) layout:set_middle(title) awful.titlebar(c):set_widget(layout) end end) client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end) client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end) awful.util.spawn_with_shell("run_once redshift -l -33.925904:151.241307") awful.util.spawn_with_shell("run_once dropbox start") awful.util.spawn_with_shell("run_once xfce4-power-manager") awful.util.spawn_with_shell("ck-launch-session") awful.util.spawn_with_shell("run_once nm-applet") awful.util.spawn_with_shell("run_once shutter --min_at_startup") -- }}}
mit
alexandergall/snabbswitch
src/lib/yang/schema.lua
1
56697
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local mem = require("lib.stream.mem") local parser = require("lib.yang.parser") local util = require("lib.yang.util") local maxpc = require("lib.maxpc") local function error_with_loc(loc, msg, ...) error(string.format("%s: "..msg, loc, ...)) end local function assert_with_loc(expr, loc, msg, ...) if not expr then error_with_loc(loc, msg, ...) end return expr end local function shallow_copy(node) local out = {} for k,v in pairs(node) do out[k] = v end return out end -- (kind -> (function(Node) -> value)) local initializers = {} local function declare_initializer(init, ...) for _, keyword in ipairs({...}) do initializers[keyword] = init end end local function parse_node(src) local ret = {} ret.kind = assert(src.keyword, 'missing keyword') local children = parse_children(src) local initialize = initializers[ret.kind] if initialize then initialize(ret, src.loc, src.argument, children) end return ret end function parse_children(src) local ret = {} for i, statement in ipairs(src.statements or {}) do local child = parse_node(statement) if not ret[child.kind] then ret[child.kind] = {} end table.insert(ret[child.kind], child) end return ret end local function require_argument(loc, argument) return assert_with_loc(argument, loc, 'missing argument') end local function parse_range_or_length_arg(loc, kind, range) local function parse_part(part) local l, r = part:match("^%s*([^%.]*)%s*%.%.%s*([^%s]*)%s*$") if not r then l = part:match("^%s*([^%.]*)%s*$") r = (l ~= 'min') and l end assert_with_loc(l and r, loc, 'bad range component: %s', part) if l ~= 'min' then l = util.tointeger(l) end if r ~= 'max' then r = util.tointeger(r) end if l ~= 'min' and l < 0 and kind == 'length' then error("length argument may not be negative: "..l) end if r ~= 'max' and r < 0 and kind == 'length' then error("length argument may not be negative: "..r) end if l ~= 'min' and r ~= 'max' and r < l then error("invalid "..kind..": "..part) end return { l, r } end local res = {} for part in range:split("|") do table.insert(res, parse_part(part)) end if #res == 0 then error_with_loc(loc, "empty "..kind, range) end return res end local function collect_children(children, kinds) if type(kinds) == 'string' then return collect_children(children, {kinds}) end local ret = {} for _, kind in ipairs(kinds) do if children[kind] then for _, child in pairs(children[kind]) do table.insert(ret, child) end end end return ret end local function collect_children_by_prop(loc, children, kinds, prop) local ret = {} for _, child in ipairs(collect_children(children, kinds)) do assert_with_loc(child[prop], loc, 'child of kind %s missing prop %s', child.kind, prop) assert_with_loc(not ret[child[prop]], loc, 'duplicate %s: %s', prop, child[prop]) ret[child[prop]] = child end return ret end local function collect_children_by_id(loc, children, kinds) return collect_children_by_prop(loc, children, kinds, 'id') end local function collect_body_children(loc, children) return collect_children_by_id( loc, children, {'container', 'leaf', 'list', 'leaf-list', 'uses', 'choice', 'anyxml'}) end local function at_least_one(tab) for k, v in pairs(tab) do return true end return false end local function collect_body_children_at_least_1(loc, children) local ret = collect_body_children(loc, children) if not at_least_one(ret) then error_with_loc(loc, "missing data statements") end return ret end local function collect_data_or_case_children_at_least_1(loc, children) local ret = collect_children_by_id( loc, children, {'container', 'leaf', 'list', 'leaf-list', 'uses', 'choice', 'anyxml', 'case'}) if not at_least_one(ret) then error_with_loc(loc, "missing data statements") end return ret end local function collect_child_properties(children, kind, field) local ret = {} for _, child in ipairs(collect_children(children, kind)) do table.insert(ret, child[field]) end return ret end local function maybe_child(loc, children, kind) local children = collect_children(children, kind) if #children > 1 then error_with_loc(loc, 'expected at most one child of type %s', kind) end return children[1] end local function maybe_child_property(loc, children, kind, prop) local child = maybe_child(loc, children, kind) if child then return child[prop] end end local function require_child(loc, children, kind) local child = maybe_child(loc, children, kind) if child then return child end error_with_loc(loc, 'missing child of type %s', kind) end local function require_child_property(loc, children, kind, prop) return require_child(loc, children, kind)[prop] end -- Simple statement kinds with string, natural, or boolean values all -- just initialize by parsing their argument and storing it as the -- "value" property in the schema node. local function init_string(node, loc, argument, children) node.value = require_argument(loc, argument) end local function init_natural(node, loc, argument, children) local arg = require_argument(loc, argument) local as_num = tonumber(arg) assert_with_loc(as_num and math.floor(as_num) == as_num and as_num >= 0, loc, 'not a natural number: %s', arg) node.value = as_num end -- Must be one or 1 or 1.1. local function init_yang_version (node, loc, argument, children) local arg = require_argument(loc, argument) assert_with_loc(arg == "1" or arg == "1.1", 'not a valid version number: %s', arg) node.value = tonumber(arg) end local function init_boolean(node, loc, argument, children) local arg = require_argument(loc, argument) if arg == 'true' then node.value = true elseif arg == 'false' then node.value = false else error_with_loc(loc, 'not a valid boolean: %s', arg) end end -- For all other statement kinds, we have custom initializers that -- parse out relevant sub-components and store them as named -- properties on the schema node. local function init_anyxml(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.must = collect_child_properties(children, 'must', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.mandatory = maybe_child_property(loc, children, 'mandatory', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_argument(node, loc, argument, children) node.id = require_argument(loc, argument) node.yin_element = maybe_child_property(loc, children, 'yin-element', 'value') end local function init_augment(node, loc, argument, children) node.node_id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.body = collect_data_or_case_children_at_least_1(loc, children) end local function init_belongs_to(node, loc, argument, children) node.id = require_argument(loc, argument) node.prefix = require_child(loc, children, 'prefix').value end local function init_case(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.body = collect_body_children(loc, children) end local function init_choice(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.default = maybe_child_property(loc, children, 'default', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.mandatory = maybe_child_property(loc, children, 'mandatory', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_children_by_id( loc, children, {'container', 'leaf', 'leaf-list', 'list', 'anyxml', 'case'}) end local function init_container(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.must = collect_child_properties(children, 'must', 'value') node.presence = maybe_child_property(loc, children, 'presence', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children(loc, children) end local function init_extension(node, loc, argument, children) node.id = require_argument(loc, argument) node.argument = maybe_child_property(loc, children, 'argument', 'id') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_feature(node, loc, argument, children) node.id = require_argument(loc, argument) node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_grouping(node, loc, argument, children) node.id = require_argument(loc, argument) node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children(loc, children) end local function init_identity(node, loc, argument, children) node.id = require_argument(loc, argument) node.bases = collect_child_properties(children, 'base', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_import(node, loc, argument, children) node.id = require_argument(loc, argument) node.prefix = require_child_property(loc, children, 'prefix', 'value') node.revision_date = maybe_child_property(loc, children, 'revision-date', 'value') end local function init_include(node, loc, argument, children) node.id = require_argument(loc, argument) node.revision_date = maybe_child_property(loc, children, 'revision-date', 'value') end local function init_input(node, loc, argument, children) node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children_at_least_1(loc, children) end local function init_leaf(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.type = require_child(loc, children, 'type') node.units = maybe_child_property(loc, children, 'units', 'value') node.must = collect_child_properties(children, 'must', 'value') node.default = maybe_child_property(loc, children, 'default', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.mandatory = maybe_child_property(loc, children, 'mandatory', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_leaf_list(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.type = require_child(loc, children, 'type') node.units = maybe_child_property(loc, children, 'units', 'value') node.must = collect_child_properties(children, 'must', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.min_elements = maybe_child_property(loc, children, 'min-elements', 'value') node.max_elements = maybe_child_property(loc, children, 'max-elements', 'value') node.ordered_by = maybe_child_property(loc, children, 'ordered-by', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_length(node, loc, argument, children) node.value = parse_range_or_length_arg(loc, node.kind, require_argument(loc, argument)) node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_list(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.must = collect_child_properties(children, 'must', 'value') node.key = maybe_child_property(loc, children, 'key', 'value') node.unique = collect_child_properties(children, 'unique', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.min_elements = maybe_child_property(loc, children, 'min-elements', 'value') node.max_elements = maybe_child_property(loc, children, 'max-elements', 'value') node.ordered_by = maybe_child_property(loc, children, 'ordered-by', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children_at_least_1(loc, children) node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_module(node, loc, argument, children) node.id = require_argument(loc, argument) node.yang_version = maybe_child_property(loc, children, 'yang-version', 'value') node.namespace = require_child_property(loc, children, 'namespace', 'value') node.prefix = require_child_property(loc, children, 'prefix', 'value') node.imports = collect_children_by_prop(loc, children, 'import', 'prefix') node.includes = collect_children_by_id(loc, children, 'include') node.organization = maybe_child_property(loc, children, 'organization', 'value') node.contact = maybe_child_property(loc, children, 'contact', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.revisions = collect_children(children, 'revision') node.augments = collect_children(children, 'augment') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.features = collect_children_by_id(loc, children, 'feature') node.extensions = collect_children_by_id(loc, children, 'extension') node.identities = collect_children_by_id(loc, children, 'identity') node.rpcs = collect_children_by_id(loc, children, 'rpc') node.notifications = collect_children_by_id(loc, children, 'notification') node.deviations = collect_children_by_id(loc, children, 'deviation') node.body = collect_body_children(loc, children) end local function init_namespace(node, loc, argument, children) -- TODO: parse uri? node.value = require_argument(loc, argument) end local function init_notification(node, loc, argument, children) node.id = require_argument(loc, argument) node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children(loc, children) end local function init_output(node, loc, argument, children) node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.body = collect_body_children_at_least_1(loc, children) end local function init_path(node, loc, argument, children) -- TODO: parse path string node.value = require_argument(loc, argument) end local function init_pattern(node, loc, argument, children) node.value = require_argument(loc, argument) node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_range(node, loc, argument, children) node.value = parse_range_or_length_arg(loc, node.kind, require_argument(loc, argument)) node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_enum(node, loc, argument, children) node.name = require_argument(loc, argument) local value = maybe_child_property(loc, children, 'value', 'value') if value then node.value = tonumber(value) end node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') end local function init_refine(node, loc, argument, children) node.node_id = require_argument(loc, argument) -- All subnode kinds. node.must = collect_child_properties(children, 'must', 'value') node.config = maybe_child_property(loc, children, 'config', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') -- Containers. node.presence = maybe_child_property(loc, children, 'presence', 'value') -- Leaves, choice, and (for mandatory) anyxml. node.default = maybe_child_property(loc, children, 'default', 'value') node.mandatory = maybe_child_property(loc, children, 'mandatory', 'value') -- Leaf lists and lists. node.min_elements = maybe_child_property(loc, children, 'min-elements', 'value') node.max_elements = maybe_child_property(loc, children, 'max-elements', 'value') end local function init_revision(node, loc, argument, children) -- TODO: parse date node.date = require_argument(loc, argument) node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_rpc(node, loc, argument, children) node.id = require_argument(loc, argument) node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.input = maybe_child(loc, children, 'input') node.output = maybe_child(loc, children, 'output') end local function init_type(node, loc, argument, children) node.id = require_argument(loc, argument) node.range = maybe_child(loc, children, 'range') node.fraction_digits = maybe_child_property(loc, children, 'fraction-digits', 'value') node.length = maybe_child(loc, children, 'length') node.patterns = collect_children(children, 'pattern') node.enums = collect_children(children, 'enum') -- !!! path node.leafref = maybe_child_property(loc, children, 'path', 'value') node.require_instances = collect_children(children, 'require-instance') node.bases = collect_child_properties(children, 'base', 'value') node.union = collect_children(children, 'type') node.bits = collect_children(children, 'bit') end local function init_submodule(node, loc, argument, children) node.id = require_argument(loc, argument) node.yang_version = maybe_child_property(loc, children, 'yang-version', 'value') node.belongs_to = require_child(loc, children, 'belongs-to') node.imports = collect_children_by_id(loc, children, 'import') node.includes = collect_children_by_id(loc, children, 'include') node.organization = maybe_child_property(loc, children, 'organization', 'value') node.contact = maybe_child_property(loc, children, 'contact', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.revisions = collect_children(children, 'revision') node.augments = collect_children(children, 'augment') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.groupings = collect_children_by_id(loc, children, 'grouping') node.features = collect_children_by_id(loc, children, 'feature') node.extensions = collect_children_by_id(loc, children, 'extension') node.identities = collect_children_by_id(loc, children, 'identity') node.rpcs = collect_children_by_id(loc, children, 'rpc') node.notifications = collect_children_by_id(loc, children, 'notification') node.deviations = collect_children_by_id(loc, children, 'deviation') node.body = collect_body_children(loc, children) end local function init_typedef(node, loc, argument, children) node.id = require_argument(loc, argument) node.type = require_child(loc, children, 'type') node.units = maybe_child_property(loc, children, 'units', 'value') node.default = maybe_child_property(loc, children, 'default', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') end local function init_uses(node, loc, argument, children) node.id = require_argument(loc, argument) node.when = maybe_child_property(loc, children, 'when', 'value') node.if_features = collect_child_properties(children, 'if-feature', 'value') node.status = maybe_child_property(loc, children, 'status', 'value') node.description = maybe_child_property(loc, children, 'description', 'value') node.reference = maybe_child_property(loc, children, 'reference', 'value') node.typedefs = collect_children_by_id(loc, children, 'typedef') node.refines = collect_children(children, 'refine') node.augments = collect_children(children, 'augment') end local function init_value(node, loc, argument, children) local arg = require_argument(loc, argument) local as_num = tonumber(arg) assert_with_loc(as_num and math.floor(as_num) == as_num, loc, 'not an integer: %s', arg) node.value = as_num end declare_initializer( init_string, 'prefix', 'organization', 'contact', 'description', 'reference', 'units', 'revision-date', 'base','if-feature', 'default', 'enum', 'bit', 'status', 'presence', 'ordered-by', 'must', 'error-message', 'error-app-tag', 'max-value', 'key', 'unique', 'when', 'deviation', 'deviate') declare_initializer( init_natural, 'fraction-digits', 'position', 'min-elements', 'max-elements') declare_initializer(init_yang_version, 'yang-version') declare_initializer( init_boolean, 'config', 'mandatory', 'require-instance', 'yin-element') declare_initializer(init_anyxml, 'anyxml') declare_initializer(init_argument, 'argument') declare_initializer(init_augment, 'augment') declare_initializer(init_belongs_to, 'belongs-to') declare_initializer(init_case, 'case') declare_initializer(init_choice, 'choice') declare_initializer(init_container, 'container') declare_initializer(init_extension, 'extension') declare_initializer(init_feature, 'feature') declare_initializer(init_grouping, 'grouping') declare_initializer(init_identity, 'identity') declare_initializer(init_import, 'import') declare_initializer(init_include, 'include') declare_initializer(init_input, 'input') declare_initializer(init_leaf, 'leaf') declare_initializer(init_leaf_list, 'leaf-list') declare_initializer(init_length, 'length') declare_initializer(init_list, 'list') declare_initializer(init_module, 'module') declare_initializer(init_namespace, 'namespace') declare_initializer(init_notification, 'notification') declare_initializer(init_output, 'output') declare_initializer(init_path, 'path') declare_initializer(init_pattern, 'pattern') declare_initializer(init_range, 'range') declare_initializer(init_enum, 'enum') declare_initializer(init_refine, 'refine') declare_initializer(init_revision, 'revision') declare_initializer(init_rpc, 'rpc') declare_initializer(init_submodule, 'submodule') declare_initializer(init_type, 'type') declare_initializer(init_typedef, 'typedef') declare_initializer(init_uses, 'uses') declare_initializer(init_value, 'value') local function schema_from_ast(ast) local ret local submodules = {} for _,node in ipairs(ast) do if node.keyword == 'module' then assert(not ret, 'expected only one module form') ret = parse_node(node) elseif node.keyword == 'submodule' then assert(not submodules[node.id], 'duplicate submodule name: '..node.id) submodules[node.id] = parse_node(node) else error('expected only module and submodule statements, got: '..node.keyword) end end assert(ret, 'missing module form') ret.submodules = submodules return ret end local primitive_types = lib.set( 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'binary', 'bits', 'boolean', 'decimal64', 'empty', 'enumeration', 'identityref', 'instance-identifier', 'leafref', 'string', 'union') -- Inherits config attributes from parents local function inherit_config(schema) local function visit(node, config) if node.config == nil then node = shallow_copy(node) node.config = config elseif node.config == false then config = node.config else assert(config) end if node.body then node.body = shallow_copy(node.body) for name, child in pairs(node.body) do node.body[name] = visit(child, config) end end return node end return visit(schema, true) end local default_features = {} function get_default_capabilities() local ret = {} for mod,features in pairs(default_features) do local feature_names = {} for feature,_ in pairs(features) do table.insert(feature_names, feature) end ret[mod] = { feature = feature_names } end return ret end function set_default_capabilities(capabilities) default_features = {} for mod,caps in pairs(capabilities) do default_features[mod] = {} for _,feature in ipairs(caps.feature) do default_features[mod][feature] = true end end end -- Parse/interpret YANG 1.1 if-feature expressions -- https://tools.ietf.org/html/rfc7950#section-7.20.2 local if_feature_expr_parser = (function () local match, capture, combine = maxpc.import() local refs = {} local function ref (s) return function (...) return refs[s](...) end end local function wsp_lf() return combine._or(match.equal(' '), match.equal('\t'), match.equal('\n'), match.equal('\r')) end local function sep() return combine.some(wsp_lf()) end local function optsep() return combine.any(wsp_lf()) end local function keyword(s) return match.string(s) end local function identifier() -- [a-zA-Z_][a-zA-Z0-9_-.:]+ local alpha_ = match.satisfies(function (x) return ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_") :find(x, 1, true) end) local digit_punct = match.satisfies(function (x) return ("0123456789-."):find(x, 1, true) end) return capture.subseq( match.seq(alpha_, combine.any(combine._or(alpha_, digit_punct))) ) end local function identifier_ref() local idref = capture.seq( identifier(), combine.maybe(match.equal(":")), combine.maybe(identifier()) ) local function ast_idref (mod_or_id, _, id) return {'feature', id or mod_or_id, id and mod_or_id or nil} end return capture.unpack(idref, ast_idref) end local function if_feature_not() local not_feature = capture.seq( keyword'not', sep(), ref'if_feature_factor' ) local function ast_not (_, _, fact) return {'not', fact} end return capture.unpack(not_feature, ast_not) end local function if_feature_subexpr() local subexpr = capture.seq( match.equal("("), optsep(), ref'if_feature_expr', optsep(), match.equal(")") ) local function ast_subexpr (_, _, expr) return {'subexpr', expr} end return capture.unpack(subexpr, ast_subexpr) end local function if_feature_factor () return combine._or( if_feature_not(), if_feature_subexpr(), identifier_ref() ) end refs.if_feature_factor = if_feature_factor() local function if_feature_and() local and_feature = capture.seq( if_feature_factor(), sep(), keyword'and', sep(), ref'if_feature_term' ) local function ast_and (a, _, _, _, b) return {'and', a, b} end return capture.unpack(and_feature, ast_and) end local function if_feature_term() return combine._or(if_feature_and(), if_feature_factor()) end refs.if_feature_term = if_feature_term() local function if_feature_or() local or_feature = capture.seq( if_feature_term(), sep(), keyword'or', sep(), ref'if_feature_expr' ) local function ast_or (a, _, _, _, b) return {'or', a, b} end return capture.unpack(or_feature, ast_or) end local function if_feature_expr() return combine._or(if_feature_or(), if_feature_term()) end refs.if_feature_expr = if_feature_expr() return refs.if_feature_expr end)() local function parse_if_feature_expr(expr) local ast, success, eof = maxpc.parse(expr, if_feature_expr_parser) assert(success and eof, "Error parsing if-feature-expression: "..expr) return ast end local function interpret_if_feature(expr, has_feature_p) local function interpret (ast) local op, a, b = unpack(ast) if op == 'feature' then return has_feature_p(a, b) elseif op == 'or' then if interpret(a) then return true else return interpret(b) end elseif op == 'and' then return interpret(a) and interpret(b) elseif op == 'subexpr' then return interpret(a) end end return interpret(parse_if_feature_expr(expr)) end -- Inline "grouping" into "uses". -- Inline "submodule" into "include". -- Inline "imports" into "module". -- Inline "typedef" into "type". -- Resolve if-feature, identity bases, and identityref bases. -- Warn on any "when", resolving them as being true. -- Resolve all augment nodes. (TODO) function resolve(schema, features) if features == nil then features = default_features end local function pop_prop(node, prop) local val = node[prop] node[prop] = nil return val end local function lookup(env, prop, name) if not env then error(prop..' not found: '..name) end if not env[prop] or not env[prop][name] then return lookup(env.env, prop, name) end return env[prop][name] end local function lookup_lazy(env, prop, name) local val = lookup(env, prop, name) if type(val) == 'table' then return val end -- Force lazy expansion and memoize result. return val() end local visit local function visit_top_level(node, env, prop) assert(not env[prop]) env[prop] = {} local p = lookup(env, 'prefix', '_') for k,v in pairs(pop_prop(node, prop) or {}) do env[prop][k] = visit(v, env) env[prop][p..':'..k] = env[prop][k] end end local function visit_lazy(tab, env) local ret = {} local prefix = lookup(env, 'prefix', '_') local function error_recursion() end for k,v in pairs(tab) do -- FIXME: Only add prefix:k if at top level. local state local function lazy() if state == 'visiting' then error('mutually recursive definitions: '..k) elseif state then return state else state = 'visiting' end state = visit(v, env) return state end ret[k] = lazy ret[prefix..':'..k] = ret[k] end return ret end -- Resolve argument of "base" statements to identity fqid and collect in a list. local function resolve_bases(bases, env) local ret = {} for _, base in ipairs(bases) do table.insert(ret, lookup_lazy(env, 'identities', base).fqid) end return ret end local function visit_type(node, env) node = shallow_copy(node) local success, typedef = pcall(lookup, env, 'typedefs', node.id) if success then -- Typedefs are lazy, so force their value. We didn't use -- lookup_lazy because we don't want the pcall to hide errors -- from the lazy expansion. typedef = typedef() assert(typedef.kind == "typedef") node.base_type = typedef node.primitive_type = assert(typedef.primitive_type) node.enums = {} for _, enum in ipairs(typedef.type.enums) do node.enums[enum.name] = true end node.union = typedef.type.union else -- If the type name wasn't bound, it must be primitive. assert(primitive_types[node.id], 'unknown type: '..node.id) if node.id == 'union' then local union = {} for _,type in ipairs(node.union) do table.insert(union, visit_type(type, env)) end node.union = union elseif node.id == 'identityref' then node.bases = resolve_bases(node.bases, env) node.default_prefix = schema.id elseif node.id == 'enumeration' then local values = {} local max_value = -2147483648 for i, enum in ipairs(node.enums) do assert(not node.enums[enum.name], 'duplicate name in enumeration: '..enum.name) node.enums[enum.name] = enum if enum.value then assert(not values[enum.value], 'duplicate value in enumeration: '..enum.value) values[enum.value] = true max_value = math.max(enum.value, max_value) elseif i == 1 then max_value = 0 enum.value = max_value elseif max_value < 2147483647 then max_value = max_value + 1 enum.value = max_value else error('explicit value required in enum: '..enum.name) end end end node.primitive_type = node.id end return node end -- Already made "local" above. function visit(node, env) node = shallow_copy(node) env = {env=env} if node.typedefs then -- Populate node.typedefs as a table of thunks that will -- lazily expand and memoize their result when called. This -- is not only a performance optimization but also allows the -- typedefs to be mutually visible. env.typedefs = visit_lazy(pop_prop(node, 'typedefs'), env) end if node.groupings then -- Likewise expand groupings at their point of definition. env.groupings = visit_lazy(pop_prop(node, 'groupings'), env) end local when = pop_prop(node, 'when') if when then print('warning: assuming "when" condition to be true: '..when.value) end if node.kind == 'module' or node.kind == 'submodule' then visit_top_level(node, env, 'extensions') -- Because features can themselves have if-feature, and -- identities can reference each other, expand them lazily. env.features = visit_lazy(pop_prop(node, 'features'), env) env.identities = visit_lazy(pop_prop(node, 'identities'), env) for _,prop in ipairs({'rpcs', 'notifications'}) do node[prop] = shallow_copy(node[prop]) for k,v in pairs(node[prop]) do node[prop][k] = visit(v, env) end end local last_revision = nil for _,revision in ipairs(node.revisions) do if last_revision == nil or last_revision < revision.date then last_revision = revision.date end end node.last_revision = last_revision end if node.kind == 'rpc' then if node.input then node.input = visit(node.input, env) end if node.output then node.output = visit(node.output, env) end end if node.kind == 'identity' then -- Attach fully-qualified identity. node.fqid = lookup(env, 'module_id', '_')..":"..node.id node.bases = resolve_bases(node.bases, env) end if node.kind == 'feature' then node.module_id = lookup(env, 'module_id', '_') if not (features[node.module_id] or {})[node.id] then node.unavailable = true end end for _,expr in ipairs(pop_prop(node, 'if_features') or {}) do local function resolve_feature (feature, mod) assert(not mod, "NYI: module qualified features in if-feature expression") local feature_node = lookup_lazy(env, 'features', feature) if node.kind == 'feature' then -- This is a feature that depends on a feature. These we -- keep in the environment but if the feature is -- unavailable, we mark it as such. local mod, id = feature_node.module_id, feature_node.id if (features[mod] or {})[id] then return true else node.unavailable = true end elseif not feature_node.unavailable then return true end end if not interpret_if_feature(expr, resolve_feature) then return nil, env end end if node.type then node.type = visit_type(node.type, env) if not node.primitive_type then node.primitive_type = node.type.primitive_type end end if node.body then local body = node.body node.body = {} for k,v in pairs(body) do if v.kind == 'uses' then -- Inline "grouping" into "uses". local grouping = lookup_lazy(env, 'groupings', v.id) for k,v in pairs(grouping.body) do assert(not node.body[k], 'duplicate identifier: '..k) node.body[k] = v end for _,refine in ipairs(v.refines) do local target = node.body[refine.node_id] assert(target, 'missing refine node: '..refine.node_id) -- FIXME: Add additional "must" statements. for _,k in ipairs({'config', 'description', 'reference', 'presence', 'default', 'mandatory', 'min_elements', 'max_elements'}) do if refine[k] ~= nil then target[k] = refine[k] end end end -- TODO: Handle augment statements. else assert(not node.body[k], 'duplicate identifier: '..k) node.body[k] = visit(v, env) end end end -- Mark "key" children of lists as being mandatory. if node.kind == 'list' and node.key then for k in node.key:split(' +') do local leaf = assert(node.body[k]) leaf.mandatory = true end end return node, env end local function include(dst, src) for k,v in pairs(src) do assert(dst[k] == nil or dst[k] == v, 'incompatible definitions: '..k) if not k:match(':') then dst[k] = v end end end local linked = {} local function link(node, env) if linked[node.id] then assert(linked[node.id] ~= 'pending', 'recursive import of '..node.id) local node, env = unpack(linked[node.id]) return node, env end linked[node.id] = 'pending' node = shallow_copy(node) local module_env = {env=env, prefixes={}, extensions={}, features={}, identities={}, typedefs={}, groupings={}, module_id={_=node.id}} node.body = shallow_copy(node.body) node.rpcs = shallow_copy(node.rpcs) node.notifications = shallow_copy(node.notifications) for k,v in pairs(pop_prop(node, 'includes')) do local submodule = lookup(env, 'submodules', k) assert(submodule.belongs_to.id == node.id) submodule, submodule_env = link(submodule, env) include(module_env.extensions, submodule_env.extensions) include(module_env.features, submodule_env.features) include(module_env.identities, submodule_env.identities) include(module_env.typedefs, submodule_env.typedefs) include(module_env.groupings, submodule_env.groupings) include(node.body, submodule.body) include(node.rpcs, submodule.rpcs) include(node.notifications, submodule.notifications) end if node.prefix then assert(node.kind == 'module', node.kind) module_env.prefixes[node.prefix] = node.id module_env.prefix = {_=node.prefix} end for k,v in pairs(pop_prop(node, 'imports')) do assert(not module_env.prefixes[v.prefix], 'duplicate prefix') -- CHECKME: Discarding body from import, just importing env. -- Is this OK? local schema, env = load_schema_by_name(v.id, v.revision_date) local prefix = v.prefix module_env.prefixes[prefix] = schema.id for _,prop in ipairs({'extensions', 'features', 'identities', 'typedefs', 'groupings'}) do for k,v in pairs(env[prop]) do if not k:match(':') then module_env[prop][prefix..':'..k] = v end end end end node, env = visit(node, module_env) -- The typedefs, groupings, identities, and so on of this module -- are externally visible for other modules that may import this -- one; save them and their environment. linked[node.id] = {node, env} return node, env end schema = shallow_copy(schema) return link(schema, {submodules=pop_prop(schema, 'submodules')}) end local primitive_types = { ['ietf-inet-types']=lib.set('ipv4-address', 'ipv6-address', 'ipv4-prefix', 'ipv6-prefix'), ['ietf-yang-types']=lib.set('mac-address') } -- NB: mutates schema in place! local function primitivize(schema) for k, _ in pairs(primitive_types[schema.id] or {}) do assert(schema.typedefs[k]).primitive_type = k end return schema end function parse_schema(src, filename) return schema_from_ast(parser.parse(mem.open_input_string(src, filename))) end function parse_schema_file(filename) return schema_from_ast(parser.parse(assert(file.open(filename)))) end local function collect_uniqueness (s) local leaves = {} local function mark (id) if leaves[id] then return false end leaves[id] = true return true end local function visit (node) if not node then return end for k,v in pairs(node) do if type(v) == 'table' then visit(v) else if k == 'kind' and v == 'leaf' then node.is_unique = mark(node.id) end end end end visit(s) return s end function load_schema(src, filename) local s, e = resolve(primitivize(parse_schema(src, filename))) return collect_uniqueness(inherit_config(s)), e end function load_schema_file(filename) local s, e = resolve(primitivize(parse_schema_file(filename))) return collect_uniqueness(inherit_config(s)), e end load_schema_file = util.memoize(load_schema_file) function load_schema_source_by_name(name, revision) -- FIXME: @ is not valid in a Lua module name. -- if revision then name = name .. '@' .. revision end name = name:gsub('-', '_') return require('lib.yang.'..name..'_yang') end function load_schema_by_name(name, revision) return load_schema(load_schema_source_by_name(name, revision)) end load_schema_by_name = util.memoize(load_schema_by_name) function add_schema(src, filename) -- Assert that the source actually parses, and get the ID. local s, e = load_schema(src, filename) -- Assert that this schema isn't known. assert(not pcall(load_schema_source_by_name, s.id)) assert(s.id) -- Intern. package.loaded['lib.yang.'..s.id:gsub('-', '_')..'_yang'] = src return s.id end function add_schema_file(filename) local file_in = assert(io.open(filename)) local contents = file_in:read("*a") file_in:close() return add_schema(contents, filename) end function lookup_identity (fqid) local schema_name, id = fqid:match("^([^:]*):(.*)$") local schema, env = load_schema_by_name(schema_name) local id_thunk = env.identities[id] if not id_thunk then error('no identity '..id..' in module '..schema_name) end return id_thunk() -- Force the lazy lookup. end lookup_identity = util.memoize(lookup_identity) function identity_is_instance_of (identity, fqid) for _, base in ipairs(identity.bases) do if base == fqid then return true end local base_id = lookup_identity(base) if identity_is_instance_of(base_id, fqid) then return true end end return false end identity_is_instance_of = util.memoize(identity_is_instance_of) function selftest() print('selftest: lib.yang.schema') set_default_capabilities(get_default_capabilities()) local test_schema = [[module fruit { namespace "urn:testing:fruit"; prefix "fruit"; import ietf-inet-types {prefix inet; } import ietf-yang-types {prefix yang; } organization "Fruit Inc."; contact "John Smith fake@person.tld"; description "Module to test YANG schema lib"; revision 2016-05-27 { description "Revision 1"; reference "tbc"; } revision 2016-05-28 { description "Revision 2"; reference "tbc"; } feature bowl { description "A fruit bowl"; reference "fruit-bowl"; } identity foo; identity bar { base foo; } identity baz { base bar; base foo; } grouping fruit { description "Represents a piece of fruit"; leaf name { type string; mandatory true; description "Name of fruit."; } leaf score { type uint8 { range 0..10; } mandatory true; description "How nice is it out of 10"; } leaf tree-grown { type boolean; description "Is it grown on a tree?"; } } container fruit-bowl { description "Represents a fruit bowl"; leaf description { type string; description "About the bowl"; } list contents { uses fruit; } } }]] local schema, env = load_schema(test_schema) assert(schema.id == "fruit") assert(schema.namespace == "urn:testing:fruit") assert(schema.prefix == "fruit") assert(schema.contact == "John Smith fake@person.tld") assert(schema.organization == "Fruit Inc.") assert(schema.description == "Module to test YANG schema lib") assert(schema.last_revision == "2016-05-28") -- Check all revisions are accounted for. assert(schema.revisions[1].description == "Revision 1") assert(schema.revisions[1].date == "2016-05-27") assert(schema.revisions[2].description == "Revision 2") assert(schema.revisions[2].date == "2016-05-28") -- Check that the feature statements are in the exports interface -- but not the schema itself. assert(not schema.features) assert(env.features["bowl"]) -- Poke through lazy features abstraction by invoking thunk. assert(env.features["bowl"]().description == 'A fruit bowl') -- Poke through lazy identity bases by invoking thunk. assert(#env.identities["baz"]().bases == 2) assert(#env.identities["bar"]().bases == 1) assert(env.identities["bar"]().bases[1] == 'fruit:foo') assert(#env.identities["foo"]().bases == 0) assert(#lookup_identity("ietf-alarms:alarm-identity").bases == 0) -- Check that groupings get inlined into their uses. assert(schema.body['fruit-bowl']) assert(schema.body['fruit-bowl'].description == 'Represents a fruit bowl') local contents = schema.body['fruit-bowl'].body['contents'] assert(contents) assert(contents.kind == 'list') -- TODO: Copy description over? Probably not given that one node -- can use multiple groupings. -- assert(contents.description == 'Represents a piece of fruit') assert(contents.body['name'].kind == 'leaf') assert(contents.body['name'].type.id == 'string') assert(contents.body["name"].mandatory == true) assert(contents.body["name"].description == "Name of fruit.") assert(contents.body["score"].type.id == "uint8") assert(contents.body["score"].mandatory == true) local equal = require('core.lib').equal assert(equal(contents.body["score"].type.range.value, {{0, 10}})) -- Check the container has a leaf called "description" local desc = schema.body["fruit-bowl"].body['description'] assert(desc.type.id == "string") assert(desc.description == "About the bowl") parse_schema(require('lib.yang.ietf_yang_types_yang')) parse_schema(require('lib.yang.ietf_inet_types_yang')) load_schema_by_name('ietf-yang-types') -- We could save and restore capabilities to avoid the persistent -- side effect, but it would do no good: the schemas would be -- memoized when the features were present. So just add to the -- capabilities, for now, assuming tests are run independently from -- programs. local caps = get_default_capabilities() local new_caps = { ['ietf-softwire-br'] = {feature={'binding-mode'}} } for mod_name, mod_caps in pairs(new_caps) do if not caps[mod_name] then caps[mod_name] = {feature={}} end for _,feature in ipairs(mod_caps.feature) do table.insert(caps[mod_name].feature, feature) end end set_default_capabilities(caps) load_schema_by_name('ietf-softwire-common') load_schema_by_name('ietf-softwire-br') load_schema_by_name('snabb-softwire-v2') local br = load_schema_by_name('ietf-softwire-br') local binding = br.body['br-instances'].body['br-type'].body['binding'] assert(binding) local bt = binding.body['binding'].body['bind-instance'].body['binding-table'] assert(bt) local ps = bt.body['binding-entry'].body['port-set'] assert(ps) local alg = br.body['br-instances'].body['br-type'].body['algorithm'] assert(not alg) -- The binding-entry grouping is defined in ietf-softwire-common and -- imported by ietf-softwire-br, but with a refinement that the -- default is 0. Test that the refinement was applied. assert(ps.body['psid-offset'].default == "0") local inherit_config_schema = [[module config-inheritance { namespace cs; prefix cs; container foo { container bar { config false; leaf baz { type uint8; } } } grouping quux { leaf quuz { type uint8; } } container corge { uses quux; } container grault { config true; uses quux; } container garply { config false; uses quux; } }]] local icschema = load_schema(inherit_config_schema) -- Test things that should be null, still are. assert(icschema.config == true) assert(icschema.body.foo.config == true) -- Assert the regular config is propergated through container. assert(icschema.body.foo.body.bar.config == false) assert(icschema.body.foo.body.bar.body.baz.config == false) -- Now test the grouping, we need to ensure copying is done correctly. assert(icschema.body.corge.config == true) assert(icschema.body.corge.body.quuz.config == true) assert(icschema.body.grault.config == true) assert(icschema.body.grault.body.quuz.config == true) assert(icschema.body.garply.config == false) assert(icschema.body.garply.body.quuz.config == false) -- Test Range with explicit value. assert(lib.equal(parse_range_or_length_arg(nil, nil, "42"), {{42, 42}})) -- Parsing/interpreting if-feature expressions local function test_features (i, m) local f = { b_99 = { ["c.d"] = true }, [0] = { bar = true } } return f[m or 0][i] end local expr = "baz and foo or bar and (a or b_99:c.d)" assert(interpret_if_feature(expr, test_features)) assert(not interpret_if_feature("boo", test_features)) assert(not interpret_if_feature("baz or foo", test_features)) print('selftest: ok') end
apache-2.0
xuejian1354/barrier_breaker
feeds/luci/applications/luci-radvd/luasrc/model/cbi/radvd/prefix.lua
74
3766
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Prefix"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "prefix" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("advanced", translate("Advanced")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"), translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used")) o.optional = true o.datatype = "ip6addr" o.placeholder = translate("default") function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "prefix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"), translate("Indicates that this prefix can be used for on-link determination (RFC4861)")) o.rmempty = false o.default = "1" o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"), translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)")) o.rmempty = false o.default = "1" -- -- Advanced -- o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"), translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6")) o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"), translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 86400 o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"), translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 14400 o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"), translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option")) o.template = "cbi/network_netlist" o.nocreate = true o.unspecified = true return m
gpl-2.0
ioiasff/sosia
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
sullome/km-freeminer-mods
mods/jabber/lib/verse/client.lua
2
6104
local verse = require "verse"; local stream = verse.stream_mt; local jid_split = require "util.jid".split; local adns = require "net.adns"; local lxp = require "lxp"; local st = require "util.stanza"; -- Shortcuts to save having to load util.stanza verse.message, verse.presence, verse.iq, verse.stanza, verse.reply, verse.error_reply = st.message, st.presence, st.iq, st.stanza, st.reply, st.error_reply; local new_xmpp_stream = require "util.xmppstream".new; local xmlns_stream = "http://etherx.jabber.org/streams"; local function compare_srv_priorities(a,b) return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight); end local stream_callbacks = { stream_ns = xmlns_stream, stream_tag = "stream", default_ns = "jabber:client" }; function stream_callbacks.streamopened(stream, attr) stream.stream_id = attr.id; if not stream:event("opened", attr) then stream.notopen = nil; end return true; end function stream_callbacks.streamclosed(stream) stream.notopen = true; if not stream.closed then stream:send("</stream:stream>"); stream.closed = true; end stream:event("closed"); return stream:close("stream closed") end function stream_callbacks.handlestanza(stream, stanza) if stanza.attr.xmlns == xmlns_stream then return stream:event("stream-"..stanza.name, stanza); elseif stanza.attr.xmlns then return stream:event("stream/"..stanza.attr.xmlns, stanza); end return stream:event("stanza", stanza); end function stream_callbacks.error(stream, e, stanza) if stream:event(e, stanza) == nil then if stanza then local err = stanza:get_child(nil, "urn:ietf:params:xml:ns:xmpp-streams"); local text = stanza:get_child_text("text", "urn:ietf:params:xml:ns:xmpp-streams"); error(err.name..(text and ": "..text or "")); else error(stanza and stanza.name or e or "unknown-error"); end end end function stream:reset() if self.stream then self.stream:reset(); else self.stream = new_xmpp_stream(self, stream_callbacks); end self.notopen = true; return true; end function stream:connect_client(jid, pass) self.jid, self.password = jid, pass; self.username, self.host, self.resource = jid_split(jid); -- Required XMPP features self:add_plugin("tls"); self:add_plugin("sasl"); self:add_plugin("bind"); self:add_plugin("session"); function self.data(conn, data) local ok, err = self.stream:feed(data); if ok then return; end self:debug("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " ")); self:close("xml-not-well-formed"); end self:hook("connected", function () self:reopen(); end); self:hook("incoming-raw", function (data) return self.data(self.conn, data); end); self.curr_id = 0; self.tracked_iqs = {}; self:hook("stanza", function (stanza) local id, type = stanza.attr.id, stanza.attr.type; if id and stanza.name == "iq" and (type == "result" or type == "error") and self.tracked_iqs[id] then self.tracked_iqs[id](stanza); self.tracked_iqs[id] = nil; return true; end end); self:hook("stanza", function (stanza) local ret; if stanza.attr.xmlns == nil or stanza.attr.xmlns == "jabber:client" then if stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns; if xmlns then ret = self:event("iq/"..xmlns, stanza); if not ret then ret = self:event("iq", stanza); end end if ret == nil then self:send(verse.error_reply(stanza, "cancel", "service-unavailable")); return true; end else ret = self:event(stanza.name, stanza); end end return ret; end, -1); self:hook("outgoing", function (data) if data.name then self:event("stanza-out", data); end end); self:hook("stanza-out", function (stanza) if not stanza.attr.xmlns then self:event(stanza.name.."-out", stanza); end end); local function stream_ready() self:event("ready"); end self:hook("session-success", stream_ready, -1) self:hook("bind-success", stream_ready, -1); local _base_close = self.close; function self:close(reason) self.close = _base_close; if not self.closed then self:send("</stream:stream>"); self.closed = true; else return self:close(reason); end end local function start_connect() -- Initialise connection self:connect(self.connect_host or self.host, self.connect_port or 5222); end if not (self.connect_host or self.connect_port) then -- Look up SRV records adns.lookup(function (answer) if answer then local srv_hosts = {}; self.srv_hosts = srv_hosts; for _, record in ipairs(answer) do table.insert(srv_hosts, record.srv); end table.sort(srv_hosts, compare_srv_priorities); local srv_choice = srv_hosts[1]; self.srv_choice = 1; if srv_choice then self.connect_host, self.connect_port = srv_choice.target, srv_choice.port; self:debug("Best record found, will connect to %s:%d", self.connect_host or self.host, self.connect_port or 5222); end self:hook("disconnected", function () if self.srv_hosts and self.srv_choice < #self.srv_hosts then self.srv_choice = self.srv_choice + 1; local srv_choice = srv_hosts[self.srv_choice]; self.connect_host, self.connect_port = srv_choice.target, srv_choice.port; start_connect(); return true; end end, 1000); self:hook("connected", function () self.srv_hosts = nil; end, 1000); end start_connect(); end, "_xmpp-client._tcp."..(self.host)..".", "SRV"); else start_connect(); end end function stream:reopen() self:reset(); self:send(st.stanza("stream:stream", { to = self.host, ["xmlns:stream"]='http://etherx.jabber.org/streams', xmlns = "jabber:client", version = "1.0" }):top_tag()); end function stream:send_iq(iq, callback) local id = self:new_id(); self.tracked_iqs[id] = callback; iq.attr.id = id; self:send(iq); end function stream:new_id() self.curr_id = self.curr_id + 1; return tostring(self.curr_id); end
gpl-3.0
Schwertspize/speedfng
configure.lua
2
12103
--[[@GROUP Configuration@END]]-- --[[@FUNCTION TODO @END]]-- function NewConfig(on_configured_callback) local config = {} config.OnConfigured = function(self) return true end if on_configured_callback then config.OnConfigured = on_configured_callback end config.options = {} config.settings = NewSettings() config.NewSettings = function(self) local s = NewSettings() for _,v in pairs(self.options) do v:Apply(s) end return s end config.Add = function(self, o) table.insert(self.options, o) self[o.name] = o end config.Print = function(self) for k,v in pairs(self.options) do print(v:FormatDisplay()) end end config.Save = function(self, filename) print("saved configuration to '"..filename.."'") local file = io.open(filename, "w") -- Define a little helper function to save options local saver = {} saver.file = file saver.line = function(self, str) self.file:write(str .. "\n") end saver.option = function(self, option, name) local valuestr = "no" if type(option[name]) == type(0) then valuestr = option[name] elseif type(option[name]) == type(true) then valuestr = "false" if option[name] then valuestr = "true" end elseif type(option[name]) == type("") then valuestr = "'"..option[name].."'" else error("option "..name.." have a value of type ".. type(option[name]).." that can't be saved") end self.file:write(option.name.."."..name.." = ".. valuestr.."\n") end -- Save all the options for k,v in pairs(self.options) do v:Save(saver) end file:close() end config.Load = function(self, filename) local options_func = loadfile(filename) local options_table = {} if not options_func then print("auto configuration") self:Config(filename) options_func = loadfile(filename) end if options_func then -- Setup the options tables for k,v in pairs(self.options) do options_table[v.name] = {} end setfenv(options_func, options_table) -- this is to make sure that we get nice error messages when -- someone sets an option that isn't valid. local mt = {} mt.__index = function(t, key) local v = rawget(t, key) if v ~= nil then return v end error("there is no configuration option named '" .. key .. "'") end setmetatable(options_table, mt) -- Process the options options_func() -- Copy the options for k,v in pairs(self.options) do if options_table[v.name] then for k2,v2 in pairs(options_table[v.name]) do v[k2] = v2 end v.auto_detected = false end end else print("error: no '"..filename.."' found") print("") print("run 'bam config' to generate") print("run 'bam config help' for configuration options") print("") os.exit(1) end end config.Config = function(self, filename) print("") print("configuration:") if _bam_targets[1] == "print" then self:Load(filename) self:Print() print("") print("notes:") self:OnConfigured() print("") else self:Autodetect() print("") print("notes:") if self:OnConfigured() then self:Save(filename) end print("") end end config.Autodetect = function(self) for k,v in pairs(self.options) do v:Check(self.settings) print(v:FormatDisplay()) self[v.name] = v end end config.PrintHelp = function(self) print("options:") for k,v in pairs(self.options) do if v.PrintHelp then v:PrintHelp() end end end config.Finalize = function(self, filename) if _bam_targets[0] == "config" then if _bam_targets[1] == "help" then self:PrintHelp() os.exit(0) end self:Config(filename) os.exit(0) end self:Load(filename) bam_update_globalstamp(filename) end return config end -- Helper functions -------------------------------------- function DefaultOptionDisplay(option) if not option.value then return "no" end if option.value == 1 or option.value == true then return "yes" end return option.value end function IsNegativeTerm(s) if s == "no" then return true end if s == "false" then return true end if s == "off" then return true end if s == "disable" then return true end if s == "0" then return true end return false end function IsPositiveTerm(s) if s == "yes" then return true end if s == "true" then return true end if s == "on" then return true end if s == "enable" then return true end if s == "1" then return true end return false end function MakeOption(name, value, check, save, display, printhelp) local o = {} o.name = name o.value = value o.Check = check o.Save = save o.auto_detected = true o.FormatDisplay = function(self) local a = "SET" if self.auto_detected then a = "AUTO" end return string.format("%-5s %-20s %s", a, self.name, self:Display()) end o.Display = display o.PrintHelp = printhelp if o.Display == nil then o.Display = DefaultOptionDisplay end return o end -- Test Compile C -------------------------------------- function OptTestCompileC(name, source, compileoptions, desc) local check = function(option, settings) option.value = false if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif IsPositiveTerm(ScriptArgs[option.name]) then option.value = true else error(ScriptArgs[option.name].." is not a valid value for option "..option.name) end option.auto_detected = false else if CTestCompile(settings, option.source, option.compileoptions) then option.value = true end end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, false, check, save, nil, printhelp) o.desc = desc o.source = source o.compileoptions = compileoptions return o end -- OptToggle -------------------------------------- function OptToggle(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif IsPositiveTerm(ScriptArgs[option.name]) then option.value = true else error(ScriptArgs[option.name].." is not a valid value for option "..option.name) end end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- OptInteger -------------------------------------- function OptInteger(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then option.value = tonumber(ScriptArgs[option.name]) end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=N") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- OptString -------------------------------------- function OptString(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then option.value = ScriptArgs[option.name] end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=STRING") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- Find Compiler -------------------------------------- --[[@FUNCTION TODO @END]]-- function OptCCompiler(name, default_driver, default_c, default_cxx, desc) local check = function(option, settings) if ScriptArgs[option.name] then -- set compile driver option.driver = ScriptArgs[option.name] -- set c compiler if ScriptArgs[option.name..".c"] then option.c_compiler = ScriptArgs[option.name..".c"] end -- set c+= compiler if ScriptArgs[option.name..".cxx"] then option.cxx_compiler = ScriptArgs[option.name..".cxx"] end option.auto_detected = false elseif option.driver then -- no need todo anything if we have a driver -- TODO: test if we can find the compiler else if ExecuteSilent("cl") == 0 then option.driver = "cl" elseif ExecuteSilent("g++ -v") == 0 then option.driver = "gcc" else error("no c/c++ compiler found") end end --setup_compiler(option.value) end local apply = function(option, settings) if option.driver == "cl" then SetDriversCL(settings) elseif option.driver == "gcc" then SetDriversGCC(settings) elseif option.driver == "clang" then SetDriversClang(settings) else error(option.driver.." is not a known c/c++ compile driver") end if option.c_compiler then settings.cc.c_compiler = option.c_compiler end if option.cxx_compiler then settings.cc.cxx_compiler = option.cxx_compiler end end local save = function(option, output) output:option(option, "driver") output:option(option, "c_compiler") output:option(option, "cxx_compiler") end local printhelp = function(option) local a = "" if option.desc then a = "for "..option.desc end print("\t"..option.name.."=gcc|cl|clang") print("\t\twhat c/c++ compile driver to use"..a) print("\t"..option.name..".c=FILENAME") print("\t\twhat c compiler executable to use"..a) print("\t"..option.name..".cxx=FILENAME") print("\t\twhat c++ compiler executable to use"..a) end local display = function(option) local s = option.driver if option.c_compiler then s = s .. " c="..option.c_compiler end if option.cxx_compiler then s = s .. " cxx="..option.cxx_compiler end return s end local o = MakeOption(name, nil, check, save, display, printhelp) o.desc = desc o.driver = false o.c_compiler = false o.cxx_compiler = false if default_driver then o.driver = default_driver end if default_c then o.c_compiler = default_c end if default_cxx then o.cxx_compiler = default_cxx end o.Apply = apply return o end -- Option Library -------------------------------------- --[[@FUNCTION TODO @END]]-- function OptLibrary(name, header, desc) local check = function(option, settings) option.value = false option.include_path = false local function check_compile_include(filename, paths) if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "") then return "" end for k,v in pairs(paths) do if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "-I"..v) then return v end end return false end if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif ScriptArgs[option.name] == "system" then option.value = true else option.value = true option.include_path = ScriptArgs[option.name] end option.auto_detected = false else option.include_path = check_compile_include(option.header, {}) if option.include_path == false then if option.required then print(name.." library not found and is required") error("required library not found") end else option.value = true option.include_path = false end end end local save = function(option, output) output:option(option, "value") output:option(option, "include_path") end local display = function(option) if option.value then if option.include_path then return option.include_path else return "(in system path)" end else return "not found" end end local printhelp = function(option) print("\t"..option.name.."=disable|system|PATH") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, false, check, save, display, printhelp) o.include_path = false o.header = header o.desc = desc return o end
gpl-2.0
gpedro/forgottenserver
data/spells/scripts/attack/curse.lua
27
1206
local combat = createCombatObject() setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_DEATHDAMAGE) setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_SMALLCLOUDS) setCombatParam(combat, COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_DEATH) local condition = createConditionObject(CONDITION_CURSED) setConditionParam(condition, CONDITION_PARAM_DELAYED, 1) addDamageCondition(condition, 1, 3000, -45) addDamageCondition(condition, 1, 3000, -40) addDamageCondition(condition, 1, 3000, -35) addDamageCondition(condition, 1, 3000, -34) addDamageCondition(condition, 2, 3000, -33) addDamageCondition(condition, 2, 3000, -32) addDamageCondition(condition, 2, 3000, -31) addDamageCondition(condition, 2, 3000, -30) addDamageCondition(condition, 3, 3000, -29) addDamageCondition(condition, 3, 3000, -25) addDamageCondition(condition, 3, 3000, -24) addDamageCondition(condition, 4, 3000, -23) addDamageCondition(condition, 4, 3000, -20) addDamageCondition(condition, 5, 3000, -19) addDamageCondition(condition, 5, 3000, -15) addDamageCondition(condition, 6, 3000, -10) addDamageCondition(condition, 10, 3000, -5) setCombatCondition(combat, condition) function onCastSpell(cid, var) return doCombat(cid, combat, var) end
gpl-2.0
xponen/Zero-K
LuaUI/Widgets/unit_jumper_jumpOverObstacle.lua
1
20670
local version = "v0.506" function widget:GetInfo() return { name = "Auto Jump Over Terrain", desc = version .. " Jumper automatically jump over terrain or buildings if it shorten walk time.", author = "Msafwan", date = "4 February 2014", license = "GNU GPL, v2 or later", layer = 21, enabled = false } end VFS.Include("LuaRules/Configs/customcmds.h.lua") VFS.Include("LuaRules/Utilities/isTargetReachable.lua") local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitRulesParam = Spring.GetUnitRulesParam local spValidUnitID = Spring.ValidUnitID local spValidFeatureID = Spring.ValidFeatureID local spGetCommandQueue = Spring.GetCommandQueue local spGiveOrderArrayToUnitArray = Spring.GiveOrderArrayToUnitArray local spGetFeaturePosition = Spring.GetFeaturePosition local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetGameSeconds = Spring.GetGameSeconds ------------------------------------------------------------ ------------------------------------------------------------ local gaussUnitDefID = UnitDefNames["armpb"].id local myTeamID local jumperAddInfo={} --Spread job stuff: (spread looping across 1 second) local spreadJobs=nil; local effectedUnit={}; local spreadPreviousIndex = nil; --end spread job stuff --Network lag hax stuff: (wait until unit receive command before processing 2nd time) local waitForNetworkDelay = nil; local issuedOrderTo = {} --end network lag stuff local jumpersToJump = {} local jumpersToWatch = {} local jumpersToJump_Count = 0 local jumpersUnitID = {} local jumperDefs = {} local excludedJumper = { corsumo = true,} --because unit like sumo can jump into ally blob and kill them all local jumpNames = VFS.Include("LuaRules/Configs/jump_defs.lua") --list of unit able to jump for name, data in pairs(jumpNames) do --convert UnitName list into unitDefID list (copied from unit_bomber_command.lua by KingRaptor) if not excludedJumper[name] then local unitDef = UnitDefNames[name] if unitDef then jumperDefs[unitDef.id] = data end end end function widget:Initialize() local _, _, spec, teamID = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeamID = teamID end function widget:GameFrame(n) if n%30==14 then --every 30 frame period (1 second) at the 14th frame: --check if we were waiting for lag for too long local currentSecond = spGetGameSeconds() if waitForNetworkDelay then if currentSecond - waitForNetworkDelay[1] > 4 then waitForNetworkDelay = nil end end end if ( n%15==0 and not waitForNetworkDelay) or spreadJobs then local numberOfUnitToProcess = 29 --NUMBER OF UNIT PER SECOND. minimum: 29 unit per second local numberOfUnitToProcessPerFrame = math.ceil(numberOfUnitToProcess/29) --spread looping to entire 1 second spreadJobs = false local numberOfLoopToProcessPerFrame = math.ceil(jumpersToJump_Count/29) local currentLoopIndex = spreadPreviousIndex or 1 local currentLoopCount = 0 local currentUnitProcessed = 0 local finishLoop = false if currentLoopIndex >= jumpersToJump_Count then finishLoop =true end local k = currentLoopIndex while (k<=jumpersToJump_Count) do local unitID = jumpersToJump[k][2] local validUnitID = spValidUnitID(unitID) if not validUnitID then MoveLastPositionToCurrentPosition(k,unitID) k = k -1 end if validUnitID then local unitDefID = jumpersToJump[k][1] if not jumperAddInfo[unitDefID] then local moveID = UnitDefs[unitDefID].moveDef.id local ud = UnitDefs[unitDefID] local halfJumprangeSq = (jumperDefs[unitDefID].range/2)^2 local heightSq = jumperDefs[unitDefID].height^2 local totalFlightDist = math.sqrt(halfJumprangeSq+heightSq)*2 local jumpTime = (totalFlightDist/jumperDefs[unitDefID].speed + jumperDefs[unitDefID].delay)/30 -- is in second local unitSpeed = ud.speed --speed is in elmo-per-second local weaponRange = GetUnitFastestWeaponRange(ud) local unitSize = math.max(ud.xsize*4, ud.zsize*4) jumperAddInfo[unitDefID] = {moveID,jumpTime,unitSpeed,weaponRange, unitSize} end repeat --note: not looping, only for using "break" as method of escaping code local _,_,inBuild = spGetUnitIsStunned(unitID) if inBuild then break; --a.k.a: Continue end --IS NEW UNIT? initialize them-- effectedUnit[unitID] = effectedUnit[unitID] or {cmdCount=0,cmdOne={id=nil,x=nil,y=nil,z=nil},cmdTwo={id=nil,x=nil,y=nil,z=nil}} --IS UNIT IDLE? skip-- local cmd_queue = spGetCommandQueue(unitID, -1); if not (cmd_queue and cmd_queue[1]) then MoveLastPositionToCurrentPosition(k,unitID) k = k -1 break; --a.k.a: Continue end -- IS UNIT WAITING? skip-- if (cmd_queue[1].id== CMD.WAIT) then break; end --IS UNIT CHARGING JUMP? skip-- local jumpReload = spGetUnitRulesParam(unitID,"jumpReload") if jumpReload then if jumpReload < 0.95 then break; --a.k.a: Continue end end --EXTRACT RELEVANT FIRST COMMAND -- local cmd_queue2 local unitIsAttacking for i=1, #cmd_queue do local cmd = cmd_queue[i] local equivalentMoveCMD = ConvertCMDToMOVE({cmd}) if equivalentMoveCMD then unitIsAttacking = cmd.id == CMD.ATTACK cmd_queue2 = equivalentMoveCMD break end end if not cmd_queue2 then break end currentUnitProcessed = currentUnitProcessed + 1 --CHECK POSITION OF PREVIOUS JUMP-- local extraCmd1 = nil local extraCmd2 = nil local jumpCmdPos = 0 if effectedUnit[unitID].cmdCount >0 then for i=1, #cmd_queue do local cmd = cmd_queue[i] if cmd.id == effectedUnit[unitID].cmdOne.id and cmd.params[1] == effectedUnit[unitID].cmdOne.x and cmd.params[2] == effectedUnit[unitID].cmdOne.y and cmd.params[3] == effectedUnit[unitID].cmdOne.z then extraCmd1 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = i end if cmd.id == effectedUnit[unitID].cmdTwo.id and cmd.params[1] == effectedUnit[unitID].cmdTwo.x and cmd.params[2] == effectedUnit[unitID].cmdTwo.y and cmd.params[3] == effectedUnit[unitID].cmdTwo.z then extraCmd2 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = jumpCmdPos or i break end end end --CHECK FOR OBSTACLE IN LINE-- local tx,ty,tz = cmd_queue2.params[1],cmd_queue2.params[2],cmd_queue2.params[3] local px,py,pz = spGetUnitPosition(unitID) local enterPoint_X,enterPoint_Y,enterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z = GetNearestObstacleEnterAndExitPoint(px,py,pz, tx,tz, unitDefID) if exitPoint_X and exitPoint_Z then local unitSpeed = jumperAddInfo[unitDefID][3] local moveID = jumperAddInfo[unitDefID][1] local weaponRange = jumperAddInfo[unitDefID][4] --MEASURE REGULAR DISTANCE-- local distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,unitIsAttacking,weaponRange) local normalTimeToDest = (distance/unitSpeed) --is in second --MEASURE DISTANCE WITH JUMP-- cmd_queue2.params[1]=enterPoint_X cmd_queue2.params[2]=enterPoint_Y cmd_queue2.params[3]=enterPoint_Z distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,false,0) --distance to jump-start point local timeToJump = (distance/unitSpeed) --is in second cmd_queue2.params[1]=tx --target coordinate cmd_queue2.params[2]=ty cmd_queue2.params[3]=tz local jumpTime = jumperAddInfo[unitDefID][2] distance = GetWaypointDistance(unitID,moveID,cmd_queue2,exitPoint_X,exitPoint_Y,exitPoint_Z,unitIsAttacking,weaponRange) --dist out of jump-landing point local timeFromExitToDestination = (distance/unitSpeed) --in second local totalTimeWithJump = timeToJump + timeFromExitToDestination + jumpTime --NOTE: time to destination is in second. local normalPathTime = normalTimeToDest - 2 --add 2 second benefit to regular walking (make walking more attractive choice unless jump can save more than 1 second travel time) if totalTimeWithJump < normalPathTime then local commandArray = {[1]=nil,[2]=nil,[3]=nil,[4]=nil} if (math.abs(enterPoint_X-px)>50 or math.abs(enterPoint_Z-pz)>50) then commandArray[1]= {CMD.INSERT, {0, CMD.MOVE, CMD.OPT_INTERNAL, enterPoint_X,enterPoint_Y,enterPoint_Z}, {"alt"}} commandArray[2]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[3]= extraCmd2 commandArray[4]= extraCmd1 effectedUnit[unitID].cmdCount = 2 effectedUnit[unitID].cmdOne.id = CMD.MOVE effectedUnit[unitID].cmdOne.x = enterPoint_X effectedUnit[unitID].cmdOne.y = enterPoint_Y effectedUnit[unitID].cmdOne.z = enterPoint_Z effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD.MOVE,enterPoint_X,enterPoint_Y,enterPoint_Z} else commandArray[1]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[2]= extraCmd2 commandArray[3]= extraCmd1 effectedUnit[unitID].cmdCount = 1 effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD_JUMP,exitPoint_X,exitPoint_Y,exitPoint_Z} end spGiveOrderArrayToUnitArray({unitID},commandArray) waitForNetworkDelay = waitForNetworkDelay or {spGetGameSeconds(),0} waitForNetworkDelay[2] = waitForNetworkDelay[2] + 1 end elseif jumpCmdPos >= 2 then spGiveOrderArrayToUnitArray({unitID},{extraCmd2,extraCmd1}) --another command was sandwiched before the Jump command, making Jump possibly outdated/no-longer-optimal. Remove Jump effectedUnit[unitID].cmdCount = 0 end until true currentLoopCount = currentLoopCount + 1 end if k >= jumpersToJump_Count then finishLoop =true break elseif currentUnitProcessed >= numberOfUnitToProcessPerFrame or currentLoopCount>= numberOfLoopToProcessPerFrame then spreadJobs = true spreadPreviousIndex = k+1 --continue at next frame break end k = k + 1 end if finishLoop then spreadPreviousIndex = nil end end end function MoveLastPositionToCurrentPosition(k,unitID) --last position to current position if k ~= jumpersToJump_Count then local lastUnitID = jumpersToJump[jumpersToJump_Count][2] jumpersToJump[k] = jumpersToJump[jumpersToJump_Count] jumpersUnitID[lastUnitID] = k end effectedUnit[unitID] = nil jumpersUnitID[unitID] = nil jumpersToJump[jumpersToJump_Count] = nil jumpersToJump_Count = jumpersToJump_Count - 1 end function GetNearestObstacleEnterAndExitPoint(currPosX,currPosY, currPosZ, targetPosX,targetPosZ, unitDefID) local nearestEnterPoint_X,original_X = currPosX,currPosX local nearestEnterPoint_Z,original_Z = currPosZ,currPosZ local nearestEnterPoint_Y,original_Y = currPosY,currPosY local exitPoint_X, exitPoint_Z,exitPoint_Y local overobstacle = false local distFromObstacle = 0 local distToTarget= 0 local unitBoxDist local defaultJumprange = jumperDefs[unitDefID].range -20 local addingFunction = function() end local check_n_SavePosition = function(x,z,gradient,addValue) local endOfLine = (math.abs(x-targetPosX) < 20) and (math.abs(z-targetPosZ) < 20) if endOfLine then return x,z,true end local y = Spring.GetGroundHeight(x, z) local clear,_ = Spring.TestBuildOrder(gaussUnitDefID or unitDefID, x,y ,z, 1) -- Spring.MarkerAddPoint(x,y ,z, clear) if clear == 0 then overobstacle = true if distToTarget==0 then distToTarget = math.sqrt((targetPosX-x)^2 + (targetPosZ-z)^2) local backX,backZ = addingFunction(x,z,addValue*-5,gradient) local backY = Spring.GetGroundHeight(backX, backZ) distFromObstacle = math.sqrt((x-backX)^2 + (z-backZ)^2) local backDistToTarget = math.sqrt((targetPosX-backX)^2 + (targetPosZ-backZ)^2) local unitDistToTarget = math.sqrt((targetPosX-original_X)^2 + (targetPosZ-original_Z)^2) if unitDistToTarget > backDistToTarget then nearestEnterPoint_X = backX --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = backZ nearestEnterPoint_Y = backY else nearestEnterPoint_X = original_X --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = original_Z nearestEnterPoint_Y = original_Y end -- Spring.MarkerAddPoint(backX,backY,backZ, "enter") else distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist end elseif overobstacle then distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist if distFromObstacle < defaultJumprange and distToTarget>0 then exitPoint_X = x exitPoint_Z = z exitPoint_Y = y -- Spring.MarkerAddPoint(x,y,z, "exit") else return x,z,true end end x,z = addingFunction(x,z,addValue,gradient) return x,z,false end local x, z = currPosX,currPosZ local xDiff = targetPosX -currPosX local zDiff = targetPosZ -currPosZ local unitBoxSize = jumperAddInfo[unitDefID][5] local finish=false if math.abs(xDiff) > math.abs(zDiff) then local xSgn = xDiff/math.abs(xDiff) local gradient = zDiff/xDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local xadd = unitBoxSize*xSgn addingFunction = function(x,z,addValue,gradient) return x+addValue, z+addValue*gradient end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,xadd) if finish then break end end else local zSgn = zDiff/math.abs(zDiff) local gradient = xDiff/zDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local zadd = unitBoxSize*zSgn addingFunction = function(x,z,addValue,gradient) return x+addValue*gradient, z + addValue end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,zadd) if finish then break end end end return nearestEnterPoint_X,nearestEnterPoint_Y,nearestEnterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z end function GetUnitFastestWeaponRange(unitDef) local fastestReloadTime, fastReloadRange = 999,-1 for _, weapons in ipairs(unitDef.weapons) do --reference: gui_contextmenu.lua by CarRepairer local weaponsID = weapons.weaponDef local weaponsDef = WeaponDefs[weaponsID] if weaponsDef.name and not (weaponsDef.name:find('fake') or weaponsDef.name:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer if not weaponsDef.isShield then --if not shield then this is conventional weapon local reloadTime = weaponsDef.reload if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time fastestReloadTime = reloadTime fastReloadRange = weaponsDef.range end end end end return fastReloadRange end function ConvertCMDToMOVE(command) if (command == nil) then return nil end command = command[1] if (command == nil) then return nil end if command.id == CMD.MOVE or command.id == CMD.PATROL or command.id == CMD.FIGHT or command.id == CMD.JUMP or command.id == CMD.ATTACK then if not command.params[2] then local x,y,z = spGetUnitPosition(command.params[1]) if not x then --outside LOS and radar return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end end if command.id == CMD.RECLAIM or command.id == CMD.REPAIR or command.id == CMD.GUARD or command.id == CMD.RESSURECT then local isPossible2PartAreaCmd = command.params[5] if not command.params[4] or isPossible2PartAreaCmd then --if not area-command or the is the 2nd part of area-command (1st part have radius at 4th-param, 2nd part have unitID/featureID at 1st-param and radius at 5th-param) if not command.params[2] or isPossible2PartAreaCmd then local x,y,z if command.id == CMD.REPAIR or command.id == CMD.GUARD then x,y,z = GetUnitOrFeaturePosition(command.params[1]) elseif command.id == CMD.RECLAIM or command.id == CMD.RESSURECT then x,y,z = GetUnitOrFeaturePosition(command.params[1]) end if not x then return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end else return nil --no area command allowed end end if command.id < 0 then if command.params[3]==nil then --is building unit in factory return nil end command.id = CMD.MOVE return command end if command.id == CMD_WAIT_AT_BEACON then return command end return nil end function GetWaypointDistance(unitID,moveID,queue,px,py,pz,isAttackCmd,weaponRange) --Note: source is from unit_transport_ai.lua (by Licho) local d = 0 if (queue == nil) then return 99999 end local v = queue if (v.id == CMD.MOVE) then local reachable = true --always assume target reachable local waypoints if moveID then --unit has compatible moveID? local minimumGoalDist = (isAttackCmd and weaponRange-20) or 128 local result, lastwaypoint result, lastwaypoint, waypoints = Spring.Utilities.IsTargetReachable(moveID,px,py,pz,v.params[1],v.params[2],v.params[3],minimumGoalDist) if result == "outofreach" then --abit out of reach? reachable=false --target is unreachable! end end if reachable then local distOffset = (isAttackCmd and weaponRange-20) or 0 if waypoints then --we have waypoint to destination? local way1,way2,way3 = px,py,pz for i=1, #waypoints do --sum all distance in waypoints d = d + Dist(way1,way2,way3, waypoints[i][1],waypoints[i][2],waypoints[i][3]) way1,way2,way3 = waypoints[i][1],waypoints[i][2],waypoints[i][3] end d = d + math.max(0,Dist(way1,way2,way3, v.params[1], v.params[2], v.params[3])-distOffset) --connect endpoint of waypoint to destination else --so we don't have waypoint? d = d + math.max(0,Dist(px,py, pz, v.params[1], v.params[2], v.params[3])-distOffset) --we don't have waypoint then measure straight line end else --pathing says target unreachable?! d = d + Dist(px,py, pz, v.params[1], v.params[2], v.params[3])*10 +9999 --target unreachable! end end return d end function Dist(x,y,z, x2, y2, z2) local xd = x2-x local yd = y2-y local zd = z2-z return math.sqrt(xd*xd + yd*yd + zd*zd) end function GetUnitOrFeaturePosition(id) --copied from cmd_commandinsert.lua widget (by dizekat) if id<=Game.maxUnits and spValidUnitID(id) then return spGetUnitPosition(id) elseif spValidFeatureID(id-Game.maxUnits) then return spGetFeaturePosition(id-Game.maxUnits) --featureID is always offset by maxunit count end return nil end ------------------------------------------------------------ ------------------------------------------------------------ function widget:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders) if myTeamID==unitTeam and jumperDefs[unitDefID] and not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdOpts, cmdParams) if myTeamID==unitTeam and jumperDefs[unitDefID] then if (cmdID ~= CMD.INSERT) then if not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end if (cmdID == CMD.INSERT) then local issuedOrderContent = issuedOrderTo[unitID] if issuedOrderContent and (cmdParams[4] == issuedOrderContent[2] and cmdParams[5] == issuedOrderContent[3] and cmdParams[6] == issuedOrderContent[4]) then issuedOrderTo[unitID] = nil if waitForNetworkDelay then waitForNetworkDelay[2] = waitForNetworkDelay[2] - 1 if waitForNetworkDelay[2]==0 then waitForNetworkDelay = nil end end end end end end
gpl-2.0
xponen/Zero-K
LuaUI/Widgets/game_resource_stats_writer.lua
17
1718
function widget:GetInfo() return { name = "Resource Stat Writer", desc = "Writes resource statistics to a file at game end.", author = "Google Frog", date = "July 11, 2012", license = "GNU GPL, v2 or later", layer = 0, enabled = false -- loaded by default? } end function WriteResourceStatsToFile(reallyBigString, teamNames) Spring.Echo("Recieved data") local filename local dateTable = os.date("*t") if dateTable then if dateTable.month < 10 then dateTable.month = "0" .. dateTable.month end if dateTable.day < 10 then dateTable.day = "0" .. dateTable.day end if dateTable.hour < 10 then dateTable.hour = "0" .. dateTable.hour end if dateTable.min < 10 then dateTable.min = "0" .. dateTable.min end filename = "ResourceStats/" .. dateTable.year .. " " .. dateTable.month .. " " .. dateTable.day .. " " .. dateTable.hour .. " " .. dateTable.min .. ".txt" else filename = "ResourceStats/recent.txt" end local file = assert(io.open(filename,'w'), "Error saving team economy data to " .. filename) local allyTeamList = Spring.GetAllyTeamList() for i=1,#allyTeamList do local allyTeamID = allyTeamList[i] local teamList = Spring.GetTeamList(allyTeamID) local toSend = allyTeamID for j=1,#teamList do local teamID = teamList[j] toSend = toSend .. " " .. teamID .. " " .. (teamNames[teamID] or "no_name") end --Spring.SendCommands("wbynum 255 SPRINGIE: allyTeamPlayerMap " .. toSend) file:write(toSend) file:write("\n") end file:write(reallyBigString) file:close() end function widget:Initialize() widgetHandler:RegisterGlobal("WriteResourceStatsToFile", WriteResourceStatsToFile) end
gpl-2.0
Elanis/SciFi-Pack-Addon-Gamemode
gamemodes/scifipack/gamemode/spawnmenu/creationmenu/content/contentsidebar.lua
1
1259
local PANEL = {} function PANEL:Init() self.Tree = vgui.Create( "DTree", self ); self.Tree:SetClickOnDragHover( true ); self.Tree.OnNodeSelected = function( Tree, Node ) hook.Call( "ContentSidebarSelection", GAMEMODE, self:GetParent(), Node ) end self.Tree:Dock( FILL ) self.Tree:SetBackgroundColor( Color( 240, 240, 240, 255 ) ) self:SetPaintBackground( false ) end function PANEL:EnableModify() self:CreateSaveNotification() self.Toolbox = vgui.Create( "ContentSidebarToolbox", self ) hook.Add( "OpenToolbox", "OpenToolbox", function() if ( !IsValid( self.Toolbox ) ) then return end self.Toolbox:Open() end ) end function PANEL:CreateSaveNotification() local SavePanel = vgui.Create( "DButton", self ) SavePanel:Dock( TOP ) SavePanel:DockMargin( 16, 1, 16, 4 ) SavePanel:SetIcon( "icon16/disk.png" ) SavePanel:SetText( "#spawnmenu.savechanges" ) SavePanel:SetVisible( false ) SavePanel.DoClick = function() SavePanel:SlideUp( 0.2 ) hook.Run( "OnSaveSpawnlist" ); end hook.Add( "SpawnlistContentChanged", "ShowSaveButton", function() if ( SavePanel:IsVisible() ) then return end SavePanel:SlideDown( 0.2 ) end ) end vgui.Register( "ContentSidebar", PANEL, "DPanel" )
gpl-2.0
Samnsparky/ljswitchboard
switchboard_modules/lua_script_debugger/premade_scripts/oldScripts/1-Wire De-Steeg(fast).lua
1
2894
--Requires Firmware 1.0161 or newer function round(num, idp) local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end function DS18xx_Start(target_rom) if target_rom[3] == 0 then MB.W(5307,0, 0xCC) -- Set to skip ROM print("rom skip") else MB.W(5307,0, 0x55) -- Set to match ROM end MB.W(5320, 0, target_rom[0]) MB.W(5321, 0, target_rom[1]) MB.W(5322, 0, target_rom[2]) MB.W(5323, 0, target_rom[3]) MB.W(5300, 0, SensPinNum) -- Set the DQ pin MB.W(5302, 0, 0) -- Set the options MB.W(5308, 0, 1) -- Write one byte MB.W(5309, 0, 0) -- Read no bytes MB.W(5340, 0, 0x4400) -- Send the start conv command return MB.W(5310, 0, 1) -- GO end function DS18xx_Read(target_rom) if target_rom[3] == 0 then MB.W(5307,0, 0xCC) -- Set to skip ROM else MB.W(5307,0, 0x55) -- Set to match ROM end MB.W(5320, 0, target_rom[0]) MB.W(5321, 0, target_rom[1]) MB.W(5322, 0, target_rom[2]) MB.W(5323, 0, target_rom[3]) MB.W(5300, 0, SensPinNum) -- Set the DQ pin MB.W(5302, 0, 0) -- Set the options MB.W(5308, 0, 1) -- Write one byte MB.W(5309, 0, 9) -- Read nine bytes MB.W(5340, 0, 0xBE00) -- Send the read command MB.W(5310, 0, 1) -- GO temp, error = MB.R(5370, 0, 1) -- Read two bytes lsb = temp / 256 round(lsb, 0) msb = temp % 256 msb = round(msb * 256, 0) temp = msb + lsb -- temp = temp * 0.0625 + 273.15 if(msb == 65280) then temp = sensorNotFound end -- print("msb",msb,"lsb",lsb) return temp, error end print("Read and display the device temperature 10 times at 0.5 Hz.") sensorNotFound = 0 MB.W(48005, 0, 1) --Ensure analog is on LJ.IntervalConfig(0, 3000) eioNum = 0 FV0 = {[0] = 0xF100, [1] = 0x0802, [2] = 0xB082, [3] = 0x8010} FV1 = {[0] = 0x2200, [1] = 0x0802, [2] = 0xB009, [3] = 0xB710} FV2 = {[0] = 0x7400, [1] = 0x0802, [2] = 0xB012, [3] = 0x2210} FV3 = {[0] = 0x3200, [1] = 0x0802, [2] = 0xAFA7, [3] = 0x0810} FV4 = {[0] = 0xCB00, [1] = 0x0802, [2] = 0xB013, [3] = 0xD210} FV5 = {[0] = 0x8C00, [1] = 0x0802, [2] = 0xB07A, [3] = 0xFC10} FV6 = {[0] = 0x5A00, [1] = 0x0802, [2] = 0xB005, [3] = 0xB410} FV7 = {[0] = 0xAE00, [1] = 0x0802, [2] = 0xAFB6, [3] = 0xCE10} ROMs = {[0] = FV0, [1] = FV1, [2] = FV2, [3] = FV3, [4] = FV4, [5] = FV5, [6] = FV6, [7] = FV7} NumSensors = 8 SensPinNum = eioNum + 8 temps = {} while true do if LJ.CheckInterval(0) then print("Reading sensors:") for i=0, NumSensors - 1, 1 do temp = DS18xx_Read(ROMs[i]) DS18xx_Start(ROMs[i]) if(temp == sensorNotFound) then print(i,"N/A") else print(i, temp, "K") end -- temps[i] = temp -- IOMEM.W(46000+i*2, temps[i]) MB.W(46000+i*2, temp) end end end
mit
Paradokz/BadRotations
System/engines/HealingEngineCollections.lua
2
7427
novaEngineTables = { } -- This is for the Dispel Check, all Debuffs we want dispelled go here -- valid arguments: stacks = num range = num novaEngineTables.DispelID = { { id = 143579, stacks = 3 }, -- Immersius { id = 143434, stacks = 3 }, -- Fallen Protectors { id = 144514, stacks = 0 }, -- Norushen { id = 144351, stacks = 0 }, -- Sha of Pride { id = 146902, stacks = 0 }, -- Galakras(Korga Poisons) { id = 143432, stacks = 0 }, -- General Nazgrim { id = 142913, stacks = 0, range = 10}, -- Malkorok(Displaced Energy) { id = 115181, stacks = 0 }, -- Spoils of Pandaria(Breath of Fire) { id = 143791, stacks = 0 }, -- Thok(Corrosive Blood) { id = 145206, stacks = 0 }, -- Aqua Bomb(Proving Grounds) -- Ko'ragh { id = 142913, stacks = 0, range = 5}, -- http://www.wowhead.com/spell=162185/expel-magic-fire { id = 185066, stacks = 0}, -- Mark of Necromancer red level -- Xavius { id = 206651, stacks = 3}, -- Xavius Darkening Soul { id = 209158, stacks = 3}, -- Xavius Blackening Soul } -- This is where we house the Debuffs that are bad for our users, and should not be healed when they have it novaEngineTables.BadDebuffList= { 104451, -- Ice Tomb 76577,-- Smoke Bomb 121949, -- Parasistic Growth 122784, -- Reshape Life 122370, -- Reshape Life 2 123184, -- Dissonance Field 123255, -- Dissonance Field 2 123596, -- Dissonance Field 3 128353, -- Dissonance Field 4 145832, -- Empowered Touch of Y'Shaarj (mind control garrosh) 145171, -- Empowered Touch of Y'Shaarj (mind control garrosh) 145065, -- Empowered Touch of Y'Shaarj (mind control garrosh) 145071, -- Empowered Touch of Y'Shaarj (mind control garrosh) --Brackenspore 159220, -- http://www.wowhead.com/spell=159220 A debuff that removes 99% of healing so no point healing them 184587, -- Touch of Mortality Prevents all healing for 9 seconds } -- list of special units we want to heal, these npc will go directly into healing engine(Special Heal must be checked) novaEngineTables.SpecialHealUnitList = { [71604] = "Immersus Oozes" , [6459] = "Boss#3 SoO", [6460] = "Boss#3 SoO", [6464] = "Boss#3 SoO", [90388] = "Tortured Essence", }; -- set dot that need to be healed to max(needs to be topped) to very low values so that engine will prioritize them -- the value used here will be substract from current health, we could use negative values to add back health instead -- these are checked debuff on allies ie br.friend[i].unit wear 145263 and its hp is 70, engine will use 50 instead novaEngineTables.SpecificHPDebuffs = { --{ debuff = 123456, value = 20, stacks = 1 }, -- Exemple. --{ debuff = 123456, value = -100, stacks = 3 }, -- Exemple -- Twin Ogrons { debuff = 158241 , value = 20 }, -- http://www.wowhead.com/spell=158241/blaze { debuff = 155569 , value = 20 }, -- http://www.wowhead.com/spell=155569/injured { debuff = 163374 , value = 20 }, -- http://www.wowhead.com/spell=163374/arcane-volatility -- Imperator { debuff = 157763 , value = 20 }, -- http://www.wowhead.com/spell=157763/fixate { debuff = 156225 , value = 40 , stacks = 8 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 35 , stacks = 7 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 30 , stacks = 6 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 25 , stacks = 5 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 20 , stacks = 4 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 15 , stacks = 3 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 10 , stacks = 2 }, --http://www.wowhead.com/spell=156225/branded { debuff = 156225 , value = 5 , stacks = 1 }, --http://www.wowhead.com/spell=156225/branded --Kargath { debuff = 159113 , value = 20 }, --http://www.wowhead.com/spell=159113/impale { debuff = 159386 , value = 20 }, --http://www.wowhead.com/spell=159386/iron-bomb { debuff = 159413 , value = 30 }, --http://www.wowhead.com/spell=159413/mauling-brew --Brackenspore { debuff = 163241 , value = 40 , stacks = 4 }, --http://www.wowhead.com/spell=163241/rot { debuff = 163241 , value = 30 , stacks = 3 }, --http://www.wowhead.com/spell=163241/rot { debuff = 163241 , value = 20 , stacks = 2 }, --http://www.wowhead.com/spell=163241/rot { debuff = 163241 , value = 20 , stacks = 1 }, --http://www.wowhead.com/spell=163241/rot -- Gruul { debuff = 155506 , value = 30 }, --http://www.wowhead.com/spell=155506/petrified { debuff = 173192 , value = 30 }, --http://www.wowhead.com/spell=173192/cave-in { debuff = 145263 , value = 20 }, -- Proving Grounds Healer Debuff. -- Blast Furnace { debuff = 155196 , value = 30 }, --http://www.wowhead.com/spell=155196/fixate { debuff = 155242 , value = 30 }, --http://www.wowhead.com/spell=155242/heat { debuff = 156934 , value = 15 }, --http://www.wowhead.com/spell=156934/rupture { debuff = 176121 , value = 15 }, --http://www.wowhead.com/spell=176121/volatile-fire --Flame Bender { debuff = 155277 , value = 30 }, --http://www.wowhead.com/spell=155277/blazing-radiance --BeastMaster { debuff = 162283 , value = 30 }, --http://www.wowhead.com/spell=162283/rend-and-tear -- Iron Maidens { debuff = 158078 , value = 30 }, --http://www.wowhead.com/spell=158078/blood-ritual { debuff = 156112 , value = 30 }, --http://www.wowhead.com/spell=156112/convulsive-shadows { debuff = 158315 , value = 15 }, --http://www.wowhead.com/spell=158315/dark-hunt --Trains { debuff = 165195 , value = 30 }, --http://www.wowhead.com/spell=165195/prototype-pulse-grenade -- Tyrant Velhari { debuff = 180116 , value = 30}, --http://www.wowhead.com/spell=180166/touch-of-harm -- Chronomatic Anomaly (M) { debuff = 206609 , value = 30}, --http://www.wowhead.com/spell=206609/time-release } -- this table will assign role to any unit wearing the unit name novaEngineTables.roleTable = { ["Oto the Protector"] = { role = "TANK", class = "Warrior" }, -- proving grounds tank ["Sooli the Survivalist"] = { role = "DPS", class = "Hunter" }, -- proving grounds dps ["Ki the Assassin"] = { role = "DPS", class = "Rogue" }, -- proving grounds dps ["Kavan the Arcanist"] = { role = "DPS", class = "Mage" }, -- proving grounds dps } -- special targets to include when we want to heal npcs novaEngineTables.SavedSpecialTargets = { ["target"] = nil, ["mouseover"] = nil, ["focus"] = nil, } -- ToDo: we need a powerful DoT handler to handle stuff such as hand of purity/heal over time novaEngineTables.BadlyDeBuffed = { --High Maul --Kargath 159386, --http://www.wowhead.com/spell=159386/iron-bomb --Twin Ogron 158241, --http://www.wowhead.com/spell=158241/blaze 155569, --http://www.wowhead.com/spell=155569/injured 163374, --http://www.wowhead.com/spell=163374/arcane-volatility -- Ko'ragh 161442, --http://www.wowhead.com/spell=161242/caustic-energy --Imperator Margok 157763, --http://www.wowhead.com/spell=157763/fixate --Black Rock Foundry --Iron Maidens 156112, --http://www.wowhead.com/spell=156112/convulsive-shadows 158315, --http://www.wowhead.com/spell=158315/dark-hunt --Trains 165195,--http://www.wowhead.com/spell=165195/prototype-pulse-grenade } -- Table for NPCs we do not want to add to table (eg. Hymdal/Odyn after they become friendly) novaEngineTables.skipNPC = { "95676", -- Odyn "94960", -- Hynmdall "100482", -- Senegos };
gpl-3.0
vpp-dev/vpp-lua-plugin
lapi-test/example-cli.lua
1
1410
--[[ /* * Copyright (c) 2016 Cisco and/or its affiliates. * 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. */ ]] vpp = require "vpp-lapi" root_dir = "/home/ubuntu/vpp" pneum_path = root_dir .. "/build-root/install-vpp_debug-native/vpp-api/lib64/libpneum.so" vpp:init({ pneum_path = pneum_path }) vpp:consume_api(root_dir .. "/build-root/install-vpp_debug-native/vlib-api/vlibmemory/memclnt.api") vpp:consume_api(root_dir .. "/build-root/install-vpp_debug-native/vpp/vpp-api/vpe.api") vpp:connect("aytest") -- api calls reply = vpp:api_call("show_version") print("Version: ", reply[1].version) print(vpp.hex_dump(reply[1].version)) print(vpp.dump(reply)) print("---") -- reply = vpp:api_call("sw_interface_dump", { context = 42, name_filter = "local", name_filter_valid = 1 } ) reply = vpp:api_call("cli_inband", { cmd = "show vers" }) print(vpp.dump(reply)) print("---") vpp:disconnect()
apache-2.0
kiarash14/tg5
plugins/calc.lua
11
2732
-- Function reference: http://mathjs.org/docs/reference/functions/categorical.html local function mathjs(exp) local url = 'http://api.mathjs.org/v1/' url = url..'?expr='..URL.escape(exp) local b,c = http.request(url) local text = nil if c == 200 then text = '= '..b elseif c == 400 then text = b else text = 'Unexpected error\n' ..'Is api.mathjs.org up?' end return text end local function run(msg, matches) return mathjs(matches[1]) end return { description = "Calculate math expressions with mathjs API", usage = "!calc [expression]: evaluates the expression and sends the result.", patterns = { "^!calc (.*)$", "^[Cc]alc (.*)$" }, run = run } -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
persiaAziz/trafficserver
lib/luajit/src/jit/dis_ppc.lua
88
20319
---------------------------------------------------------------------------- -- LuaJIT PPC disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all common, non-privileged 32/64 bit PowerPC instructions -- plus the e500 SPE instructions and some Cell/Xenon extensions. -- -- NYI: VMX, VMX128 ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_crops = { shift = 1, mask = 1023, [0] = "mcrfXX", [33] = "crnor|crnotCCC=", [129] = "crandcCCC", [193] = "crxor|crclrCCC%", [225] = "crnandCCC", [257] = "crandCCC", [289] = "creqv|crsetCCC%", [417] = "crorcCCC", [449] = "cror|crmoveCCC=", [16] = "b_lrKB", [528] = "b_ctrKB", [150] = "isync", } local map_rlwinm = setmetatable({ shift = 0, mask = -1, }, { __index = function(t, x) local rot = band(rshift(x, 11), 31) local mb = band(rshift(x, 6), 31) local me = band(rshift(x, 1), 31) if mb == 0 and me == 31-rot then return "slwiRR~A." elseif me == 31 and mb == 32-rot then return "srwiRR~-A." else return "rlwinmRR~AAA." end end }) local map_rld = { shift = 2, mask = 7, [0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.", { shift = 1, mask = 1, [0] = "rldclRR~RM.", "rldcrRR~RM.", }, } local map_ext = setmetatable({ shift = 1, mask = 1023, [0] = "cmp_YLRR", [32] = "cmpl_YLRR", [4] = "twARR", [68] = "tdARR", [8] = "subfcRRR.", [40] = "subfRRR.", [104] = "negRR.", [136] = "subfeRRR.", [200] = "subfzeRR.", [232] = "subfmeRR.", [520] = "subfcoRRR.", [552] = "subfoRRR.", [616] = "negoRR.", [648] = "subfeoRRR.", [712] = "subfzeoRR.", [744] = "subfmeoRR.", [9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.", [457] = "divduRRR.", [489] = "divdRRR.", [745] = "mulldoRRR.", [969] = "divduoRRR.", [1001] = "divdoRRR.", [10] = "addcRRR.", [138] = "addeRRR.", [202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.", [522] = "addcoRRR.", [650] = "addeoRRR.", [714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.", [11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.", [459] = "divwuRRR.", [491] = "divwRRR.", [747] = "mullwoRRR.", [971] = "divwouRRR.", [1003] = "divwoRRR.", [15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR", [144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", }, [19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", }, [371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", }, [339] = { shift = 11, mask = 1023, [32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR", }, [467] = { shift = 11, mask = 1023, [32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR", }, [20] = "lwarxRR0R", [84] = "ldarxRR0R", [21] = "ldxRR0R", [53] = "lduxRRR", [149] = "stdxRR0R", [181] = "stduxRRR", [341] = "lwaxRR0R", [373] = "lwauxRRR", [23] = "lwzxRR0R", [55] = "lwzuxRRR", [87] = "lbzxRR0R", [119] = "lbzuxRRR", [151] = "stwxRR0R", [183] = "stwuxRRR", [215] = "stbxRR0R", [247] = "stbuxRRR", [279] = "lhzxRR0R", [311] = "lhzuxRRR", [343] = "lhaxRR0R", [375] = "lhauxRRR", [407] = "sthxRR0R", [439] = "sthuxRRR", [54] = "dcbst-R0R", [86] = "dcbf-R0R", [150] = "stwcxRR0R.", [214] = "stdcxRR0R.", [246] = "dcbtst-R0R", [278] = "dcbt-R0R", [310] = "eciwxRR0R", [438] = "ecowxRR0R", [470] = "dcbi-RR", [598] = { shift = 21, mask = 3, [0] = "sync", "lwsync", "ptesync", }, [758] = "dcba-RR", [854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R", [26] = "cntlzwRR~", [58] = "cntlzdRR~", [122] = "popcntbRR~", [154] = "prtywRR~", [186] = "prtydRR~", [28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.", [284] = "eqvRR~R.", [316] = "xorRR~R.", [412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.", [508] = "cmpbRR~R", [512] = "mcrxrX", [532] = "ldbrxRR0R", [660] = "stdbrxRR0R", [533] = "lswxRR0R", [597] = "lswiRR0A", [661] = "stswxRR0R", [725] = "stswiRR0A", [534] = "lwbrxRR0R", [662] = "stwbrxRR0R", [790] = "lhbrxRR0R", [918] = "sthbrxRR0R", [535] = "lfsxFR0R", [567] = "lfsuxFRR", [599] = "lfdxFR0R", [631] = "lfduxFRR", [663] = "stfsxFR0R", [695] = "stfsuxFRR", [727] = "stfdxFR0R", [759] = "stfduxFR0R", [855] = "lfiwaxFR0R", [983] = "stfiwxFR0R", [24] = "slwRR~R.", [27] = "sldRR~R.", [536] = "srwRR~R.", [792] = "srawRR~R.", [824] = "srawiRR~A.", [794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.", [922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.", [539] = "srdRR~R.", }, { __index = function(t, x) if band(x, 31) == 15 then return "iselRRRC" end end }) local map_ld = { shift = 0, mask = 3, [0] = "ldRRE", "lduRRE", "lwaRRE", } local map_std = { shift = 0, mask = 3, [0] = "stdRRE", "stduRRE", } local map_fps = { shift = 5, mask = 1, { shift = 1, mask = 15, [0] = false, false, "fdivsFFF.", false, "fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false, "fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false, "fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.", } } local map_fpd = { shift = 5, mask = 1, [0] = { shift = 1, mask = 1023, [0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX", [38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>", [8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.", [136] = "fnabsF-F.", [264] = "fabsF-F.", [12] = "frspF-F.", [14] = "fctiwF-F.", [15] = "fctiwzF-F.", [583] = "mffsF.", [711] = "mtfsfZF.", [392] = "frinF-F.", [424] = "frizF-F.", [456] = "fripF-F.", [488] = "frimF-F.", [814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.", }, { shift = 1, mask = 15, [0] = false, false, "fdivFFF.", false, "fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.", "freF-F.", "fmulFF-F.", "frsqrteF-F.", false, "fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.", } } local map_spe = { shift = 0, mask = 2047, [512] = "evaddwRRR", [514] = "evaddiwRAR~", [516] = "evsubwRRR~", [518] = "evsubiwRAR~", [520] = "evabsRR", [521] = "evnegRR", [522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR", [525] = "evcntlzwRR", [526] = "evcntlswRR", [527] = "brincRRR", [529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR", [535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=", [537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR", [544] = "evsrwuRRR", [545] = "evsrwsRRR", [546] = "evsrwiuRRA", [547] = "evsrwisRRA", [548] = "evslwRRR", [550] = "evslwiRRA", [552] = "evrlwRRR", [553] = "evsplatiRS", [554] = "evrlwiRRA", [555] = "evsplatfiRS", [556] = "evmergehiRRR", [557] = "evmergeloRRR", [558] = "evmergehiloRRR", [559] = "evmergelohiRRR", [560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR", [562] = "evcmpltuYRR", [563] = "evcmpltsYRR", [564] = "evcmpeqYRR", [632] = "evselRRR", [633] = "evselRRRW", [634] = "evselRRRW", [635] = "evselRRRW", [636] = "evselRRRW", [637] = "evselRRRW", [638] = "evselRRRW", [639] = "evselRRRW", [640] = "evfsaddRRR", [641] = "evfssubRRR", [644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR", [648] = "evfsmulRRR", [649] = "evfsdivRRR", [652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR", [656] = "evfscfuiR-R", [657] = "evfscfsiR-R", [658] = "evfscfufR-R", [659] = "evfscfsfR-R", [660] = "evfsctuiR-R", [661] = "evfsctsiR-R", [662] = "evfsctufR-R", [663] = "evfsctsfR-R", [664] = "evfsctuizR-R", [666] = "evfsctsizR-R", [668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR", [704] = "efsaddRRR", [705] = "efssubRRR", [708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR", [712] = "efsmulRRR", [713] = "efsdivRRR", [716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR", [719] = "efscfdR-R", [720] = "efscfuiR-R", [721] = "efscfsiR-R", [722] = "efscfufR-R", [723] = "efscfsfR-R", [724] = "efsctuiR-R", [725] = "efsctsiR-R", [726] = "efsctufR-R", [727] = "efsctsfR-R", [728] = "efsctuizR-R", [730] = "efsctsizR-R", [732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR", [736] = "efdaddRRR", [737] = "efdsubRRR", [738] = "efdcfuidR-R", [739] = "efdcfsidR-R", [740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR", [744] = "efdmulRRR", [745] = "efddivRRR", [746] = "efdctuidzR-R", [747] = "efdctsidzR-R", [748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR", [751] = "efdcfsR-R", [752] = "efdcfuiR-R", [753] = "efdcfsiR-R", [754] = "efdcfufR-R", [755] = "efdcfsfR-R", [756] = "efdctuiR-R", [757] = "efdctsiR-R", [758] = "efdctufR-R", [759] = "efdctsfR-R", [760] = "efdctuizR-R", [762] = "efdctsizR-R", [764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR", [768] = "evlddxRR0R", [769] = "evlddRR8", [770] = "evldwxRR0R", [771] = "evldwRR8", [772] = "evldhxRR0R", [773] = "evldhRR8", [776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2", [780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2", [782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2", [784] = "evlwhexRR0R", [785] = "evlwheRR4", [788] = "evlwhouxRR0R", [789] = "evlwhouRR4", [790] = "evlwhosxRR0R", [791] = "evlwhosRR4", [792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4", [796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4", [800] = "evstddxRR0R", [801] = "evstddRR8", [802] = "evstdwxRR0R", [803] = "evstdwRR8", [804] = "evstdhxRR0R", [805] = "evstdhRR8", [816] = "evstwhexRR0R", [817] = "evstwheRR4", [820] = "evstwhoxRR0R", [821] = "evstwhoRR4", [824] = "evstwwexRR0R", [825] = "evstwweRR4", [828] = "evstwwoxRR0R", [829] = "evstwwoRR4", [1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR", [1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR", [1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR", [1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR", [1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR", [1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR", [1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR", [1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR", [1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR", [1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR", [1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR", [1147] = "evmwsmfaRRR", [1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR", [1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR", [1220] = "evmraRR", [1222] = "evdivwsRRR", [1223] = "evdivwuRRR", [1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR", [1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR", [1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR", [1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR", [1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR", [1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR", [1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR", [1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR", [1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR", [1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR", [1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR", [1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR", [1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR", [1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR", [1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR", [1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR", [1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR", [1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR", [1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR", [1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR", [1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR", [1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR", [1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR", [1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR", [1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR", [1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR", [1491] = "evmwssfanRRR", [1496] = "evmwumianRRR", [1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR", } local map_pri = { [0] = false, false, "tdiARI", "twiARI", map_spe, false, false, "mulliRRI", "subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI", "addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I", "b_KBJ", "sc", "bKJ", map_crops, "rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.", "oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U", "andi.RR~U", "andis.RR~U", map_rld, map_ext, "lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD", "stwRRD", "stwuRRD", "stbRRD", "stbuRRD", "lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD", "sthRRD", "sthuRRD", "lmwRRD", "stmwRRD", "lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD", "stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD", false, false, map_ld, map_fps, false, false, map_std, map_fpd, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", } local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", } -- Format a condition bit. local function condfmt(cond) if cond <= 3 then return map_cond[band(cond, 3)] else return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)]) end end ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) local operands = {} local last = nil local rs = 21 ctx.op = op ctx.rel = nil local opat = map_pri[rshift(b0, 2)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "R" then x = map_gpr[band(rshift(op, rs), 31)] rs = rs - 5 elseif p == "F" then x = "f"..band(rshift(op, rs), 31) rs = rs - 5 elseif p == "A" then x = band(rshift(op, rs), 31) rs = rs - 5 elseif p == "S" then x = arshift(lshift(op, 27-rs), 27) rs = rs - 5 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "D" or p == "E" then local disp = arshift(lshift(op, 16), 16) if p == "E" then disp = band(disp, -4) end if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p >= "2" and p <= "8" then local disp = band(rshift(op, rs), 31) * p if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p == "H" then x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4) rs = rs - 5 elseif p == "M" then x = band(rshift(op, rs), 31) + band(op, 0x20) elseif p == "C" then x = condfmt(band(rshift(op, rs), 31)) rs = rs - 5 elseif p == "B" then local bo = rshift(op, 21) local cond = band(rshift(op, 16), 31) local cn = "" rs = rs - 10 if band(bo, 4) == 0 then cn = band(bo, 2) == 0 and "dnz" or "dz" if band(bo, 0x10) == 0 then cn = cn..(band(bo, 8) == 0 and "f" or "t") end if band(bo, 0x10) == 0 then x = condfmt(cond) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") elseif band(bo, 0x10) == 0 then cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)] if cond > 3 then x = "cr"..rshift(cond, 2) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") end name = gsub(name, "_", cn) elseif p == "J" then x = arshift(lshift(op, 27-rs), 29-rs)*4 if band(op, 2) == 0 then x = ctx.addr + pos + x end ctx.rel = x x = "0x"..tohex(x) elseif p == "K" then if band(op, 1) ~= 0 then name = name.."l" end if band(op, 2) ~= 0 then name = name.."a" end elseif p == "X" or p == "Y" then x = band(rshift(op, rs+2), 7) if x == 0 and p == "Y" then x = nil else x = "cr"..x end rs = rs - 5 elseif p == "W" then x = "cr"..band(op, 7) elseif p == "Z" then x = band(rshift(op, rs-4), 255) rs = rs - 10 elseif p == ">" then operands[#operands] = rshift(operands[#operands], 1) elseif p == "0" then if last == "r0" then operands[#operands] = nil if altname then name = altname end end elseif p == "L" then name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w") elseif p == "." then if band(op, 1) == 1 then name = name.."." end elseif p == "N" then if op == 0x60000000 then name = "nop"; break end elseif p == "~" then local n = #operands operands[n-1], operands[n] = operands[n], operands[n-1] elseif p == "=" then local n = #operands if last == operands[n-1] then operands[n] = nil name = altname end elseif p == "%" then local n = #operands if last == operands[n-1] and last == operands[n-2] then operands[n] = nil operands[n-1] = nil name = altname end elseif p == "-" then rs = rs - 5 else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. module(...) create = create_ disass = disass_ regname = regname_
apache-2.0
xponen/Zero-K
LuaRules/Gadgets/unit_transport_speed.lua
1
2558
function gadget:GetInfo() return { name = "Transport Speed", desc = "Lowers the speed of transports when they transport large loads.", author = "Google Frog", date = "31 August 2012", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local mass = {} for i=1,#UnitDefs do local ud = UnitDefs[i] mass[i] = ud.mass end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local inTransport = {} function gadget:UnitUnloaded(unitID, unitDefID, unitTeam, transportID, transportTeam) if unitID then inTransport[unitID] = nil end if Spring.ValidUnitID(unitID) and not Spring.GetUnitIsDead(transportID) then local tudid = Spring.GetUnitDefID(transportID) Spring.SetUnitRulesParam(transportID, "effectiveMass", mass[tudid]) Spring.SetUnitRulesParam(transportID, "selfMoveSpeedChange", 1) GG.UpdateUnitAttributes(transportID) end end function gadget:UnitLoaded(unitID, unitDefID, unitTeam, transportID, transportTeam) if Spring.ValidUnitID(unitID) and Spring.ValidUnitID(transportID) then local tudid = Spring.GetUnitDefID(transportID) if tudid and unitDefID then local effectiveMass = mass[tudid] + mass[unitDefID] local speedFactor = math.min(1, 3 * mass[tudid]/(effectiveMass)) Spring.SetUnitRulesParam(transportID, "effectiveMass", effectiveMass) Spring.SetUnitRulesParam(transportID, "selfMoveSpeedChange", speedFactor) GG.attUnits[transportID] = true GG.UpdateUnitAttributes(transportID) inTransport[unitID] = transportID end end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) if inTransport[unitID] then local transportID = inTransport[unitID] if not Spring.GetUnitIsDead(transportID) then local tudid = Spring.GetUnitDefID(transportID) Spring.SetUnitRulesParam(transportID, "effectiveMass", mass[tudid]) Spring.SetUnitRulesParam(transportID, "selfMoveSpeedChange", 1) GG.UpdateUnitAttributes(transportID) end inTransport[unitID] = nil end end
gpl-2.0
Ali021s/Ali021
plugins/lock_fwd.lua
9
1105
do local function pre_process(msg) --Checking mute local hash = 'mate:'..msg.to.id if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) and not is_admin1(msg) then delete_msg(msg.id, ok_cb, true) return "done" end return msg end local function run(msg, matches) chat_id = msg.to.id if is_momod(msg) and matches[1] == 'lock' or matches[1] == 'قفل کردن' then local hash = 'mate:'..msg.to.id redis:set(hash, true) return "" elseif is_momod(msg) and matches[1] == 'unlock' or matches[1] == 'بازکردن' then local hash = 'mate:'..msg.to.id redis:del(hash) return "" end end return { patterns = { '^[/!#](lock) fwd$', '^[/!#](unlock) fwd$', '^[/!#](قفل کردن) فوروارد$', '^[/!#](بازکردن) فوروارد$' }, run = run, pre_process = pre_process } end
agpl-3.0
xponen/Zero-K
effects/gundam_otaplas.lua
50
48727
-- miniotaplas_fireball11 -- otaplas_fireball3 -- otaplas_fireball16 -- otaplas_fireball14 -- ota_plas -- miniotaplas_fireball17 -- otaplas_fireball18 -- otaplas_fireball1 -- otaplas_fireball11 -- miniotaplas_fireball13 -- otaplas_fireball10 -- miniotaplas_fireball16 -- otaplas_fireball13 -- miniotaplas_fireball2 -- otaplas_fireball7 -- miniotaplas_fireball14 -- otaplas_fireball12 -- miniotaplas_fireball7 -- otaplas_fireball17 -- miniotaplas_fireball9 -- miniotaplas_fireball18 -- miniota_plas -- miniotaplas_fireball3 -- otaplas_fireball6 -- otaplas_fireball4 -- miniotaplas_fireball5 -- otaplas_fireball8 -- miniotaplas_fireball15 -- otaplas_fireball2 -- miniotaplas_fireball6 -- otaplas_fireball15 -- otaplas_fireball9 -- miniotaplas_fireball8 -- miniotaplas_fireball4 -- miniotaplas_fireball10 -- miniotaplas_fireball12 -- miniotaplas_fireball1 -- otaplas_fireball5 return { ["miniotaplas_fireball11"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas11]], }, }, }, ["otaplas_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas3]], }, }, }, ["otaplas_fireball16"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas16]], }, }, }, ["otaplas_fireball14"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas14]], }, }, }, ["ota_plas"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:OTAPLAS_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame10 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 18, explosiongenerator = [[custom:OTAPLAS_FIREBALL10]], pos = [[0, 9, 0]], }, }, frame11 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 20, explosiongenerator = [[custom:OTAPLAS_FIREBALL11]], pos = [[0, 10, 0]], }, }, frame12 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 22, explosiongenerator = [[custom:OTAPLAS_FIREBALL12]], pos = [[0, 11, 0]], }, }, frame13 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 24, explosiongenerator = [[custom:OTAPLAS_FIREBALL13]], pos = [[0, 12, 0]], }, }, frame14 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 26, explosiongenerator = [[custom:OTAPLAS_FIREBALL14]], pos = [[0, 13, 0]], }, }, frame15 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 28, explosiongenerator = [[custom:OTAPLAS_FIREBALL15]], pos = [[0, 14, 0]], }, }, frame16 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:OTAPLAS_FIREBALL16]], pos = [[0, 15, 0]], }, }, frame17 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 32, explosiongenerator = [[custom:OTAPLAS_FIREBALL17]], pos = [[0, 16, 0]], }, }, frame18 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 34, explosiongenerator = [[custom:OTAPLAS_FIREBALL18]], pos = [[0, 17, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 2, explosiongenerator = [[custom:OTAPLAS_FIREBALL2]], pos = [[0, 1, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 4, explosiongenerator = [[custom:OTAPLAS_FIREBALL3]], pos = [[0, 2, 0]], }, }, frame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6, explosiongenerator = [[custom:OTAPLAS_FIREBALL4]], pos = [[0, 3, 0]], }, }, frame5 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 8, explosiongenerator = [[custom:OTAPLAS_FIREBALL5]], pos = [[0, 4, 0]], }, }, frame6 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:OTAPLAS_FIREBALL6]], pos = [[0, 5, 0]], }, }, frame7 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 12, explosiongenerator = [[custom:OTAPLAS_FIREBALL7]], pos = [[0, 6, 0]], }, }, frame8 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 14, explosiongenerator = [[custom:OTAPLAS_FIREBALL8]], pos = [[0, 7, 0]], }, }, frame9 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 16, explosiongenerator = [[custom:OTAPLAS_FIREBALL9]], pos = [[0, 8, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 40, ttl = 20, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, }, ["miniotaplas_fireball17"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas17]], }, }, }, ["otaplas_fireball18"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas18]], }, }, }, ["otaplas_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 1 1 1 0.01 .5 .5 .5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas1]], }, }, }, ["otaplas_fireball11"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas11]], }, }, }, ["miniotaplas_fireball13"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas13]], }, }, }, ["otaplas_fireball10"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas10]], }, }, }, ["miniotaplas_fireball16"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas16]], }, }, }, ["otaplas_fireball13"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas13]], }, }, }, ["miniotaplas_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas2]], }, }, }, ["otaplas_fireball7"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas7]], }, }, }, ["miniotaplas_fireball14"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas14]], }, }, }, ["otaplas_fireball12"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas12]], }, }, }, ["miniotaplas_fireball7"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas7]], }, }, }, ["otaplas_fireball17"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas17]], }, }, }, ["miniotaplas_fireball9"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas9]], }, }, }, ["miniotaplas_fireball18"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas18]], }, }, }, ["miniota_plas"] = { frame1 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL1]], pos = [[0, 0, 0]], }, }, frame10 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 18, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL10]], pos = [[0, 9, 0]], }, }, frame11 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 20, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL11]], pos = [[0, 10, 0]], }, }, frame12 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 22, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL12]], pos = [[0, 11, 0]], }, }, frame13 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 24, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL13]], pos = [[0, 12, 0]], }, }, frame14 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 26, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL14]], pos = [[0, 13, 0]], }, }, frame15 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 28, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL15]], pos = [[0, 14, 0]], }, }, frame16 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL16]], pos = [[0, 15, 0]], }, }, frame17 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 32, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL17]], pos = [[0, 16, 0]], }, }, frame18 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 34, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL18]], pos = [[0, 17, 0]], }, }, frame2 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 2, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL2]], pos = [[0, 1, 0]], }, }, frame3 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 4, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL3]], pos = [[0, 2, 0]], }, }, frame4 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 6, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL4]], pos = [[0, 3, 0]], }, }, frame5 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 8, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL5]], pos = [[0, 4, 0]], }, }, frame6 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 10, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL6]], pos = [[0, 5, 0]], }, }, frame7 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 12, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL7]], pos = [[0, 6, 0]], }, }, frame8 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 14, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL8]], pos = [[0, 7, 0]], }, }, frame9 = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 16, explosiongenerator = [[custom:MINIOTAPLAS_FIREBALL9]], pos = [[0, 8, 0]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 40, ttl = 20, color = { [1] = 1, [2] = 0.69999998807907, [3] = 0.69999998807907, }, }, }, ["miniotaplas_fireball3"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas3]], }, }, }, ["otaplas_fireball6"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas6]], }, }, }, ["otaplas_fireball4"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas4]], }, }, }, ["miniotaplas_fireball5"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas5]], }, }, }, ["otaplas_fireball8"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas8]], }, }, }, ["miniotaplas_fireball15"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas15]], }, }, }, ["otaplas_fireball2"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas2]], }, }, }, ["miniotaplas_fireball6"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas6]], }, }, }, ["otaplas_fireball15"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas15]], }, }, }, ["otaplas_fireball9"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas9]], }, }, }, ["miniotaplas_fireball8"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas8]], }, }, }, ["miniotaplas_fireball4"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas4]], }, }, }, ["miniotaplas_fireball10"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas10]], }, }, }, ["miniotaplas_fireball12"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas12]], }, }, }, ["miniotaplas_fireball1"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 0.01 1 1 1 0.01 .5 .5 .5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 25, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas1]], }, }, }, ["otaplas_fireball5"] = { wezels = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.5 0.5 0.5 0.01 1 1 1 0.01 0.5 0.5 0.5 0.01]], directional = false, emitrot = 0, emitrotspread = 1, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 6, particlelifespread = 0, particlesize = 35, particlesizespread = 0, particlespeed = .3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[otaplas5]], }, }, }, }
gpl-2.0
kiarash14/spam
plugins/domaintools.lua
359
1494
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function check(name) local api = "https://domainsearch.p.mashape.com/index.php?" local param = "name="..name local url = api..param local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "application/json" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local body = json:decode(body) --vardump(body) local domains = "List of domains for '"..name.."':\n" for k,v in pairs(body) do print(k) local status = " ❌ " if v == "Available" then status = " ✔ " end domains = domains..k..status.."\n" end return domains end local function run(msg, matches) if matches[1] == "check" then local name = matches[2] return check(name) end end return { description = "Domain tools", usage = {"!domain check [domain] : Check domain name availability.", }, patterns = { "^!domain (check) (.*)$", }, run = run }
gpl-2.0
alexandergall/snabbswitch
lib/ljsyscall/syscall/libc.lua
24
2992
-- things that are libc only, not syscalls -- this file will not be included if not running with libc eg for rump local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(S) local c = S.c local types = S.types local t, s, pt = types.t, types.s, types.pt local ffi = require "ffi" local h = require "syscall.helpers" local zeropointer = pt.void(0) local function retbool(ret) if ret == -1 then return nil, t.error() end return true end -- if getcwd not defined, fall back to libc implementation (currently osx, freebsd) -- freebsd implementation fairly complex if not S.getcwd then ffi.cdef [[ char *getcwd(char *buf, size_t size); ]] function S.getcwd(buf, size) size = size or c.PATH_MAX buf = buf or t.buffer(size) local ret = ffi.C.getcwd(buf, size) if ret == zeropointer then return nil, t.error() end return ffi.string(buf) end end -- in NetBSD, OSX exit defined in libc, no _exit syscall available if not S.exit then function S.exit(status) return retbool(ffi.C.exit(c.EXIT[status or 0])) end end if not S._exit then S._exit = S.exit -- provide syscall exit if possible end ffi.cdef [[ int __cxa_atexit(void (*func) (void *), void * arg, void * dso_handle); ]] local function inlibc(k) return ffi.C[k] end if pcall(inlibc, "exit") and pcall(inlibc, "__cxa_atexit") then function S.exit(status) return retbool(ffi.C.exit(c.EXIT[status or 0])) end -- use libc exit instead function S.atexit(f) return retbool(ffi.C.__cxa_atexit(f, nil, nil)) end end --[[ -- need more types defined int uname(struct utsname *buf); time_t time(time_t *t); ]] --[[ int gethostname(char *name, size_t namelen); int sethostname(const char *name, size_t len); int getdomainname(char *name, size_t namelen); int setdomainname(const char *name, size_t len); --]] -- environment ffi.cdef [[ // environment extern char **environ; int setenv(const char *name, const char *value, int overwrite); int unsetenv(const char *name); int clearenv(void); char *getenv(const char *name); ]] function S.environ() -- return whole environment as table local environ = ffi.C.environ if not environ then return nil end local r = {} local i = 0 while environ[i] ~= zeropointer do local e = ffi.string(environ[i]) local eq = e:find('=') if eq then r[e:sub(1, eq - 1)] = e:sub(eq + 1) end i = i + 1 end return r end function S.getenv(name) return S.environ()[name] end function S.unsetenv(name) return retbool(ffi.C.unsetenv(name)) end function S.setenv(name, value, overwrite) overwrite = h.booltoc(overwrite) -- allows nil as false/0 return retbool(ffi.C.setenv(name, value, overwrite)) end function S.clearenv() return retbool(ffi.C.clearenv()) end S.errno = ffi.errno return S end return {init = init}
apache-2.0
masterteam1/Master-plus
plugins/plugins.lua
1
6494
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local tmp = '\n\n@Al_Srai1' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '*|✖️|*>*' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '*|✔|>*' end nact = nact+1 end if not only_enabled or status == '*|✔|>*'then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end local text = text..'\n\n'..nsum..' *📂plugins installed*\n\n'..nact..' _✔️plugins enabled_\n\n'..nsum-nact..' _❌plugins disabled_'..tmp return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '*|✖️|>*' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '*|✔|>*' end nact = nact+1 end if not only_enabled or status == '*|✔|>*'then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end local text = text.."\n_🔃All Plugins Reloaded_\n\n"..nact.." *✔️Plugins Enabled*\n"..nsum.." *📂Plugins Installed*\n\n@Al_Srai1" return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return ''..plugin_name..' _is enabled_' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return ''..plugin_name..' _does not exists_' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return ' '..name..' _does not exists_' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return ' '..name..' _not enabled_' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "_Plugin doesn't exists_" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return ' '..plugin..' _disabled on this chat_' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return '_This plugin is not disabled_' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return ' '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if is_sudo(msg) then if matches[1]:lower() == '!plist' or matches[1]:lower() == '/plist' or matches[1]:lower() == '#plist' then --after changed to moderator mode, set only sudo return list_all_plugins() end end -- Re-enable a plugin for this chat if matches[1] == 'pl' then if matches[2] == '+' and matches[4] == 'chat' then if is_momod(msg) then local receiver = msg.chat_id_ local plugin = matches[3] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end end -- Enable a plugin if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo if is_mod(msg) then local plugin_name = matches[3] print("enable: "..matches[3]) return enable_plugin(plugin_name) end end -- Disable a plugin on a chat if matches[2] == '-' and matches[4] == 'chat' then if is_mod(msg) then local plugin = matches[3] local receiver = msg.chat_id_ print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end end -- Disable a plugin if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[3] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[3]) return disable_plugin(matches[3]) end end -- Reload all the plugins! if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end if matches[1]:lower() == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plug disable [plugin] chat : disable plugin only this chat.", "!plug enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plist : list all plugins.", "!pl + [plugin] : enable plugin.", "!pl - [plugin] : disable plugin.", "!pl * : reloads all plugins." }, }, patterns = { "^[!/#]plist$", "^[!/#](pl) (+) ([%w_%.%-]+)$", "^[!/#](pl) (-) ([%w_%.%-]+)$", "^[!/#](pl) (+) ([%w_%.%-]+) (chat)", "^[!/#](pl) (-) ([%w_%.%-]+) (chat)", "^!pl? (*)$", "^[!/](reload)$" }, run = run } end
gpl-3.0
infernal1200/infernall
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
nexusstar/dotfiles
neovim/.config/nvim/lua/config/lsp_kind.lua
1
2856
local M = {} M.cmp_kind = { Class = " ", Color = " ", Constant = "", Constructor = " ", Default = " ", Enum = "練", EnumMember = " ", Event = " ", Field = "ﰠ ", File = " ", Folder = " ", Function = " ", Interface = " ", Keyword = " ", Method = "ƒ ", Module = " ", Operator = " ", Property = " ", Reference = "", Snippet = " ", -- " "," " Struct = "פּ ", Text = " ", TypeParameter = " ", Unit = "塞", Value = " ", Variable = " ", } M.icons = { error = " ", warn = " ", info = "", hint = " ", code_action = "", test = "", docs = "", clock = " ", calendar = " ", buffer = " ", settings = " ", ls_inactive = "轢", ls_active = "歷", question = "", screen = "冷", dart = " ", config = " ", git = "", magic = " ", } M.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "", staged = "", unmerged = "", renamed = "➜", untracked = "", deleted = "", ignored = "◌", }, folder = { arrow_closed = "", arrow_open = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "", }, } M.symbols_outline = { File = "", Module = "", Namespace = "", Package = "", Class = "", Method = "ƒ", Property = "", Field = "", Constructor = "", Enum = "練", Interface = "ﰮ", Function = "", Variable = "", Constant = "", String = "𝓐", Number = "#", Boolean = "⊨", Array = "", Object = "⦿", Key = "", Null = "NULL", EnumMember = "", Struct = "פּ", Event = "", Operator = "", TypeParameter = "𝙏", } M.todo_comments = { FIX = "律", TODO = " ", HACK = " ", WARN = "裂", PERF = "龍", NOTE = " ", ERROR = " ", REFS = "", } M.numbers = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", } M.file_icons = { Brown = { "" }, Aqua = { "" }, LightBlue = { "", "" }, Blue = { "", "", "", "", "", "", "", "", "", "", "", "", "" }, DarkBlue = { "", "" }, Purple = { "", "", "", "", "" }, Red = { "", "", "", "", "", "" }, Beige = { "", "", "" }, Yellow = { "", "", "λ", "", "" }, Orange = { "", "" }, DarkOrange = { "", "", "", "", "" }, Pink = { "", "" }, Salmon = { "" }, Green = { "", "", "", "", "", "" }, LightGreen = { "", "", "", "﵂" }, White = { "", "", "", "", "", "" }, } return M
unlicense
gpedro/forgottenserver
data/chatchannels/scripts/advertising.lua
48
1220
function canJoin(player) return player:getVocation():getId() ~= VOCATION_NONE or player:getAccountType() >= ACCOUNT_TYPE_SENIORTUTOR end local CHANNEL_ADVERTISING = 5 local muted = Condition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT) muted:setParameter(CONDITION_PARAM_SUBID, CHANNEL_ADVERTISING) muted:setParameter(CONDITION_PARAM_TICKS, 120000) function onSpeak(player, type, message) if player:getAccountType() >= ACCOUNT_TYPE_GAMEMASTER then if type == TALKTYPE_CHANNEL_Y then return TALKTYPE_CHANNEL_O end return true end if player:getLevel() == 1 then player:sendCancelMessage("You may not speak into channels as long as you are on level 1.") return false end if player:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_ADVERTISING) then player:sendCancelMessage("You may only place one offer in two minutes.") return false end player:addCondition(muted) if type == TALKTYPE_CHANNEL_O then if player:getAccountType() < ACCOUNT_TYPE_GAMEMASTER then type = TALKTYPE_CHANNEL_Y end elseif type == TALKTYPE_CHANNEL_R1 then if not getPlayerFlagValue(player, PlayerFlag_CanTalkRedChannel) then type = TALKTYPE_CHANNEL_Y end end return type end
gpl-2.0
mbmahdiiii/mbmhdi
plugins/stats.lua
866
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
alexandergall/snabbswitch
lib/ljsyscall/syscall/osx/c.lua
18
1783
-- This sets up the table of C functions -- For OSX we hope we do not need many overrides local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" local voidp = ffi.typeof("void *") local function void(x) return ffi.cast(voidp, x) end -- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t. local int, long = ffi.typeof("int"), ffi.typeof("long") local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long") local function inlibc_fn(k) return ffi.C[k] end -- Syscalls that just return ENOSYS but are in libc. Note these might vary by version in future local nosys_calls = { mlockall = true, } local C = setmetatable({}, { __index = function(C, k) if nosys_calls[k] then return nil end if pcall(inlibc_fn, k) then C[k] = ffi.C[k] -- add to table, so no need for this slow path again return C[k] else return nil end end }) -- new stat structure, else get legacy one; could use syscalls instead C.stat = C.stat64 C.fstat = C.fstat64 C.lstat = C.lstat64 -- TODO create syscall table. Except I cannot find how to call them, neither C.syscall nor C._syscall seems to exist --[[ local getdirentries = 196 local getdirentries64 = 344 function C.getdirentries(fd, buf, len, basep) return C._syscall(getdirentries64, int(fd), void(buf), int(len), void(basep)) end ]] -- cannot find these anywhere! --C.getdirentries = ffi.C._getdirentries --C.sigaction = ffi.C._sigaction return C
apache-2.0
D3vMa3sTrO/superbot
plugins/lock_user.lua
1
1106
--[[ _ _ _ _____ _____ ____ ____ / \ / \ / \ | ____|___|_ _| /_\ \ / __ \ Đєⱴ 💀: @MaEsTrO_0 / / \/ / \ / _ \ | _| / __| | | | |_\_/| | | | Đєⱴ 💀: @devmaestr0 / / \ \/ \ \ / ___ \| |___\__ \ | | | | \ \| |__| | Đєⱴ ฿๏ͳ💀: @iqMaestroBot /_/ \/ \_/_/ \_|_____|___/ |_| |_| \_\\____/ Đєⱴ ฿๏ͳ💀: @maestr0bot Đєⱴ Ϲḫ₳ͷͷєℓ💀: @DevMaestro —]] local function run(msg, matches) if is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['username'] then username = data[tostring(msg.to.id)]['settings']['username'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if username == "yes" then delete_msg(msg.id, ok_cb, true) end end return { patterns = { "@" }, run = run }
gpl-2.0
Elanis/SciFi-Pack-Addon-Gamemode
gamemodes/scifipack/entities/entities/gmod_emitter.lua
3
10259
AddCSLuaFile() DEFINE_BASECLASS( "base_gmodentity" ) ENT.Spawnable = false ENT.RenderGroup = RENDERGROUP_OPAQUE local matLight = Material( "sprites/light_ignorez" ) local matBeam = Material( "effects/lamp_beam" ) function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "Delay" ) self:NetworkVar( "Float", 1, "Scale" ) self:NetworkVar( "Bool", 0, "Toggle" ) self:NetworkVar( "Bool", 1, "On" ) self:NetworkVar( "String", 0, "Effect" ) end function ENT:Initialize() if ( SERVER ) then self:SetModel( "models/props_lab/tpplug.mdl" ) -- TODO: Find something better than this shitty shit. self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:DrawShadow( false ) self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) local phys = self:GetPhysicsObject() if ( IsValid( phys ) ) then phys:Wake() end end end --[[--------------------------------------------------------- Name: Draw -----------------------------------------------------------]] function ENT:Draw() -- Don't draw if we local ply = LocalPlayer() local wep = ply:GetActiveWeapon() if ( wep:IsValid() ) then local weapon_name = wep:GetClass() if ( weapon_name == "gmod_camera" ) then return end end BaseClass.Draw( self ) end --[[--------------------------------------------------------- Name: Think -----------------------------------------------------------]] function ENT:Think() if ( SERVER ) then return end BaseClass.Think( self ) if ( !self:GetOn() ) then return end self.Delay = self.Delay or 0 if ( self.Delay > CurTime() ) then return end self.Delay = CurTime() + self:GetDelay() -- -- Find our effect table -- local Effect = self:GetEffect() local list = list.Get( "EffectType" ) local EffectTable = list[ Effect ] if ( !EffectTable ) then return end local Angle = self:GetAngles() EffectTable.func( self, self:GetPos() + Angle:Forward() * 12, Angle, self:GetScale() ) end --[[--------------------------------------------------------- Overridden because I want to show the name of the player that spawned it.. -----------------------------------------------------------]] function ENT:GetOverlayText() return self:GetPlayerName() end if ( SERVER ) then numpad.Register( "Emitter_On", function ( pl, ent ) if ( !IsValid( ent ) ) then return end if ( ent:GetToggle() ) then ent:SetOn( !ent:GetOn() ) return end ent:SetOn( true ) end ) numpad.Register( "Emitter_Off", function ( pl, ent ) if ( !IsValid( ent ) ) then return end if ( ent:GetToggle() ) then return end ent:SetOn( false ) end ) end game.AddParticles( "particles/gmod_effects.pcf" ) PrecacheParticleSystem( "generic_smoke" ) list.Set( "EffectType", "smoke", { print = "#effecttype.smoke", material = "gui/effects/smoke.png", func = function( ent, pos, angle, scale ) ParticleEffect( "generic_smoke", pos, angle, ent ) end }) list.Set( "EffectType", "sparks", { print = "#effecttype.sparks", material = "gui/effects/sparks.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() * scale ) effectdata:SetMagnitude( scale / 2 ) effectdata:SetRadius( 8 - scale ) util.Effect( "Sparks", effectdata, true, true ) end }) list.Set( "EffectType", "stunstickimpact", { print = "#effecttype.stunstick", material = "gui/effects/stunstickimpact.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() ) util.Effect( "stunstickimpact", effectdata, true, true ) end }) list.Set( "EffectType", "manhacksparks", { print = "#effecttype.manhack", material = "gui/effects/manhacksparks.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() * scale ) util.Effect( "manhacksparks", effectdata, true, true ) end }) list.Set( "EffectType", "bloodspray", { print = "#effecttype.blood", material = "gui/effects/bloodspray.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() * math.max( 3, scale ) / 3 ) effectdata:SetMagnitude( 1 ) effectdata:SetScale( scale + 9 ) effectdata:SetColor( 0 ) effectdata:SetFlags( 3 ) util.Effect( "bloodspray", effectdata, true, true ) end }) list.Set( "EffectType", "striderblood", { print = "#effecttype.strider", material = "gui/effects/striderblood.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() * ( 6 - scale ) / 2 ) effectdata:SetScale( scale / 2 ) util.Effect( "StriderBlood", effectdata, true, true ) end }) list.Set( "EffectType", "shells", { print = "#effecttype.pistol", material = "gui/effects/shells.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetAngles( angle ) util.Effect( "ShellEject", effectdata, true, true ) end }) list.Set( "EffectType", "rifleshells", { print = "#effecttype.rifle", material = "gui/effects/rifleshells.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetAngles( angle ) util.Effect( "RifleShellEject", effectdata, true, true ) end }) list.Set( "EffectType", "shotgunshells", { print = "#effecttype.shotgun", material = "gui/effects/shotgunshells.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetAngles( angle ) util.Effect( "ShotgunShellEject", effectdata, true, true ) end }) list.Set( "EffectType", "cball_explode", { print = "#effecttype.cball_explode", material = "gui/effects/cball_explode.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "cball_explode", effectdata, true, true ) end }) list.Set( "EffectType", "cball_bounce", { print = "#effecttype.cball_bounce", material = "gui/effects/cball_bounce.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() * scale / 4 ) effectdata:SetRadius( scale * 2 ) util.Effect( "cball_bounce", effectdata, true, true ) end }) list.Set( "EffectType", "thumperdust", { print = "#effecttype.thumperdust", material = "gui/effects/thumperdust.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetScale( scale * 24 ) util.Effect( "ThumperDust", effectdata, true, true ) end }) list.Set( "EffectType", "ar2impact", { print = "#effecttype.ar2impact", material = "gui/effects/ar2impact.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetNormal( angle:Forward() ) util.Effect( "AR2Impact", effectdata, true, true ) end }) list.Set( "EffectType", "ar2explosion", { print = "#effecttype.ar2explosion", material = "gui/effects/ar2explosion.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetRadius( scale * 4 ) effectdata:SetNormal( angle:Forward() ) util.Effect( "AR2Explosion", effectdata, true, true ) end }) list.Set( "EffectType", "explosion", { print = "#effecttype.explosion", material = "gui/effects/explosion.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "explosion", effectdata, true, true ) end }) list.Set( "EffectType", "helicoptermegabomb", { print = "#effecttype.helicoptermegabomb", material = "gui/effects/helicoptermegabomb.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "helicoptermegabomb", effectdata, true, true ) end }) list.Set( "EffectType", "underwaterexplosion", { print = "#effecttype.waterexplosion", material = "gui/effects/waterexplosion.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "WaterSurfaceExplosion", effectdata, true, true ) end }) list.Set( "EffectType", "watersplash", { print = "#effecttype.watersplash", material = "gui/effects/watersplash.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetScale( scale * 2 ) effectdata:SetFlags( 0 ) util.Effect( "WaterSplash", effectdata, true, true ) end }) list.Set( "EffectType", "dirtywatersplash", { print = "#effecttype.dirtywatersplash", material = "gui/effects/dirtywatersplash.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) effectdata:SetScale( scale * 2 ) effectdata:SetFlags( 1 ) util.Effect( "WaterSplash", effectdata, true, true ) end }) list.Set( "EffectType", "glassimpact", { print = "#effecttype.glassimpact", material = "gui/effects/glassimpact.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "GlassImpact", effectdata, true, true ) end }) list.Set( "EffectType", "bloodimpact", { print = "#effecttype.bloodimpact", material = "gui/effects/bloodimpact.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos ) util.Effect( "BloodImpact", effectdata, true, true ) end }) list.Set( "EffectType", "muzzleeffect", { print = "#effecttype.muzzleeffect", material = "gui/effects/muzzleeffect.png", func = function( ent, pos, angle, scale ) local effectdata = EffectData() effectdata:SetOrigin( pos + angle:Forward() * 4 ) effectdata:SetAngles( angle ) effectdata:SetScale( scale ) util.Effect( "MuzzleEffect", effectdata, true, true ) end })
gpl-2.0
xuejian1354/barrier_breaker
feeds/routing/luci-app-bmx6/files/usr/lib/lua/luci/model/cbi/bmx6/plugins.lua
20
1493
--[[ Copyright (C) 2011 Pau Escrich <pau@dabax.net> 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. The full GNU General Public License is included in this distribution in the file called "COPYING". --]] local sys = require("luci.sys") m = Map("bmx6", "bmx6") plugins_dir = {"/usr/lib/","/var/lib","/lib"} plugin = m:section(TypedSection,"plugin","Plugin") plugin.addremove = true plugin.anonymous = true plv = plugin:option(ListValue,"plugin", "Plugin") for _,d in ipairs(plugins_dir) do pl = luci.sys.exec("cd "..d..";ls bmx6_*") if #pl > 6 then for _,v in ipairs(luci.util.split(pl,"\n")) do plv:value(v,v) end end end function m.on_commit(self,map) local err = sys.call('/etc/init.d/bmx6 restart') if err ~= 0 then m.message = sys.exec("Cannot restart bmx6") end end return m
gpl-2.0
dani-sj/daniabbas
plugins/location.lua
185
1565
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end
gpl-2.0
DaanHaaz/love-base
scripts/libs/lurker.lua
1
6560
-- -- lurker -- -- Copyright (c) 2015 rxi -- -- This library is free software; you can redistribute it and/or modify it -- under the terms of the MIT license. See LICENSE for details. -- -- Assumes lume is in the same directory as this file local lume = require((...):gsub("[^/.\\]+$", "lume")) local lurker = { _version = "1.0.1" } local dir = love.filesystem.enumerate or love.filesystem.getDirectoryItems local isdir = love.filesystem.isDirectory local time = love.timer.getTime or os.time local lastmodified = love.filesystem.getLastModified local lovecallbacknames = { "update", "load", "draw", "mousepressed", "mousereleased", "keypressed", "keyreleased", "focus", "quit", } function lurker.init() lurker.print("Initing lurker") lurker.path = "." lurker.preswap = function() end lurker.postswap = function() end lurker.interval = .5 lurker.protected = false lurker.quiet = false lurker.lastscan = 0 lurker.lasterrorfile = nil lurker.files = {} lurker.funcwrappers = {} lurker.lovefuncs = {} lurker.state = "init" lume.each(lurker.getchanged(), lurker.resetfile) return lurker end function lurker.print(...) oldprint("[lurker] " .. lume.format(...)) end function lurker.listdir(path, recursive, skipdotfiles) path = (path == ".") and "" or path local function fullpath(x) return path .. "/" .. x end local t = {} for _, f in pairs(lume.map(dir(path), fullpath)) do if not skipdotfiles or not f:match("/%.[^/]*$") then if recursive and isdir(f) then t = lume.concat(t, lurker.listdir(f, true, true)) else table.insert(t, lume.trim(f, "/")) end end end return t end function lurker.initwrappers() for _, v in pairs(lovecallbacknames) do lurker.funcwrappers[v] = function(...) local args = {...} xpcall(function() return lurker.lovefuncs[v] and lurker.lovefuncs[v](unpack(args)) end, lurker.onerror) end lurker.lovefuncs[v] = love[v] end lurker.updatewrappers() end function lurker.updatewrappers() for _, v in pairs(lovecallbacknames) do if love[v] ~= lurker.funcwrappers[v] then lurker.lovefuncs[v] = love[v] love[v] = lurker.funcwrappers[v] end end end function lurker.onerror(e, nostacktrace) lurker.print("An error occurred; switching to error state") lurker.state = "error" -- Release mouse local setgrab = love.mouse.setGrab or love.mouse.setGrabbed setgrab(false) -- Set up callbacks for _, v in pairs(lovecallbacknames) do love[v] = function() end end love.update = lurker.update love.keypressed = function(k) if k == "escape" then lurker.print("Exiting...") love.event.quit() end end local stacktrace = nostacktrace and "" or lume.trim((debug.traceback("", 2):gsub("\t", ""))) local msg = lume.format("{1}\n\n{2}", {e, stacktrace}) local colors = { 0xFF1E1E2C, 0xFFF0A3A3, 0xFF92B5B0, 0xFF66666A, 0xFFCDCDCD } love.graphics.reset() love.graphics.setFont(love.graphics.newFont(12)) love.draw = function() local pad = 25 local width = love.graphics.getWidth() local function drawhr(pos, color1, color2) local animpos = lume.smooth(pad, width - pad - 8, lume.pingpong(time())) if color1 then love.graphics.setColor(lume.rgba(color1)) end love.graphics.rectangle("fill", pad, pos, width - pad*2, 1) if color2 then love.graphics.setColor(lume.rgba(color2)) end love.graphics.rectangle("fill", animpos, pos, 8, 1) end local function drawtext(str, x, y, color, limit) love.graphics.setColor(lume.rgba(color)) love.graphics[limit and "printf" or "print"](str, x, y, limit) end love.graphics.setBackgroundColor(lume.rgba(colors[1])) love.graphics.clear() drawtext("An error has occurred", pad, pad, colors[2]) drawtext("lurker", width - love.graphics.getFont():getWidth("lurker") - pad, pad, colors[4]) drawhr(pad + 32, colors[4], colors[5]) drawtext("If you fix the problem and update the file the program will " .. "resume", pad, pad + 46, colors[3]) drawhr(pad + 72, colors[4], colors[5]) drawtext(msg, pad, pad + 90, colors[5], width - pad * 2) love.graphics.reset() end end function lurker.exitinitstate() lurker.state = "normal" if lurker.protected then lurker.initwrappers() end end function lurker.exiterrorstate() lurker.state = "normal" for _, v in pairs(lovecallbacknames) do love[v] = lurker.funcwrappers[v] end end function lurker.update() if lurker.state == "init" then lurker.exitinitstate() end local diff = time() - lurker.lastscan if diff > lurker.interval then lurker.lastscan = lurker.lastscan + diff local changed = lurker.scan() if #changed > 0 and lurker.lasterrorfile then local f = lurker.lasterrorfile lurker.lasterrorfile = nil lurker.hotswapfile(f) end end end function lurker.getchanged() local function fn(f) return f:match("%.lua$") and lurker.files[f] ~= lastmodified(f) end return lume.filter(lurker.listdir(lurker.path, true, true), fn) end function lurker.modname(f) return (f:gsub("%.lua$", ""):gsub("[/\\]", ".")) end function lurker.resetfile(f) lurker.files[f] = lastmodified(f) end function lurker.hotswapfile(f) lurker.print("Hotswapping '{1}'...", {f}) if lurker.state == "error" then lurker.exiterrorstate() end if lurker.preswap(f) then lurker.print("Hotswap of '{1}' aborted by preswap", {f}) lurker.resetfile(f) return end local modname = lurker.modname(f) local t, ok, err = lume.time(lume.hotswap, modname) if ok then lurker.print("Swapped '{1}' in {2} secs", {f, t}) else lurker.print("Failed to swap '{1}' : {2}", {f, err}) if not lurker.quiet and lurker.protected then lurker.lasterrorfile = f lurker.onerror(err, true) lurker.resetfile(f) return end end lurker.resetfile(f) lurker.postswap(f) if lurker.protected then lurker.updatewrappers() end end function lurker.scan() if lurker.state == "init" then lurker.exitinitstate() end local changed = lurker.getchanged() lume.each(changed, lurker.hotswapfile) return changed end return lurker.init()
mit
xponen/Zero-K
effects/gundam_powerplant_explosion.lua
25
3625
-- powerplant_explosion return { ["powerplant_explosion"] = { electric1 = { air = true, class = [[heatcloud]], count = 3, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.1, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 1, sizegrowth = 15, speed = [[0, 1 0, 0]], texture = [[electnovaexplo]], }, }, electric2 = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.3, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 3, sizegrowth = 25, speed = [[0, 0, 0]], texture = [[flare]], }, }, electricarcs1 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1.0 1.0 1.0 0.04 0.2 0.5 0.9 0.01 0.1 0.5 0.7 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 16, particlelife = 10, particlelifespread = 5, particlesize = 20, particlesizespread = 0, particlespeed = 7, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[lightening]], useairlos = false, }, }, groundflash = { air = true, alwaysvisible = true, circlealpha = 0.6, circlegrowth = 6, flashalpha = 0.9, flashsize = 220, ground = true, ttl = 13, water = true, color = { [1] = 0, [2] = 0.5, [3] = 1, }, }, smoke = { air = true, count = 8, ground = true, water = true, properties = { agespeed = 0.01, alwaysvisible = true, color = 0.1, pos = [[r-60 r60, 24, r-60 r60]], size = 50, sizeexpansion = 0.6, speed = [[r-3 r3, 1 r2.3, r-3 r3]], startsize = 10, }, }, whiteglow = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.1, maxheat = 15, pos = [[0, 5, 0]], size = 10, sizegrowth = 25, speed = [[0, 1 0, 0]], texture = [[laserend]], }, }, }, }
gpl-2.0
abasshacker/ali
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
rogerpueyo/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/system.lua
78
2244
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.util") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) s = m:section(TypedSection, "system", "") s.anonymous = true s.addremove = false local sysinfo = luci.util.ubus("system", "info") or { } local boardinfo = luci.util.ubus("system", "board") or { } local uptime = sysinfo.uptime or 0 local loads = sysinfo.load or { 0, 0, 0 } local memory = sysinfo.memory or { total = 0, free = 0, buffered = 0, shared = 0 } s:option(DummyValue, "_system", translate("Model")).value = boardinfo.model or "?" s:option(DummyValue, "_cpu", translate("System")).value = boardinfo.system or "?" s:option(DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0) s:option(DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s)", tonumber(memory.total) / 1024 / 1024, 100 * memory.buffered / memory.total, tostring(translate("buffered")), 100 * memory.free / memory.total, tostring(translate("free")) ) s:option(DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("Hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
apache-2.0
xponen/Zero-K
units/chicken_tiamat.lua
4
9070
unitDef = { unitname = [[chicken_tiamat]], name = [[Tiamat]], description = [[Heavy Assault/Riot]], acceleration = 0.36, autoheal = 20, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chicken_tiamat.png]], buildTime = 350, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND FIREPROOF]], customParams = { description_fr = [[Assault lourd]], description_de = [[Schwere Sturm-/Rioteinheit]], description_pl = [[Ciezkie wsparcie szturmowe]], fireproof = 1, helptext = [[The ultimate assault chicken, the Tiamat is a fire-breathing, iron-jawed, spore-spewing monstrosity that knows no fear, no mercy. It even has a mucous shield to protect itself and surrounding chickens from damage.]], helptext_fr = [[L'ultime unit? d'assault pouler, le Tiamat est une monstruosit? crachant des flammes, d?chirant de ses machoires d'acier et lan?ant des spores sur ses victimes. Elle poss?de m?me un bouclier ?nerg?tique r?sultant de sa fureur, lui procurant ? elle et aux unit?s alli?es ? proximit? une protection efficace durant leur progession vers l'adversaire.]], helptext_de = [[Das ultimative Sturmchicken: Tiamat ist eine feuer-, eisenspuckende und Sporenspeiende Monstrosität, die keine Angst oder Furcht kennt, aber auch keine Gnade. Sie besitzt sogar ein schleimiges Schild, welches sie selbst und nahe, verbündete Einheiten schützt.]], helptext_pl = [[Tiamat to wytrzymale, ziejace ogniem i wypuszczajace zarodniki monstrum z mocnymi szczekami i sluzowa tarcza, ktora chroni zarowno Tiamat, jak i okoliczne kurczaki.]], }, explodeAs = [[NOWEAPON]], footprintX = 4, footprintZ = 4, iconType = [[t3generic]], idleAutoHeal = 20, idleTime = 300, leaveTracks = true, mass = 287, maxDamage = 3650, maxSlope = 37, maxVelocity = 2.3, maxWaterDepth = 5000, minCloakDistance = 75, movementClass = [[AKBOT6]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB STUPIDTARGET MINE]], objectName = [[chickenbroodqueen.s3o]], power = 350, seismicSignature = 4, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], [[custom:RAIDMUZZLE]], }, }, side = [[THUNDERBIRDS]], sightDistance = 256, smoothAnim = true, trackOffset = 7, trackStrength = 9, trackStretch = 1, trackType = [[ChickenTrack]], trackWidth = 34, turninplace = 0, turnRate = 806, upright = false, workerTime = 0, weapons = { { def = [[JAWS]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, { def = [[SPORES]], badTargetCategory = [[SWIM LAND SHIP HOVER]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[FLAMETHROWER]], badTargetCategory = [[FIREPROOF]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]], }, { def = [[SHIELD]], }, }, weaponDefs = { FLAMETHROWER = { name = [[Flamethrower]], areaOfEffect = 64, avoidFeature = false, avoidFriendly = false, collideFeature = false, collideGround = false, coreThickness = 0, craterBoost = 0, craterMult = 0, cegTag = [[flamer]], customParams = { flamethrower = [[1]], setunitsonfire = "1", burntime = [[450]], }, damage = { default = 12, subs = 0.01, }, duration = 0.01, explosionGenerator = [[custom:SMOKE]], fallOffRate = 1, fireStarter = 100, impulseBoost = 0, impulseFactor = 0, intensity = 0.3, interceptedByShieldType = 1, noExplode = true, noSelfDamage = true, --predictBoost = 1, range = 290, reloadtime = 0.16, rgbColor = [[1 1 1]], soundStart = [[weapon/flamethrower]], soundTrigger = true, texture1 = [[flame]], thickness = 0, tolerance = 5000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 800, }, JAWS = { name = [[Jaws]], areaOfEffect = 8, craterBoost = 0, craterMult = 0, damage = { default = 300, planes = 300, subs = 3, }, endsmoke = [[0]], explosionGenerator = [[custom:NONE]], impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 0, noSelfDamage = true, range = 160, reloadtime = 1.5, size = 0, soundHit = [[chickens/chickenbig2]], soundStart = [[chickens/chickenbig2]], targetborder = 1, tolerance = 5000, turret = true, waterWeapon = true, weaponType = [[Cannon]], weaponVelocity = 500, }, SHIELD = { name = [[Shield]], craterMult = 0, damage = { default = 10, }, exteriorShield = true, impulseFactor = 0, interceptedByShieldType = 1, shieldAlpha = 0.15, shieldBadColor = [[1.0 1 0.1]], shieldGoodColor = [[0.1 1.0 0.1]], shieldInterceptType = 3, shieldPower = 2500, shieldPowerRegen = 180, shieldPowerRegenEnergy = 0, shieldRadius = 300, shieldRepulser = false, smartShield = true, texture1 = [[wake]], visibleShield = true, visibleShieldHitFrames = 30, visibleShieldRepulse = false, weaponType = [[Shield]], }, SPORES = { name = [[Spores]], areaOfEffect = 24, avoidFriendly = false, burst = 8, burstrate = 0.1, collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 100, planes = 100, subs = 100, }, dance = 60, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = 1, flightTime = 5, groundbounce = 1, guidance = true, heightmod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, lineOfSight = true, metalpershot = 0, model = [[chickeneggpink.s3o]], noSelfDamage = true, range = 600, reloadtime = 6, renderType = 1, selfprop = true, smokedelay = [[0.1]], smokeTrail = true, startsmoke = [[1]], startVelocity = 100, texture1 = [[]], texture2 = [[sporetrail]], tolerance = 10000, tracks = true, turnRate = 24000, turret = true, waterweapon = true, weaponAcceleration = 100, weaponType = [[MissileLauncher]], weaponVelocity = 500, wobble = 32000, }, }, } return lowerkeys({ chicken_tiamat = unitDef })
gpl-2.0
Elanis/SciFi-Pack-Addon-Gamemode
gamemodes/scifipack/entities/weapons/gmod_tool/stools/hydraulic.lua
4
7136
TOOL.Category = "Constraints" TOOL.Name = "#tool.hydraulic.name" TOOL.ClientConVar[ "group" ] = "37" TOOL.ClientConVar[ "width" ] = "3" TOOL.ClientConVar[ "addlength" ] = "100" TOOL.ClientConVar[ "fixed" ] = "1" TOOL.ClientConVar[ "speed" ] = "64" TOOL.ClientConVar[ "material" ] = "cable/rope" function TOOL:LeftClick( trace ) if ( IsValid( trace.Entity ) && trace.Entity:IsPlayer() ) then return false end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) self:SetOperation( 1 ) if ( iNum > 0 ) then if ( CLIENT ) then self:ClearObjects() return true end if ( ( !IsValid( self:GetEnt( 1 ) ) && !IsValid( self:GetEnt( 2 ) ) ) || iNum > 1 ) then self:ClearObjects() return true end -- Get client's CVars local width = self:GetClientNumber( "width", 3 ) local bind = self:GetClientNumber( "group", 1 ) local AddLength = self:GetClientNumber( "addlength", 0 ) local fixed = self:GetClientNumber( "fixed", 1 ) local speed = self:GetClientNumber( "speed", 64 ) local material = self:GetClientInfo( "material" ) -- Get information we're about to use local Ent1, Ent2 = self:GetEnt( 1 ), self:GetEnt( 2 ) local Bone1, Bone2 = self:GetBone( 1 ), self:GetBone( 2 ) local LPos1, LPos2 = self:GetLocalPos( 1 ), self:GetLocalPos( 2 ) local WPos1, WPos2 = self:GetPos( 1 ), self:GetPos( 2 ) local Length1 = ( WPos1 - WPos2 ):Length() local Length2 = Length1 + AddLength local constraint, rope, controller, slider = constraint.Hydraulic( self:GetOwner(), Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Length1, Length2, width, bind, fixed, speed, material ) undo.Create( "Hydraulic" ) if ( IsValid( constraint ) ) then undo.AddEntity( constraint ) end if ( IsValid( rope ) ) then undo.AddEntity( rope ) end if ( IsValid( slider ) ) then undo.AddEntity( slider ) end if ( IsValid( controller ) ) then undo.AddEntity( controller ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() if ( IsValid( constraint ) ) then self:GetOwner():AddCleanup( "ropeconstraints", constraint ) end if ( IsValid( rope ) ) then self:GetOwner():AddCleanup( "ropeconstraints", rope ) end if ( IsValid( slider ) ) then self:GetOwner():AddCleanup( "ropeconstraints", slider ) end if ( IsValid( controller ) ) then self:GetOwner():AddCleanup( "ropeconstraints", controller ) end -- Clear the objects so we're ready to go again self:ClearObjects() else self:SetStage( iNum + 1 ) end return true end function TOOL:RightClick( trace ) if ( self:GetOperation() == 1 ) then return false end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) local tr = {} tr.start = trace.HitPos tr.endpos = tr.start + ( trace.HitNormal * 16384 ) tr.filter = {} tr.filter[ 1 ] = self:GetOwner() if ( IsValid( trace.Entity ) ) then tr.filter[ 2 ] = trace.Entity end local tr = util.TraceLine( tr ) if ( !tr.Hit ) then self:ClearObjects() return end -- Don't try to constrain world to world if ( trace.HitWorld && tr.HitWorld ) then self:ClearObjects() return end if ( IsValid( trace.Entity ) && trace.Entity:IsPlayer() ) then self:ClearObjects() return end if ( IsValid( tr.Entity ) && tr.Entity:IsPlayer() ) then self:ClearObjects() return end local Phys2 = tr.Entity:GetPhysicsObjectNum( tr.PhysicsBone ) self:SetObject( 2, tr.Entity, tr.HitPos, Phys2, tr.PhysicsBone, tr.HitNormal ) if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local width = self:GetClientNumber( "width", 3 ) local bind = self:GetClientNumber( "group", 1 ) local AddLength = self:GetClientNumber( "addlength", 0 ) local fixed = self:GetClientNumber( "fixed", 1 ) local speed = self:GetClientNumber( "speed", 64 ) local material = self:GetClientInfo( "material" ) -- Get information we're about to use local Ent1, Ent2 = self:GetEnt( 1 ), self:GetEnt( 2 ) local Bone1, Bone2 = self:GetBone( 1 ), self:GetBone( 2 ) local LPos1, LPos2 = self:GetLocalPos( 1 ), self:GetLocalPos( 2 ) local WPos1, WPos2 = self:GetPos( 1 ), self:GetPos( 2 ) local Length1 = ( WPos1 - WPos2 ):Length() local Length2 = Length1 + AddLength local constraint, rope, controller, slider = constraint.Hydraulic( self:GetOwner(), Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Length1, Length2, width, bind, fixed, speed, material ) undo.Create( "Hydraulic" ) if ( IsValid( constraint ) ) then undo.AddEntity( constraint ) end if ( IsValid( rope ) ) then undo.AddEntity( rope ) end if ( IsValid( slider ) ) then undo.AddEntity( slider ) end if ( IsValid( controller ) ) then undo.AddEntity( controller ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() if ( IsValid( constraint ) ) then self:GetOwner():AddCleanup( "ropeconstraints", constraint ) end if ( IsValid( rope ) ) then self:GetOwner():AddCleanup( "ropeconstraints", rope ) end if ( IsValid( slider ) ) then self:GetOwner():AddCleanup( "ropeconstraints", slider ) end if ( IsValid( controller ) ) then self:GetOwner():AddCleanup( "ropeconstraints", controller ) end -- Clear the objects so we're ready to go again self:ClearObjects() return true end function TOOL:Reload( trace ) if ( !IsValid( trace.Entity ) || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end return constraint.RemoveConstraints( trace.Entity, "Hydraulic" ) end function TOOL:Holster() self:ClearObjects() end local ConVarsDefault = TOOL:BuildConVarList() function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Description = "#tool.hydraulic.help" } ) CPanel:AddControl( "ComboBox", { MenuButton = 1, Folder = "hydraulic", Options = { [ "#preset.default" ] = ConVarsDefault }, CVars = table.GetKeys( ConVarsDefault ) } ) CPanel:AddControl( "Numpad", { Label = "#tool.hydraulic.controls", Command = "hydraulic_group" } ) CPanel:AddControl( "Slider", { Label = "#tool.hydraulic.addlength", Command = "hydraulic_addlength", Type = "Float", Min = -1000, Max = 1000, Help = true } ) CPanel:AddControl( "Slider", { Label = "#tool.hydraulic.speed", Command = "hydraulic_speed", Type = "Float", Min = 0, Max = 50, Help = true } ) CPanel:AddControl( "CheckBox", { Label = "#tool.hydraulic.fixed", Command = "hydraulic_fixed", Help = true } ) CPanel:AddControl( "Slider", { Label = "#tool.hydraulic.width", Command = "hydraulic_width", Type = "Float", Min = 0, Max = 5 } ) CPanel:AddControl( "RopeMaterial", { Label = "#tool.hydraulic.material", ConVar = "hydraulic_material" } ) end
gpl-2.0
nifty-site-manager/nsm
LuaJIT/src/jit/dis_x86.lua
6
33826
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2021 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a, AVX, AVX2 and even privileged and hypervisor -- (VMX/SVM) instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","vex*3$lesVrm","vex*2$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]="vex*3", [0xc5]="vex*2", [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrvm|movupdXrm|movsdXrvm", "movupsXmr|movssXmvr|movupdXmr|movsdXmvr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrvm||unpcklpdXrvm", "unpckhpsXrvm||unpckhpdXrvm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrvVmt|cvtpi2pdXrMm|cvtsi2sdXrvVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrvm","rcppsXrm|rcpssXrvm", "andpsXrvm||andpdXrvm","andnpsXrvm||andnpdXrvm", "orpsXrvm||orpdXrvm","xorpsXrvm||xorpdXrvm", "addpsXrvm|addssXrvm|addpdXrvm|addsdXrvm","mulpsXrvm|mulssXrvm|mulpdXrvm|mulsdXrvm", "cvtps2pdXrm|cvtss2sdXrvm|cvtpd2psXrm|cvtsd2ssXrvm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrvm|subssXrvm|subpdXrvm|subsdXrvm","minpsXrvm|minssXrvm|minpdXrvm|minsdXrvm", "divpsXrvm|divssXrvm|divpdXrvm|divsdXrvm","maxpsXrvm|maxssXrvm|maxpdXrvm|maxsdXrvm", --6x "punpcklbwPrvm","punpcklwdPrvm","punpckldqPrvm","packsswbPrvm", "pcmpgtbPrvm","pcmpgtwPrvm","pcmpgtdPrvm","packuswbPrvm", "punpckhbwPrvm","punpckhwdPrvm","punpckhdqPrvm","packssdwPrvm", "||punpcklqdqXrvm","||punpckhqdqXrvm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pvmu", "pshiftd!Pvmu","pshiftq!Mvmu||pshiftdq!Xvmu", "pcmpeqbPrvm","pcmpeqwPrvm","pcmpeqdPrvm","emms*|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrvm|haddpsXrvm","||hsubpdXrvm|hsubpsXrvm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrvmu|cmpssXrvmu|cmppdXrvmu|cmpsdXrvmu","$movntiVmr|", "pinsrwPrvWmu","pextrwDrPmu", "shufpsXrvmu||shufpdXrvmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrvm|addsubpsXrvm","psrlwPrvm","psrldPrvm","psrlqPrvm", "paddqPrvm","pmullwPrvm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrvm","psubuswPrvm","pminubPrvm","pandPrvm", "paddusbPrvm","padduswPrvm","pmaxubPrvm","pandnPrvm", --Ex "pavgbPrvm","psrawPrvm","psradPrvm","pavgwPrvm", "pmulhuwPrvm","pmulhwPrvm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrvm","psubswPrvm","pminswPrvm","porPrvm", "paddsbPrvm","paddswPrvm","pmaxswPrvm","pxorPrvm", --Fx "|||lddquXrm","psllwPrvm","pslldPrvm","psllqPrvm", "pmuludqPrvm","pmaddwdPrvm","psadbwPrvm","maskmovqMrm||maskmovdquXrm$", "psubbPrvm","psubwPrvm","psubdPrvm","psubqPrvm", "paddbPrvm","paddwPrvm","padddPrvm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrvm","phaddwPrvm","phadddPrvm","phaddswPrvm", "pmaddubswPrvm","phsubwPrvm","phsubdPrvm","phsubswPrvm", "psignbPrvm","psignwPrvm","psigndPrvm","pmulhrswPrvm", "||permilpsXrvm","||permilpdXrvm",nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma","||permpsXrvm","||ptestXrm", "||broadcastssXrm","||broadcastsdXrm","||broadcastf128XrlXm",nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrvm","||pcmpeqqXrvm","||$movntdqaXrm","||packusdwXrvm", "||maskmovpsXrvm","||maskmovpdXrvm","||maskmovpsXmvr","||maskmovpdXmvr", --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm","||permdXrvm","||pcmpgtqXrvm", "||pminsbXrvm","||pminsdXrvm","||pminuwXrvm","||pminudXrvm", "||pmaxsbXrvm","||pmaxsdXrvm","||pmaxuwXrvm","||pmaxudXrvm", --4x "||pmulddXrvm","||phminposuwXrm",nil,nil, nil,"||psrlvVSXrvm","||psravdXrvm","||psllvVSXrvm", --5x [0x58] = "||pbroadcastdXrlXm",[0x59] = "||pbroadcastqXrlXm", [0x5a] = "||broadcasti128XrlXm", --7x [0x78] = "||pbroadcastbXrlXm",[0x79] = "||pbroadcastwXrlXm", --8x [0x8c] = "||pmaskmovXrvVSm", [0x8e] = "||pmaskmovVSmXvr", --9x [0x96] = "||fmaddsub132pHXrvm",[0x97] = "||fmsubadd132pHXrvm", [0x98] = "||fmadd132pHXrvm",[0x99] = "||fmadd132sHXrvm", [0x9a] = "||fmsub132pHXrvm",[0x9b] = "||fmsub132sHXrvm", [0x9c] = "||fnmadd132pHXrvm",[0x9d] = "||fnmadd132sHXrvm", [0x9e] = "||fnmsub132pHXrvm",[0x9f] = "||fnmsub132sHXrvm", --Ax [0xa6] = "||fmaddsub213pHXrvm",[0xa7] = "||fmsubadd213pHXrvm", [0xa8] = "||fmadd213pHXrvm",[0xa9] = "||fmadd213sHXrvm", [0xaa] = "||fmsub213pHXrvm",[0xab] = "||fmsub213sHXrvm", [0xac] = "||fnmadd213pHXrvm",[0xad] = "||fnmadd213sHXrvm", [0xae] = "||fnmsub213pHXrvm",[0xaf] = "||fnmsub213sHXrvm", --Bx [0xb6] = "||fmaddsub231pHXrvm",[0xb7] = "||fmsubadd231pHXrvm", [0xb8] = "||fmadd231pHXrvm",[0xb9] = "||fmadd231sHXrvm", [0xba] = "||fmsub231pHXrvm",[0xbb] = "||fmsub231sHXrvm", [0xbc] = "||fnmadd231pHXrvm",[0xbd] = "||fnmadd231sHXrvm", [0xbe] = "||fnmsub231pHXrvm",[0xbf] = "||fnmsub231sHXrvm", --Dx [0xdc] = "||aesencXrvm", [0xdd] = "||aesenclastXrvm", [0xde] = "||aesdecXrvm", [0xdf] = "||aesdeclastXrvm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", [0xf7] = "| sarxVrmv| shlxVrmv| shrxVrmv", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]="||permqXrmu","||permpdXrmu","||pblenddXrvmu",nil, "||permilpsXrmu","||permilpdXrmu","||perm2f128Xrvmu",nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrvmu","||roundsdXrvmu", "||blendpsXrvmu","||blendpdXrvmu","||pblendwXrvmu","palignrPrvmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", "||insertf128XrvlXmu","||extractf128XlXmYru",nil,nil, nil,nil,nil,nil, --2x "||pinsrbXrvVmu","||insertpsXrvmu","||pinsrXrvVmuS",nil, --3x [0x38] = "||inserti128Xrvmu",[0x39] = "||extracti128XlXmYru", --4x [0x40] = "||dppsXrvmu", [0x41] = "||dppdXrvmu", [0x42] = "||mpsadbwXrvmu", [0x44] = "||pclmulqdqXrvmu", [0x46] = "||perm2i128Xrvmu", [0x4a] = "||blendvpsXrvmb",[0x4b] = "||blendvpdXrvmb", [0x4c] = "||pblendvbXrvmb", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", [0xdf] = "||aeskeygenassistXrmu", --Fx [0xf0] = "||| rorxVrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, Y = { "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, Y = 32, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", Y = "yword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "").. (ctx.vexl and "l" or "") if ctx.vexv and ctx.vexv ~= 0 then t = t.."v"..ctx.vexv end if t ~= "" then text = ctx.rex.."."..t.." "..gsub(text, "^ ", "") elseif ctx.rex == "vex" then text = gsub("v"..text, "^v ", "") end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.vexl = false; ctx.vexv = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.vexv = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false; ctx.vexl = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop, vexl = ctx.code, ctx.pos, ctx.stop, ctx.vexl -- Chars used: 1DFGHIMPQRSTUVWXYabcdfgijlmoprstuvwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXYFG]") then sz = p if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "H" then name = name..(ctx.rexw and "d" or "s") ctx.rexw = false elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "b" then local imm = getimm(ctx, pos, 1); if not imm then return end x = regs[imm/16+1] pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "v" then if ctx.vexv then x = regs[ctx.vexv+1]; ctx.vexv = false end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "l" then vexl = false elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, Y = putpat, H = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = "rex" end, -- VEX prefix. vex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. ctx.rex = "vex" local pos = ctx.pos if ctx.mrm then ctx.mrm = nil pos = pos-1 end local b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b < 128 then ctx.rexr = true end local m = 1 if pat == "3" then m = b%32; b = (b-m)/32 local nb = b%2; b = (b-nb)/2 if nb == 0 then ctx.rexb = true end local nx = b%2 if nx == 0 then ctx.rexx = true end b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b >= 128 then ctx.rexw = true end end ctx.pos = pos local map if m == 1 then map = map_opc2 elseif m == 2 then map = map_opc3["38"] elseif m == 3 then map = map_opc3["3a"] else return unknown(ctx) end local p = b%4; b = (b-p)/4 if p == 1 then ctx.o16 = "o16" elseif p == 2 then ctx.rep = "rep" elseif p == 3 then ctx.rep = "repne" end local l = b%2; b = (b-l)/2 if l ~= 0 then ctx.vexl = true end ctx.vexv = (-1-b)%16 return dispatchmap(ctx, map) end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, -- Special case for 0F 77. emms = function(ctx, name, pat) if ctx.rex ~= "vex" then return putop(ctx, "emms") elseif ctx.vexl then ctx.vexl = false return putop(ctx, "zeroall") else return putop(ctx, "zeroupper") end end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
mit
MRAHS/UBTEST
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
SirNate0/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/doit.lua
24
2028
-- Generate binding code -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- Last update: Apr 2003 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Modified by Aster Jian for Urho3D function parse_extra() for k,v in ipairs(_extra_parameters or {}) do local b,e,name,value = string.find(v, "^([^=]*)=(.*)$") if b then _extra_parameters[name] = value else _extra_parameters[v] = true end end end function doit () -- define package name, if not provided if not flags.n then if flags.f then flags.n = gsub(flags.f,"%..*$","") _,_,flags.n = string.find(flags.n, "([^/\\]*)$") else error("#no package name nor input file provided") end end -- parse table with extra paramters parse_extra() -- do this after setting the package name if flags['L'] then dofile(flags['L']) end -- add cppstring if not flags['S'] then _basic['string'] = 'cppstring' _basic['std::string'] = 'cppstring' _basic_ctype.cppstring = 'const char*' -- Urho3D: Add Urho3D::String Support in tolua++ _basic['String'] = 'urho3dstring' _basic['Urho3D::String'] = 'urho3dstring' _basic_ctype.urho3dstring = 'const char*' end -- proccess package local p = Package(flags.n,flags.f) if flags.p then return -- only parse end if flags.o then local st,msg = writeto(flags.o) if not st then error('#'..msg) end end p:decltype() if flags.P then p:print() else push(p) pre_output_hook(p) pop() p:preamble() p:supcode() push(p) pre_register_hook(p) pop() p:register() push(p) post_output_hook(p) pop() end if flags.o then writeto() end -- write header file if not flags.P then if flags.H then local st,msg = writeto(flags.H) if not st then error('#'..msg) end p:header() writeto() end end end
mit
pokorj18/vlc
share/lua/sd/icecast.lua
10
1975
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> 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. --]] require "simplexml" function descriptor() return { title="Icecast Radio Directory" } end function main() local tree = simplexml.parse_url("http://dir.xiph.org/yp.xml") for _, station in ipairs( tree.children ) do simplexml.add_name_maps( station ) local station_name = station.children_map["server_name"][1].children[1] if station_name == "Unspecified name" or station_name == "" then station_name = station.children_map["listen_url"][1].children[1] if string.find( station_name, "radionomy.com" ) then station_name = string.match( station_name, "([^/]+)$") station_name = string.gsub( station_name, "-", " " ) end end vlc.sd.add_item( {path=station.children_map["listen_url"][1].children[1], title=station_name, genre=station.children_map["genre"][1].children[1], nowplaying=station.children_map["current_song"][1].children[1], meta={ ["Icecast Bitrate"]=station.children_map["bitrate"][1].children[1], ["Icecast Server Type"]=station.children_map["server_type"][1].children[1] }} ) end end
gpl-2.0
rogerpueyo/luci
applications/luci-app-radicale2/luasrc/model/cbi/radicale2/logging.lua
10
1503
-- Licensed to the public under the Apache License 2.0. local m = Map("radicale2", translate("Radicale 2.x"), translate("A lightweight CalDAV/CardDAV server")) local s = m:section(NamedSection, "logging", "section", translate("Logging")) s.addremove = true s.anonymous = false local logging_file = nil logging_file = s:option(FileUpload, "config", translate("Logging File"), translate("Log configuration file (no file means default procd which ends up in syslog")) logging_file.rmempty = true logging_file.default = "" o = s:option(Button, "remove_conf", translate("Remove configuration for logging"), translate("This permanently deletes configuration for logging")) o.inputstyle = "remove" function o.write(self, section) if logging_file:cfgvalue(section) and fs.access(logging_file:cfgvalue(section)) then fs.unlink(loggin_file:cfgvalue(section)) end self.map:del(section, "config") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "radicale2", "logging")) end o = s:option(Flag, "debug", translate("Debug"), translate("Send debug information to logs")) o.rmempty = true o.default = o.disabled o = s:option(Flag, "full_environment", translate("Dump Environment"), translate("Include full environment in logs")) o.rmempty = true o.default = o.disabled o = s:option(Flag, "mask_passwords", translate("Mask Passwords"), translate("Redact passwords in logs")) o.rmempty = true o.default = o.enabled -- TODO: Allow configuration logging file from this page return m
apache-2.0
Canaan-Creative/luci
protocols/ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua
53
2242
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 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 IPv4 address of the relay")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,128)" ip6prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip6prefixlen.placeholder = "0" ip6prefixlen.datatype = "range(0,32)" 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)"
apache-2.0
adixcompany/self
bot/bot.lua
1
13760
-- #ArashN0 Self Robot -- #@adixco tdcli = dofile('./tg/tdcli.lua') serpent = (loadfile "./libs/serpent.lua")() feedparser = (loadfile "./libs/feedparser.lua")() require('./bot/utils') URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") chats = {} function do_notify (user, msg) local n = notify.Notification.new(user, msg) n:show () end function dl_cb (arg, data) -- vardump(data) end function vardump(value) print(serpent.block(value, {comment=false})) end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end function save_self( ) serialize_to_file(_self, './data/self.lua') print ('saved self into ./data/self.lua') end function create_self( ) self = { names = { "arash", "آرش", "ارش", "arsh", "سینوس", "رنجر", "sinoos" }, answers = { "bale", "jon", "jonm", "بله", "جونم؟" }, } serialize_to_file(self, './data/self.lua') print('saved self into ./data/self.lua') end function load_self( ) local f = io.open('./data/self.lua', "r") -- If self.lua doesn't exist if not f then print ("Created new self file: data/self.lua") create_self() else f:close() end local self = loadfile ("./data/self.lua")() for k, v in pairs(self.names) do --print("self names : " ..v) end return self end function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "self-manager", "groupmanager", "plugins", "self", "tools", "fun" }, sudo_users = {226726601}, admins = {}, disabled_channels = {}, moderation = {data = './data/moderation.json'}, info_text = [[》Arash N0 Age: 16 Location: Karaj 》 @ArashN0 ]], } serialize_to_file(config, './data/config.lua') print ('saved config into config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: ./data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " ..user) end return config end plugins = {} _config = load_config() _self = load_self() function load_plugins() local config = loadfile ("./data/config.lua")() for k, v in pairs(config.enabled_plugins) do print("Loading Plugins", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugins '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end function msg_valid(msg) if msg.date_ < os.time() - 60 then print('\27[36mNot valid: old msg\27[39m') return false end if is_channel_disabled(msg.chat_id_) then print('\27[36m➣Self Is Off :/\27[39m') return false end return true end function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = '_Plugin_ *'..check_markdown(disabled_plugin)..'* _is disabled on this chat_' print(warning) tdcli.sendMessage(receiver, "", 0, warning, 0, "md") return true end end end return false end function match_plugin(plugin, plugin_name, msg) if plugin.pre_process then --If plugin is for privileged users only local result = plugin.pre_process(msg) if result then print("pre process: ", plugin_name) -- tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md") end end for k, pattern in pairs(plugin.patterns) do matches = match_pattern(pattern, msg.text or msg.media.caption) if matches then if is_plugin_disabled_on_chat(plugin_name, msg.chat_id_) then return nil end print("Message matches: ", pattern..' | Plugin: '..plugin_name) if plugin.run then if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md") end end end return end end end _config = load_config() load_plugins() _self = load_self() function var_cb(msg, data) -------------Get Var------------ bot = {} msg.to = {} msg.from = {} msg.media = {} msg.id = msg.id_ msg.to.type = gp_type(data.chat_id_) if data.content_.caption_ then msg.media.caption = data.content_.caption_ end if data.reply_to_message_id_ ~= 0 then msg.reply_id = data.reply_to_message_id_ else msg.reply_id = false end function get_gp(arg, data) if gp_type(msg.chat_id_) == "channel" or gp_type(msg.chat_id_) == "chat" then msg.to.id = msg.chat_id_ msg.to.title = data.title_ else msg.to.id = msg.chat_id_ msg.to.title = false end end tdcli_function ({ ID = "GetChat", chat_id_ = data.chat_id_ }, get_gp, nil) function botifo_cb(arg, data) bot.id = data.id_ our_id = data.id_ if data.username_ then bot.username = data.username_ else bot.username = false end if data.first_name_ then bot.first_name = data.first_name_ end if data.last_name_ then bot.last_name = data.last_name_ else bot.last_name = false end if data.first_name_ and data.last_name_ then bot.print_name = data.first_name_..' '..data.last_name_ else bot.print_name = data.first_name_ end if data.phone_number_ then bot.phone = data.phone_number_ else bot.phone = false end end tdcli_function({ ID = 'GetMe'}, botifo_cb, {chat_id=msg.chat_id_}) function get_user(arg, data) msg.from.id = data.id_ if data.username_ then msg.from.username = data.username_ else msg.from.username = false end if data.first_name_ then msg.from.first_name = data.first_name_ end if data.last_name_ then msg.from.last_name = data.last_name_ else msg.from.last_name = false end if data.first_name_ and data.last_name_ then msg.from.print_name = data.first_name_..' '..data.last_name_ else msg.from.print_name = data.first_name_ end if data.phone_number_ then msg.from.phone = data.phone_number_ else msg.from.phone = false end match_plugins(msg) end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, get_user, nil) -------------End------------- -- return msg end function whoami() local usr = io.popen("id -un"):read('*a') usr = string.gsub(usr, '^%s+', '') usr = string.gsub(usr, '%s+$', '') usr = string.gsub(usr, '[\n\r]+', ' ') if usr:match("^root$") then tcpath = '/root/.telegram-cli' elseif not usr:match("^root$") then tcpath = '/home/'..usr..'/.telegram-cli' end end function file_cb(msg) if msg.content_.ID == "MessagePhoto" then photo_id = '' local function get_cb(arg, data) photo_id = data.content_.photo_.sizes_[2].photo_.id_ tdcli.downloadFile(photo_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVideo" then video_id = '' local function get_cb(arg, data) video_id = data.content_.video_.video_.id_ tdcli.downloadFile(video_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAnimation" then anim_id, anim_name = '', '' local function get_cb(arg, data) anim_id = data.content_.animation_.animation_.id_ anim_name = data.content_.animation_.file_name_ tdcli.downloadFile(anim_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVoice" then voice_id = '' local function get_cb(arg, data) voice_id = data.content_.voice_.voice_.id_ tdcli.downloadFile(voice_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAudio" then audio_id, audio_name, audio_title = '', '', '' local function get_cb(arg, data) audio_id = data.content_.audio_.audio_.id_ audio_name = data.content_.audio_.file_name_ audio_title = data.content_.audio_.title_ tdcli.downloadFile(audio_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageSticker" then sticker_id = '' local function get_cb(arg, data) sticker_id = data.content_.sticker_.sticker_.id_ tdcli.downloadFile(sticker_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageDocument" then document_id, document_name = '', '' local function get_cb(arg, data) document_id = data.content_.document_.document_.id_ document_name = data.content_.document_.file_name_ tdcli.downloadFile(document_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) end end function tdcli_update_callback (data) whoami() -- print(serpent.block(data)) if (data.ID == "UpdateNewMessage") then local msg = data.message_ local d = data.disable_notification_ local chat = chats[msg.chat_id_] local hash = 'msgs:'..msg.sender_user_id_..':'..msg.chat_id_ redis:incr(hash) if redis:get('markread') == 'on' then tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil) end if ((not d) and chat) then if msg.content_.ID == "MessageText" then do_notify (chat.title_, msg.content_.text_) else do_notify (chat.title_, msg.content_.ID) end end var_cb(msg, msg) file_cb(msg) if msg.content_.ID == "MessageText" then if msg_valid(msg) then msg.text = msg.content_.text_ msg.edited = false msg.pinned = false end elseif msg.content_.ID == "MessagePinMessage" then msg.pinned = true elseif msg.content_.ID == "MessagePhoto" then msg.photo_ = true elseif msg.content_.ID == "MessageVideo" then msg.video_ = true elseif msg.content_.ID == "MessageAnimation" then msg.animation_ = true elseif msg.content_.ID == "MessageVoice" then msg.voice_ = true elseif msg.content_.ID == "MessageAudio" then msg.audio_ = true elseif msg.content_.ID == "MessageForwardedFromUser" then msg.forward_info_ = true elseif msg.content_.ID == "MessageSticker" then msg.sticker_ = true elseif msg.content_.ID == "MessageContact" then msg.contact_ = true elseif msg.content_.ID == "MessageDocument" then msg.document_ = true elseif msg.content_.ID == "MessageLocation" then msg.location_ = true elseif msg.content_.ID == "MessageGame" then msg.game_ = true elseif msg.content_.ID == "MessageChatAddMembers" then if msg_valid(msg) then for i=0,#msg.content_.members_ do msg.adduser = msg.content_.members_[i].id_ end end elseif msg.content_.ID == "MessageChatJoinByLink" then if msg_valid(msg) then msg.joinuser = msg.sender_user_id_ end elseif msg.content_.ID == "MessageChatDeleteMember" then if msg_valid(msg) then msg.deluser = true end end elseif data.ID == "UpdateMessageContent" then cmsg = data local function edited_cb(arg, data) msg = data msg.media = {} if cmsg.new_content_.text_ then msg.text = cmsg.new_content_.text_ end if cmsg.new_content_.caption_ then msg.media.caption = cmsg.new_content_.caption_ end msg.edited = true var_cb(msg, msg) end tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_, message_id_ = data.message_id_ }, edited_cb, nil) elseif data.ID == "UpdateFile" then file_id = data.file_.id_ elseif (data.ID == "UpdateChat") then chat = data.chat_ chats[chat.id_] = chat elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil) end end
gpl-3.0
merlinblack/Game-Engine-Testbed
scripts/cell.lua
1
1223
require "lualib" cell={} local x = gui.screen.width-300 cell.panel = Widget( gui.mainLayer, x, gui.screen.height-145, 300, 145 ) cell.panel:background( gui.dialogBackground ) cell.text = MarkupText( gui.mainLayer, x+25, gui.screen.height-140, "" ) cell.text2 = MarkupText( gui.mainLayer, x+135, gui.screen.height-140, "" ) cell.panel:addChild( cell.text ) cell.panel:addChild( cell.text2 ) cell.text.markup.text = "%9g Cost\nh Cost\npath\nOpen\nClosed" cell.drag = DragButton( gui.mainLayer, x, gui.screen.height-145, cell.panel ) cell.panel:addChild( cell.drag ) function cell.update() local str local cellref local info while cell.stop == false do cellref = getCellUnderMouse() if cellref then info = cellref:info() str = "" str = str .. info.g .. "\n" str = str .. info.h .. "\n" str = str .. info.path .. "\n" str = str .. tostring(info.open) .. "\n" str = str .. tostring(info.closed) cell.text2.markup.text = str end wait(1) end gui.removeModeless(cell.panel) cell.panel:destroy() end cell.stop = false createTask( cell.update ) gui.addModeless( cell.panel )
mit
link4all/20170920openwrt
own_files/mt7628/files_tw7628_wifidog/usr/lib/lua/luci/controller/admin/index.lua
21
1141
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) function index() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.target = firstchild() page.title = _("Administration") page.order = 10 page.sysauth = "admin" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true -- Empty services menu to be populated by addons entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) dsp.context.urltoken.stok = nil luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{ sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end luci.http.redirect(luci.dispatcher.build_url()) end
gpl-2.0
link4all/20170920openwrt
own_files/mt7628/files_mifi_ss/usr/lib/lua/luci/controller/admin/index.lua
21
1141
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) function index() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.target = firstchild() page.title = _("Administration") page.order = 10 page.sysauth = "admin" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true -- Empty services menu to be populated by addons entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) dsp.context.urltoken.stok = nil luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{ sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end luci.http.redirect(luci.dispatcher.build_url()) end
gpl-2.0
link4all/20170920openwrt
own_files/ar934x/files_yn9341/usr/lib/lua/luci/controller/admin/index.lua
21
1141
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) function index() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.target = firstchild() page.title = _("Administration") page.order = 10 page.sysauth = "admin" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true -- Empty services menu to be populated by addons entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) dsp.context.urltoken.stok = nil luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{ sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end luci.http.redirect(luci.dispatcher.build_url()) end
gpl-2.0
xuejian1354/barrier_breaker
feeds/luci/protocols/ipv6/luasrc/model/network/proto_4x6.lua
63
1522
--[[ LuCI - Network model - 6to4, 6in4 & 6rd protocol extensions Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Copyright 2013 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. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"dslite"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "dslite" then return luci.i18n.translate("Dual-Stack Lite (RFC6333)") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "dslite" then return "ds-lite" end end function proto.is_installed(self) return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
gpl-2.0
caoyongfeng0214/nplexpress
npl_mod/express/request.lua
1
5222
NPL.load("(gl)script/ide/Json.lua"); local httpfile = NPL.load('./httpfile.lua'); local cookie = NPL.load('./cookie.lua'); -- Host localhost:3000 -- rcode 0 -- Connection keep-alive -- Accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 -- Cache-Control max-age=0 -- Accept-Encoding gzip, deflate, sdch, br -- method GET -- body -- url / -- User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 -- Upgrade-Insecure-Requests 1 -- Accept-Language zh-CN,zh;q=0.8 local request = {}; function request:new(o) o = o or {}; setmetatable(o, self); self.__index = self; o.nid = o.tid or o.nid; o.client = {}; o.client.ip = NPL.GetIP(o.nid); if(o.method) then o.method = string.upper(o.method); end local url = o.url; local aryUrl = url:split('?'); o.pathname = aryUrl[1]; o.query = {}; o.search = aryUrl[2]; if(o.search) then local arySearch = o.search:split('&'); local i = 1; for i = 1, #arySearch do local kv = arySearch[i]; local aryKV = kv:split('='); o.query[aryKV[1]] = aryKV[2]:decodeURI(); end end if(o.Cookie) then o.cookies = cookie.parse(o.Cookie); else o.cookies = {}; end local body = o.body; o.body = {}; if(body) then if(type(body) == 'string') then if(body:len() > 0) then local contentType = o['Content-Type']; -- application/x-www-form-urlencoded if(contentType and (contentType:startsWith('multipart/form-data'))) then -- body = body:replace('\r\n', '\n'); local idx0, idx1 = string.find(body, 'Content', 1); local boundaryKey_end = idx0 - 2; if(string.sub(body, idx0 - 2, idx0 - 1) == '\r\n') then boundaryKey_end = idx0 - 3; end local boundaryKey = string.sub(body, 1, boundaryKey_end); local start = idx1 + 1; local _, keyStart = string.find(body, 'name="', start); while keyStart do local keyEnd, _ = string.find(body, '"', keyStart + 1); local key = string.sub(body, keyStart + 1, keyEnd - 1); local nextwords = string.sub(body, keyEnd + 3, keyEnd + 12); if(nextwords == 'filename="') then local filenameStart = keyEnd + 13; local filenameEnd, _ = string.find(body, '"', filenameStart); local filename = string.sub(body, filenameStart, filenameEnd - 1); local fileContentTypeStart = filenameEnd + 16; if(string.sub(body, filenameEnd + 2, filenameEnd + 2) == '\n') then fileContentTypeStart = fileContentTypeStart + 1; end local fileContentTypeEnd, _ = string.find(body, '\n', fileContentTypeStart); local fileContentStart, _ = string.find(body, '\n', fileContentTypeEnd + 1) + 1; if(string.sub(body, fileContentTypeEnd - 1, fileContentTypeEnd - 1) == '\r') then fileContentTypeEnd = fileContentTypeEnd - 2; else fileContentTypeEnd = fileContentTypeEnd - 1; end local fileContentType = string.sub(body, fileContentTypeStart, fileContentTypeEnd); local fileContentEnd, fileContentEnd2 = string.find(body, boundaryKey, fileContentStart + 1); if(string.sub(body, fileContentEnd - 2, fileContentEnd - 1) == '\r\n') then fileContentEnd = fileContentEnd - 3; else fileContentEnd = fileContentEnd - 2; end local fileContent = string.sub(body, fileContentStart, fileContentEnd); if(not o.files) then o.files = {}; end o.files[#(o.files) + 1] = httpfile:new({ keyname = key, filename = filename, contentType = fileContentType, content = fileContent, -- size = fileContentEnd - 1 - fileContentStart size = #fileContent }); start = fileContentEnd2 + 1; else local valStart = keyEnd + 3; local valEnd, _ = string.find(body, boundaryKey, valStart + 1); local val = string.sub(body, valStart, valEnd - 2); if(val:startsWith('\r\n') and val:endsWith('\r')) then -- 解决当参数中有传文件时,其它文本参数前后取值范围不正确的bug val = string.sub(val, 3, -2); end -- print('=====start====', val:startsWith('\r'), val:startsWith('\n'), val:startsWith('\r\n'), val:endsWith('\r'), val:endsWith('\n'), val:endsWith('\r\n')); -- o.body[key] = val:replace('\n', '\r\n'); o.body[key] = val; start = valEnd + 1; end _, keyStart = string.find(body, 'name="', start); end elseif(contentType and (contentType:startsWith('application/json'))) then local _body = commonlib.Json.Decode(body); for k, v in pairs(_body) do o.body[k] = v; end else -- print(body); local items = body:split('&'); local i = 1; for i = 1, #items do local item = items[i]; local ary = item:split('='); local key = ary[1]; local val = ary[2]; if(val) then val = val:decodeURI(); else val = ''; end o.body[key] = val; end end end end end return o; end function request:onBefore() end function request:onAfter() end NPL.export(request);
lgpl-3.0
xponen/Zero-K
LuaRules/Gadgets/CustomUnitShaders/UnitMaterials/1_normalmapping.lua
17
4460
-- $Id$ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local materials = { normalMappedS3o = { shaderDefinitions = { "#define use_perspective_correct_shadows", "#define use_normalmapping", --"#define flip_normalmap", }, shader = include(GADGET_DIR .. "UnitMaterials/Shaders/default.lua"), usecamera = false, culling = GL.BACK, predl = nil, postdl = nil, texunits = { [0] = '%%UNITDEFID:0', [1] = '%%UNITDEFID:1', [2] = '$shadow', [3] = '$specular', [4] = '$reflection', [5] = '%NORMALTEX', }, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Automated normalmap detection local unitMaterials = {} local function FindNormalmap(tex1, tex2) local normaltex --// check if there is a corresponding _normals.dds file if (VFS.FileExists(tex1)) then local basefilename = tex1:gsub("%....","") if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end --if FileExists if (not normaltex) and tex2 and (VFS.FileExists(tex2)) then local basefilename = tex2:gsub("%....","") if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end return normaltex end for i=1,#UnitDefs do local udef = UnitDefs[i] if (udef.customParams.normaltex and VFS.FileExists(udef.customParams.normaltex)) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = udef.customParams.normaltex} elseif (udef.model.type == "s3o") then local modelpath = udef.model.path if (modelpath) then --// udef.model.textures is empty at gamestart, so read the texture filenames from the s3o directly local rawstr = VFS.LoadFile(modelpath) local header = rawstr:sub(1,60) local texPtrs = VFS.UnpackU32(header, 45, 2) local tex1,tex2 if (texPtrs[2] > 0) then tex2 = "unittextures/" .. rawstr:sub(texPtrs[2]+1, rawstr:len()-1) else texPtrs[2] = rawstr:len() end if (texPtrs[1] > 0) then tex1 = "unittextures/" .. rawstr:sub(texPtrs[1]+1, texPtrs[2]-1) end -- output units without tex2 if not tex2 then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2") end local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[udef.name]) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex} end end --if model elseif (udef.model.type == "obj") then local modelinfopath = udef.model.path if (modelinfopath) then modelinfopath = modelinfopath .. ".lua" if (VFS.FileExists(modelinfopath)) then local infoTbl = Include(modelinfopath) if (infoTbl) then local tex1 = "unittextures/" .. (infoTbl.tex1 or "") local tex2 = "unittextures/" .. (infoTbl.tex2 or "") -- output units without tex2 if not tex2 then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2") end local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[udef.name]) then unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex} end end end end end --elseif end --for -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return materials, unitMaterials -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
LuaDist2/evdev
evdev/constants.lua
2
12161
local _ENV = {} if setfenv then setfenv(1, _ENV) end -- Constants for the Linux evdev API -- created by the gen-constants.lua script from the <linux/input.h> header -- Event Types EV_VERSION = 0x010001 EV_SYN = 0x00 EV_KEY = 0x01 EV_REL = 0x02 EV_ABS = 0x03 EV_MSC = 0x04 EV_SW = 0x05 EV_LED = 0x11 EV_SND = 0x12 EV_REP = 0x14 EV_FF = 0x15 EV_PWR = 0x16 EV_FF_STATUS = 0x17 EV_MAX = 0x1f EV_CNT = (EV_MAX+1) -- Synchronization SYN_REPORT = 0 SYN_CONFIG = 1 SYN_MT_REPORT = 2 SYN_DROPPED = 3 SYN_MAX = 0xf SYN_CNT = (SYN_MAX+1) -- Keys KEY_RESERVED = 0 KEY_ESC = 1 KEY_1 = 2 KEY_2 = 3 KEY_3 = 4 KEY_4 = 5 KEY_5 = 6 KEY_6 = 7 KEY_7 = 8 KEY_8 = 9 KEY_9 = 10 KEY_0 = 11 KEY_MINUS = 12 KEY_EQUAL = 13 KEY_BACKSPACE = 14 KEY_TAB = 15 KEY_Q = 16 KEY_W = 17 KEY_E = 18 KEY_R = 19 KEY_T = 20 KEY_Y = 21 KEY_U = 22 KEY_I = 23 KEY_O = 24 KEY_P = 25 KEY_LEFTBRACE = 26 KEY_RIGHTBRACE = 27 KEY_ENTER = 28 KEY_LEFTCTRL = 29 KEY_A = 30 KEY_S = 31 KEY_D = 32 KEY_F = 33 KEY_G = 34 KEY_H = 35 KEY_J = 36 KEY_K = 37 KEY_L = 38 KEY_SEMICOLON = 39 KEY_APOSTROPHE = 40 KEY_GRAVE = 41 KEY_LEFTSHIFT = 42 KEY_BACKSLASH = 43 KEY_Z = 44 KEY_X = 45 KEY_C = 46 KEY_V = 47 KEY_B = 48 KEY_N = 49 KEY_M = 50 KEY_COMMA = 51 KEY_DOT = 52 KEY_SLASH = 53 KEY_RIGHTSHIFT = 54 KEY_KPASTERISK = 55 KEY_LEFTALT = 56 KEY_SPACE = 57 KEY_CAPSLOCK = 58 KEY_F1 = 59 KEY_F2 = 60 KEY_F3 = 61 KEY_F4 = 62 KEY_F5 = 63 KEY_F6 = 64 KEY_F7 = 65 KEY_F8 = 66 KEY_F9 = 67 KEY_F10 = 68 KEY_NUMLOCK = 69 KEY_SCROLLLOCK = 70 KEY_KP7 = 71 KEY_KP8 = 72 KEY_KP9 = 73 KEY_KPMINUS = 74 KEY_KP4 = 75 KEY_KP5 = 76 KEY_KP6 = 77 KEY_KPPLUS = 78 KEY_KP1 = 79 KEY_KP2 = 80 KEY_KP3 = 81 KEY_KP0 = 82 KEY_KPDOT = 83 KEY_ZENKAKUHANKAKU = 85 KEY_102ND = 86 KEY_F11 = 87 KEY_F12 = 88 KEY_RO = 89 KEY_KATAKANA = 90 KEY_HIRAGANA = 91 KEY_HENKAN = 92 KEY_KATAKANAHIRAGANA = 93 KEY_MUHENKAN = 94 KEY_KPJPCOMMA = 95 KEY_KPENTER = 96 KEY_RIGHTCTRL = 97 KEY_KPSLASH = 98 KEY_SYSRQ = 99 KEY_RIGHTALT = 100 KEY_LINEFEED = 101 KEY_HOME = 102 KEY_UP = 103 KEY_PAGEUP = 104 KEY_LEFT = 105 KEY_RIGHT = 106 KEY_END = 107 KEY_DOWN = 108 KEY_PAGEDOWN = 109 KEY_INSERT = 110 KEY_DELETE = 111 KEY_MACRO = 112 KEY_MUTE = 113 KEY_VOLUMEDOWN = 114 KEY_VOLUMEUP = 115 KEY_POWER = 116 KEY_KPEQUAL = 117 KEY_KPPLUSMINUS = 118 KEY_PAUSE = 119 KEY_SCALE = 120 KEY_KPCOMMA = 121 KEY_HANGEUL = 122 KEY_HANGUEL = KEY_HANGEUL KEY_HANJA = 123 KEY_YEN = 124 KEY_LEFTMETA = 125 KEY_RIGHTMETA = 126 KEY_COMPOSE = 127 KEY_STOP = 128 KEY_AGAIN = 129 KEY_PROPS = 130 KEY_UNDO = 131 KEY_FRONT = 132 KEY_COPY = 133 KEY_OPEN = 134 KEY_PASTE = 135 KEY_FIND = 136 KEY_CUT = 137 KEY_HELP = 138 KEY_MENU = 139 KEY_CALC = 140 KEY_SETUP = 141 KEY_SLEEP = 142 KEY_WAKEUP = 143 KEY_FILE = 144 KEY_SENDFILE = 145 KEY_DELETEFILE = 146 KEY_XFER = 147 KEY_PROG1 = 148 KEY_PROG2 = 149 KEY_WWW = 150 KEY_MSDOS = 151 KEY_COFFEE = 152 KEY_SCREENLOCK = KEY_COFFEE KEY_ROTATE_DISPLAY = 153 KEY_DIRECTION = KEY_ROTATE_DISPLAY KEY_CYCLEWINDOWS = 154 KEY_MAIL = 155 KEY_BOOKMARKS = 156 KEY_COMPUTER = 157 KEY_BACK = 158 KEY_FORWARD = 159 KEY_CLOSECD = 160 KEY_EJECTCD = 161 KEY_EJECTCLOSECD = 162 KEY_NEXTSONG = 163 KEY_PLAYPAUSE = 164 KEY_PREVIOUSSONG = 165 KEY_STOPCD = 166 KEY_RECORD = 167 KEY_REWIND = 168 KEY_PHONE = 169 KEY_ISO = 170 KEY_CONFIG = 171 KEY_HOMEPAGE = 172 KEY_REFRESH = 173 KEY_EXIT = 174 KEY_MOVE = 175 KEY_EDIT = 176 KEY_SCROLLUP = 177 KEY_SCROLLDOWN = 178 KEY_KPLEFTPAREN = 179 KEY_KPRIGHTPAREN = 180 KEY_NEW = 181 KEY_REDO = 182 KEY_F13 = 183 KEY_F14 = 184 KEY_F15 = 185 KEY_F16 = 186 KEY_F17 = 187 KEY_F18 = 188 KEY_F19 = 189 KEY_F20 = 190 KEY_F21 = 191 KEY_F22 = 192 KEY_F23 = 193 KEY_F24 = 194 KEY_PLAYCD = 200 KEY_PAUSECD = 201 KEY_PROG3 = 202 KEY_PROG4 = 203 KEY_DASHBOARD = 204 KEY_SUSPEND = 205 KEY_CLOSE = 206 KEY_PLAY = 207 KEY_FASTFORWARD = 208 KEY_BASSBOOST = 209 KEY_PRINT = 210 KEY_HP = 211 KEY_CAMERA = 212 KEY_SOUND = 213 KEY_QUESTION = 214 KEY_EMAIL = 215 KEY_CHAT = 216 KEY_SEARCH = 217 KEY_CONNECT = 218 KEY_FINANCE = 219 KEY_SPORT = 220 KEY_SHOP = 221 KEY_ALTERASE = 222 KEY_CANCEL = 223 KEY_BRIGHTNESSDOWN = 224 KEY_BRIGHTNESSUP = 225 KEY_MEDIA = 226 KEY_SWITCHVIDEOMODE = 227 KEY_KBDILLUMTOGGLE = 228 KEY_KBDILLUMDOWN = 229 KEY_KBDILLUMUP = 230 KEY_SEND = 231 KEY_REPLY = 232 KEY_FORWARDMAIL = 233 KEY_SAVE = 234 KEY_DOCUMENTS = 235 KEY_BATTERY = 236 KEY_BLUETOOTH = 237 KEY_WLAN = 238 KEY_UWB = 239 KEY_UNKNOWN = 240 KEY_VIDEO_NEXT = 241 KEY_VIDEO_PREV = 242 KEY_BRIGHTNESS_CYCLE = 243 KEY_BRIGHTNESS_AUTO = 244 KEY_BRIGHTNESS_ZERO = KEY_BRIGHTNESS_AUTO KEY_DISPLAY_OFF = 245 KEY_WWAN = 246 KEY_WIMAX = KEY_WWAN KEY_RFKILL = 247 KEY_MICMUTE = 248 KEY_OK = 0x160 KEY_SELECT = 0x161 KEY_GOTO = 0x162 KEY_CLEAR = 0x163 KEY_POWER2 = 0x164 KEY_OPTION = 0x165 KEY_INFO = 0x166 KEY_TIME = 0x167 KEY_VENDOR = 0x168 KEY_ARCHIVE = 0x169 KEY_PROGRAM = 0x16a KEY_CHANNEL = 0x16b KEY_FAVORITES = 0x16c KEY_EPG = 0x16d KEY_PVR = 0x16e KEY_MHP = 0x16f KEY_LANGUAGE = 0x170 KEY_TITLE = 0x171 KEY_SUBTITLE = 0x172 KEY_ANGLE = 0x173 KEY_ZOOM = 0x174 KEY_MODE = 0x175 KEY_KEYBOARD = 0x176 KEY_SCREEN = 0x177 KEY_PC = 0x178 KEY_TV = 0x179 KEY_TV2 = 0x17a KEY_VCR = 0x17b KEY_VCR2 = 0x17c KEY_SAT = 0x17d KEY_SAT2 = 0x17e KEY_CD = 0x17f KEY_TAPE = 0x180 KEY_RADIO = 0x181 KEY_TUNER = 0x182 KEY_PLAYER = 0x183 KEY_TEXT = 0x184 KEY_DVD = 0x185 KEY_AUX = 0x186 KEY_MP3 = 0x187 KEY_AUDIO = 0x188 KEY_VIDEO = 0x189 KEY_DIRECTORY = 0x18a KEY_LIST = 0x18b KEY_MEMO = 0x18c KEY_CALENDAR = 0x18d KEY_RED = 0x18e KEY_GREEN = 0x18f KEY_YELLOW = 0x190 KEY_BLUE = 0x191 KEY_CHANNELUP = 0x192 KEY_CHANNELDOWN = 0x193 KEY_FIRST = 0x194 KEY_LAST = 0x195 KEY_AB = 0x196 KEY_NEXT = 0x197 KEY_RESTART = 0x198 KEY_SLOW = 0x199 KEY_SHUFFLE = 0x19a KEY_BREAK = 0x19b KEY_PREVIOUS = 0x19c KEY_DIGITS = 0x19d KEY_TEEN = 0x19e KEY_TWEN = 0x19f KEY_VIDEOPHONE = 0x1a0 KEY_GAMES = 0x1a1 KEY_ZOOMIN = 0x1a2 KEY_ZOOMOUT = 0x1a3 KEY_ZOOMRESET = 0x1a4 KEY_WORDPROCESSOR = 0x1a5 KEY_EDITOR = 0x1a6 KEY_SPREADSHEET = 0x1a7 KEY_GRAPHICSEDITOR = 0x1a8 KEY_PRESENTATION = 0x1a9 KEY_DATABASE = 0x1aa KEY_NEWS = 0x1ab KEY_VOICEMAIL = 0x1ac KEY_ADDRESSBOOK = 0x1ad KEY_MESSENGER = 0x1ae KEY_DISPLAYTOGGLE = 0x1af KEY_BRIGHTNESS_TOGGLE = KEY_DISPLAYTOGGLE KEY_SPELLCHECK = 0x1b0 KEY_LOGOFF = 0x1b1 KEY_DOLLAR = 0x1b2 KEY_EURO = 0x1b3 KEY_FRAMEBACK = 0x1b4 KEY_FRAMEFORWARD = 0x1b5 KEY_CONTEXT_MENU = 0x1b6 KEY_MEDIA_REPEAT = 0x1b7 KEY_10CHANNELSUP = 0x1b8 KEY_10CHANNELSDOWN = 0x1b9 KEY_IMAGES = 0x1ba KEY_DEL_EOL = 0x1c0 KEY_DEL_EOS = 0x1c1 KEY_INS_LINE = 0x1c2 KEY_DEL_LINE = 0x1c3 KEY_FN = 0x1d0 KEY_FN_ESC = 0x1d1 KEY_FN_F1 = 0x1d2 KEY_FN_F2 = 0x1d3 KEY_FN_F3 = 0x1d4 KEY_FN_F4 = 0x1d5 KEY_FN_F5 = 0x1d6 KEY_FN_F6 = 0x1d7 KEY_FN_F7 = 0x1d8 KEY_FN_F8 = 0x1d9 KEY_FN_F9 = 0x1da KEY_FN_F10 = 0x1db KEY_FN_F11 = 0x1dc KEY_FN_F12 = 0x1dd KEY_FN_1 = 0x1de KEY_FN_2 = 0x1df KEY_FN_D = 0x1e0 KEY_FN_E = 0x1e1 KEY_FN_F = 0x1e2 KEY_FN_S = 0x1e3 KEY_FN_B = 0x1e4 KEY_BRL_DOT1 = 0x1f1 KEY_BRL_DOT2 = 0x1f2 KEY_BRL_DOT3 = 0x1f3 KEY_BRL_DOT4 = 0x1f4 KEY_BRL_DOT5 = 0x1f5 KEY_BRL_DOT6 = 0x1f6 KEY_BRL_DOT7 = 0x1f7 KEY_BRL_DOT8 = 0x1f8 KEY_BRL_DOT9 = 0x1f9 KEY_BRL_DOT10 = 0x1fa KEY_NUMERIC_0 = 0x200 KEY_NUMERIC_1 = 0x201 KEY_NUMERIC_2 = 0x202 KEY_NUMERIC_3 = 0x203 KEY_NUMERIC_4 = 0x204 KEY_NUMERIC_5 = 0x205 KEY_NUMERIC_6 = 0x206 KEY_NUMERIC_7 = 0x207 KEY_NUMERIC_8 = 0x208 KEY_NUMERIC_9 = 0x209 KEY_NUMERIC_STAR = 0x20a KEY_NUMERIC_POUND = 0x20b KEY_NUMERIC_A = 0x20c KEY_NUMERIC_B = 0x20d KEY_NUMERIC_C = 0x20e KEY_NUMERIC_D = 0x20f KEY_CAMERA_FOCUS = 0x210 KEY_WPS_BUTTON = 0x211 KEY_TOUCHPAD_TOGGLE = 0x212 KEY_TOUCHPAD_ON = 0x213 KEY_TOUCHPAD_OFF = 0x214 KEY_CAMERA_ZOOMIN = 0x215 KEY_CAMERA_ZOOMOUT = 0x216 KEY_CAMERA_UP = 0x217 KEY_CAMERA_DOWN = 0x218 KEY_CAMERA_LEFT = 0x219 KEY_CAMERA_RIGHT = 0x21a KEY_ATTENDANT_ON = 0x21b KEY_ATTENDANT_OFF = 0x21c KEY_ATTENDANT_TOGGLE = 0x21d KEY_LIGHTS_TOGGLE = 0x21e KEY_ALS_TOGGLE = 0x230 KEY_BUTTONCONFIG = 0x240 KEY_TASKMANAGER = 0x241 KEY_JOURNAL = 0x242 KEY_CONTROLPANEL = 0x243 KEY_APPSELECT = 0x244 KEY_SCREENSAVER = 0x245 KEY_VOICECOMMAND = 0x246 KEY_BRIGHTNESS_MIN = 0x250 KEY_BRIGHTNESS_MAX = 0x251 KEY_KBDINPUTASSIST_PREV = 0x260 KEY_KBDINPUTASSIST_NEXT = 0x261 KEY_KBDINPUTASSIST_PREVGROUP = 0x262 KEY_KBDINPUTASSIST_NEXTGROUP = 0x263 KEY_KBDINPUTASSIST_ACCEPT = 0x264 KEY_KBDINPUTASSIST_CANCEL = 0x265 KEY_MIN_INTERESTING = KEY_MUTE KEY_MAX = 0x2ff KEY_CNT = (KEY_MAX+1) -- Buttons BTN_MISC = 0x100 BTN_0 = 0x100 BTN_1 = 0x101 BTN_2 = 0x102 BTN_3 = 0x103 BTN_4 = 0x104 BTN_5 = 0x105 BTN_6 = 0x106 BTN_7 = 0x107 BTN_8 = 0x108 BTN_9 = 0x109 BTN_MOUSE = 0x110 BTN_LEFT = 0x110 BTN_RIGHT = 0x111 BTN_MIDDLE = 0x112 BTN_SIDE = 0x113 BTN_EXTRA = 0x114 BTN_FORWARD = 0x115 BTN_BACK = 0x116 BTN_TASK = 0x117 BTN_JOYSTICK = 0x120 BTN_TRIGGER = 0x120 BTN_THUMB = 0x121 BTN_THUMB2 = 0x122 BTN_TOP = 0x123 BTN_TOP2 = 0x124 BTN_PINKIE = 0x125 BTN_BASE = 0x126 BTN_BASE2 = 0x127 BTN_BASE3 = 0x128 BTN_BASE4 = 0x129 BTN_BASE5 = 0x12a BTN_BASE6 = 0x12b BTN_DEAD = 0x12f BTN_GAMEPAD = 0x130 BTN_SOUTH = 0x130 BTN_A = BTN_SOUTH BTN_EAST = 0x131 BTN_B = BTN_EAST BTN_C = 0x132 BTN_NORTH = 0x133 BTN_X = BTN_NORTH BTN_WEST = 0x134 BTN_Y = BTN_WEST BTN_Z = 0x135 BTN_TL = 0x136 BTN_TR = 0x137 BTN_TL2 = 0x138 BTN_TR2 = 0x139 BTN_SELECT = 0x13a BTN_START = 0x13b BTN_MODE = 0x13c BTN_THUMBL = 0x13d BTN_THUMBR = 0x13e BTN_DIGI = 0x140 BTN_TOOL_PEN = 0x140 BTN_TOOL_RUBBER = 0x141 BTN_TOOL_BRUSH = 0x142 BTN_TOOL_PENCIL = 0x143 BTN_TOOL_AIRBRUSH = 0x144 BTN_TOOL_FINGER = 0x145 BTN_TOOL_MOUSE = 0x146 BTN_TOOL_LENS = 0x147 BTN_TOOL_QUINTTAP = 0x148 BTN_TOUCH = 0x14a BTN_STYLUS = 0x14b BTN_STYLUS2 = 0x14c BTN_TOOL_DOUBLETAP = 0x14d BTN_TOOL_TRIPLETAP = 0x14e BTN_TOOL_QUADTAP = 0x14f BTN_WHEEL = 0x150 BTN_GEAR_DOWN = 0x150 BTN_GEAR_UP = 0x151 BTN_DPAD_UP = 0x220 BTN_DPAD_DOWN = 0x221 BTN_DPAD_LEFT = 0x222 BTN_DPAD_RIGHT = 0x223 BTN_TRIGGER_HAPPY = 0x2c0 BTN_TRIGGER_HAPPY1 = 0x2c0 BTN_TRIGGER_HAPPY2 = 0x2c1 BTN_TRIGGER_HAPPY3 = 0x2c2 BTN_TRIGGER_HAPPY4 = 0x2c3 BTN_TRIGGER_HAPPY5 = 0x2c4 BTN_TRIGGER_HAPPY6 = 0x2c5 BTN_TRIGGER_HAPPY7 = 0x2c6 BTN_TRIGGER_HAPPY8 = 0x2c7 BTN_TRIGGER_HAPPY9 = 0x2c8 BTN_TRIGGER_HAPPY10 = 0x2c9 BTN_TRIGGER_HAPPY11 = 0x2ca BTN_TRIGGER_HAPPY12 = 0x2cb BTN_TRIGGER_HAPPY13 = 0x2cc BTN_TRIGGER_HAPPY14 = 0x2cd BTN_TRIGGER_HAPPY15 = 0x2ce BTN_TRIGGER_HAPPY16 = 0x2cf BTN_TRIGGER_HAPPY17 = 0x2d0 BTN_TRIGGER_HAPPY18 = 0x2d1 BTN_TRIGGER_HAPPY19 = 0x2d2 BTN_TRIGGER_HAPPY20 = 0x2d3 BTN_TRIGGER_HAPPY21 = 0x2d4 BTN_TRIGGER_HAPPY22 = 0x2d5 BTN_TRIGGER_HAPPY23 = 0x2d6 BTN_TRIGGER_HAPPY24 = 0x2d7 BTN_TRIGGER_HAPPY25 = 0x2d8 BTN_TRIGGER_HAPPY26 = 0x2d9 BTN_TRIGGER_HAPPY27 = 0x2da BTN_TRIGGER_HAPPY28 = 0x2db BTN_TRIGGER_HAPPY29 = 0x2dc BTN_TRIGGER_HAPPY30 = 0x2dd BTN_TRIGGER_HAPPY31 = 0x2de BTN_TRIGGER_HAPPY32 = 0x2df BTN_TRIGGER_HAPPY33 = 0x2e0 BTN_TRIGGER_HAPPY34 = 0x2e1 BTN_TRIGGER_HAPPY35 = 0x2e2 BTN_TRIGGER_HAPPY36 = 0x2e3 BTN_TRIGGER_HAPPY37 = 0x2e4 BTN_TRIGGER_HAPPY38 = 0x2e5 BTN_TRIGGER_HAPPY39 = 0x2e6 BTN_TRIGGER_HAPPY40 = 0x2e7 -- Relative Axes REL_X = 0x00 REL_Y = 0x01 REL_Z = 0x02 REL_RX = 0x03 REL_RY = 0x04 REL_RZ = 0x05 REL_HWHEEL = 0x06 REL_DIAL = 0x07 REL_WHEEL = 0x08 REL_MISC = 0x09 REL_MAX = 0x0f REL_CNT = (REL_MAX+1) -- Absolute Axes ABS_X = 0x00 ABS_Y = 0x01 ABS_Z = 0x02 ABS_RX = 0x03 ABS_RY = 0x04 ABS_RZ = 0x05 ABS_THROTTLE = 0x06 ABS_RUDDER = 0x07 ABS_WHEEL = 0x08 ABS_GAS = 0x09 ABS_BRAKE = 0x0a ABS_HAT0X = 0x10 ABS_HAT0Y = 0x11 ABS_HAT1X = 0x12 ABS_HAT1Y = 0x13 ABS_HAT2X = 0x14 ABS_HAT2Y = 0x15 ABS_HAT3X = 0x16 ABS_HAT3Y = 0x17 ABS_PRESSURE = 0x18 ABS_DISTANCE = 0x19 ABS_TILT_X = 0x1a ABS_TILT_Y = 0x1b ABS_TOOL_WIDTH = 0x1c ABS_VOLUME = 0x20 ABS_MISC = 0x28 ABS_MT_SLOT = 0x2f ABS_MT_TOUCH_MAJOR = 0x30 ABS_MT_TOUCH_MINOR = 0x31 ABS_MT_WIDTH_MAJOR = 0x32 ABS_MT_WIDTH_MINOR = 0x33 ABS_MT_ORIENTATION = 0x34 ABS_MT_POSITION_X = 0x35 ABS_MT_POSITION_Y = 0x36 ABS_MT_TOOL_TYPE = 0x37 ABS_MT_BLOB_ID = 0x38 ABS_MT_TRACKING_ID = 0x39 ABS_MT_PRESSURE = 0x3a ABS_MT_DISTANCE = 0x3b ABS_MT_TOOL_X = 0x3c ABS_MT_TOOL_Y = 0x3d ABS_MAX = 0x3f ABS_CNT = (ABS_MAX+1) -- LEDs LED_NUML = 0x00 LED_CAPSL = 0x01 LED_SCROLLL = 0x02 LED_COMPOSE = 0x03 LED_KANA = 0x04 LED_SLEEP = 0x05 LED_SUSPEND = 0x06 LED_MUTE = 0x07 LED_MISC = 0x08 LED_MAIL = 0x09 LED_CHARGING = 0x0a LED_MAX = 0x0f LED_CNT = (LED_MAX+1) return _ENV
mit
DavidIngraham/ardupilot
libraries/AP_Scripting/examples/param_add.lua
8
1300
-- example for adding parameters to a lua script -- the table key must be used by only one script on a particular flight -- controller. If you want to re-use it then you need to wipe your old parameters -- the key must be a number between 0 and 200. The key is persistent in storage local PARAM_TABLE_KEY = 72 -- create a parameter table with 2 parameters in it. A table can have -- at most 63 parameters. The table size for a particular table key -- cannot increase without a reboot. The prefix "MY_" is used with -- every parameter in the table. This prefix is used to ensure another -- script doesn't use the same PARAM_TABLE_KEY. assert(param:add_table(PARAM_TABLE_KEY, "MY_", 2), 'could not add param table') -- create two parameters. The param indexes (2nd argument) must -- be between 1 and 63. All added parameters are floats, with the given -- default value (4th argument). assert(param:add_param(PARAM_TABLE_KEY, 1, 'TEST', 3.14), 'could not add param1') assert(param:add_param(PARAM_TABLE_KEY, 2, 'TEST2', 5.7), 'could not add param2') gcs:send_text(0, string.format("Added two parameters")) local param1 = Parameter("MY_TEST") local param2 = Parameter("MY_TEST2") gcs:send_text(0, string.format("param1=%f", param1:get())) gcs:send_text(0, string.format("param2=%f", param2:get()))
gpl-3.0
link4all/20170920openwrt
own_files/ar934x/files_zhonglian/usr/lib/lua/luci/sys.lua
21
15277
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local io = require "io" local os = require "os" local table = require "table" local nixio = require "nixio" local fs = require "nixio.fs" local uci = require "luci.model.uci" local luci = {} luci.util = require "luci.util" luci.ip = require "luci.ip" local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select = tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select module "luci.sys" function call(...) return os.execute(...) / 256 end exec = luci.util.exec function mounts() local data = {} local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"} local ps = luci.util.execi("df") if not ps then return else ps() end for line in ps do local row = {} local j = 1 for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end if row[k[1]] then -- this is a rather ugly workaround to cope with wrapped lines in -- the df output: -- -- /dev/scsi/host0/bus0/target0/lun0/part3 -- 114382024 93566472 15005244 86% /mnt/usb -- if not row[k[2]] then j = 2 line = ps() for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end end table.insert(data, row) end end return data end -- containing the whole environment is returned otherwise this function returns -- the corresponding string value for the given name or nil if no such variable -- exists. getenv = nixio.getenv function hostname(newname) if type(newname) == "string" and #newname > 0 then fs.writefile( "/proc/sys/kernel/hostname", newname ) return newname else return nixio.uname().nodename end end function httpget(url, stream, target) if not target then local source = stream and io.popen or luci.util.exec return source("wget -qO- '"..url:gsub("'", "").."'") else return os.execute("wget -qO '%s' '%s'" % {target:gsub("'", ""), url:gsub("'", "")}) end end function loadavg() local info = nixio.sysinfo() return info.loads[1], info.loads[2], info.loads[3] end function reboot() return os.execute("reboot >/dev/null 2>&1") end function syslog() return luci.util.exec("logread") end function dmesg() return luci.util.exec("dmesg") end function uniqueid(bytes) local rand = fs.readfile("/dev/urandom", bytes) return rand and nixio.bin.hexlify(rand) end function uptime() return nixio.sysinfo().uptime end net = {} -- The following fields are defined for arp entry objects: -- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" } function net.arptable(callback) local arp = (not callback) and {} or nil local e, r, v if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do local r = { }, v for v in e:gmatch("%S+") do r[#r+1] = v end if r[1] ~= "IP" then local x = { ["IP address"] = r[1], ["HW type"] = r[2], ["Flags"] = r[3], ["HW address"] = r[4], ["Mask"] = r[5], ["Device"] = r[6] } if callback then callback(x) else arp = arp or { } arp[#arp+1] = x end end end end return arp end local function _nethints(what, callback) local _, k, e, mac, ip, name local cur = uci.cursor() local ifn = { } local hosts = { } local function _add(i, ...) local k = select(i, ...) if k then if not hosts[k] then hosts[k] = { } end hosts[k][1] = select(1, ...) or hosts[k][1] hosts[k][2] = select(2, ...) or hosts[k][2] hosts[k][3] = select(3, ...) or hosts[k][3] hosts[k][4] = select(4, ...) or hosts[k][4] end end if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+") if ip and mac then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/etc/ethers") then for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/var/dhcp.leases") then for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, name ~= "*" and name) end end end cur:foreach("dhcp", "host", function(s) for mac in luci.util.imatch(s.mac) do _add(what, mac:upper(), s.ip, nil, s.name) end end) for _, e in ipairs(nixio.getifaddrs()) do if e.name ~= "lo" then ifn[e.name] = ifn[e.name] or { } if e.family == "packet" and e.addr and #e.addr == 17 then ifn[e.name][1] = e.addr:upper() elseif e.family == "inet" then ifn[e.name][2] = e.addr elseif e.family == "inet6" then ifn[e.name][3] = e.addr end end end for _, e in pairs(ifn) do if e[what] and (e[2] or e[3]) then _add(what, e[1], e[2], e[3], e[4]) end end for _, e in luci.util.kspairs(hosts) do callback(e[1], e[2], e[3], e[4]) end end -- Each entry contains the values in the following order: -- [ "mac", "name" ] function net.mac_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv4_hints(callback) if callback then _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then callback(v4, name) end end) else local rv = { } _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then rv[#rv+1] = { v4, name } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv6_hints(callback) if callback then _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then callback(v6, name) end end) else local rv = { } _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then rv[#rv+1] = { v6, name } end end) return rv end end function net.conntrack(callback) local connt = {} if fs.access("/proc/net/nf_conntrack", "r") then for line in io.lines("/proc/net/nf_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[6] ~= "TIME_WAIT" then entry.layer3 = flags[1] entry.layer4 = flags[3] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end elseif fs.access("/proc/net/ip_conntrack", "r") then for line in io.lines("/proc/net/ip_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[4] ~= "TIME_WAIT" then entry.layer3 = "ipv4" entry.layer4 = flags[1] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end else return nil end return connt end function net.devices() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then devs[#devs+1] = v.name end end return devs end function net.deviceinfo() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then local d = v.data d[1] = d.rx_bytes d[2] = d.rx_packets d[3] = d.rx_errors d[4] = d.rx_dropped d[5] = 0 d[6] = 0 d[7] = 0 d[8] = d.multicast d[9] = d.tx_bytes d[10] = d.tx_packets d[11] = d.tx_errors d[12] = d.tx_dropped d[13] = 0 d[14] = d.collisions d[15] = 0 d[16] = 0 devs[v.name] = d end end return devs end -- The following fields are defined for route entry tables: -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt", -- "flags", "device" } function net.routes(callback) local routes = { } for line in io.lines("/proc/net/route") do local dev, dst_ip, gateway, flags, refcnt, usecnt, metric, dst_mask, mtu, win, irtt = line:match( "([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" .. "(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)" ) if dev then gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 ) dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 ) dst_ip = luci.ip.Hex( dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4 ) local rt = { dest = dst_ip, gateway = gateway, metric = tonumber(metric), refcount = tonumber(refcnt), usecount = tonumber(usecnt), mtu = tonumber(mtu), window = tonumber(window), irtt = tonumber(irtt), flags = tonumber(flags, 16), device = dev } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end -- The following fields are defined for route entry tables: -- { "source", "dest", "nexthop", "metric", "refcount", "usecount", -- "flags", "device" } function net.routes6(callback) if fs.access("/proc/net/ipv6_route", "r") then local routes = { } for line in io.lines("/proc/net/ipv6_route") do local dst_ip, dst_prefix, src_ip, src_prefix, nexthop, metric, refcnt, usecnt, flags, dev = line:match( "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) +([^%s]+)" ) if dst_ip and dst_prefix and src_ip and src_prefix and nexthop and metric and refcnt and usecnt and flags and dev then src_ip = luci.ip.Hex( src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false ) dst_ip = luci.ip.Hex( dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false ) nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false ) local rt = { source = src_ip, dest = dst_ip, nexthop = nexthop, metric = tonumber(metric, 16), refcount = tonumber(refcnt, 16), usecount = tonumber(usecnt, 16), flags = tonumber(flags, 16), device = dev, -- lua number is too small for storing the metric -- add a metric_raw field with the original content metric_raw = metric } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end end function net.pingtest(host) return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1") end process = {} function process.info(key) local s = {uid = nixio.getuid(), gid = nixio.getgid()} return not key and s or s[key] end function process.list() local data = {} local k local ps = luci.util.execi("/bin/busybox top -bn1") if not ps then return end for line in ps do local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match( "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)" ) local idx = tonumber(pid) if idx then data[idx] = { ['PID'] = pid, ['PPID'] = ppid, ['USER'] = user, ['STAT'] = stat, ['VSZ'] = vsz, ['%MEM'] = mem, ['%CPU'] = cpu, ['COMMAND'] = cmd } end end return data end function process.setgroup(gid) return nixio.setgid(gid) end function process.setuser(uid) return nixio.setuid(uid) end process.signal = nixio.kill user = {} -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" } user.getuser = nixio.getpw function user.getpasswd(username) local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username) local pwh = pwe and (pwe.pwdp or pwe.passwd) if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then return nil, pwe else return pwh, pwe end end function user.checkpasswd(username, pass) local pwh, pwe = user.getpasswd(username) if pwe then return (pwh == nil or nixio.crypt(pass, pwh) == pwh) end return false end function user.setpasswd(username, password) if password then password = password:gsub("'", [['"'"']]) end if username then username = username:gsub("'", [['"'"']]) end return os.execute( "(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " .. "passwd '" .. username .. "' >/dev/null 2>&1" ) end wifi = {} function wifi.getiwinfo(ifname) local stat, iwinfo = pcall(require, "iwinfo") if ifname then local c = 0 local u = uci.cursor_state() local d, n = ifname:match("^(%w+)%.network(%d+)") if d and n then ifname = d n = tonumber(n) u:foreach("wireless", "wifi-iface", function(s) if s.device == d then c = c + 1 if c == n then ifname = s.ifname or s.device return false end end end) elseif u:get("wireless", ifname) == "wifi-device" then u:foreach("wireless", "wifi-iface", function(s) if s.device == ifname and s.ifname then ifname = s.ifname return false end end) end local t = stat and iwinfo.type(ifname) local x = t and iwinfo[t] or { } return setmetatable({}, { __index = function(t, k) if k == "ifname" then return ifname elseif x[k] then return x[k](ifname) end end }) end end init = {} init.dir = "/etc/init.d/" function init.names() local names = { } for name in fs.glob(init.dir.."*") do names[#names+1] = fs.basename(name) end return names end function init.index(name) if fs.access(init.dir..name) then return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null" %{ init.dir, name }) end end local function init_action(action, name) if fs.access(init.dir..name) then return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action }) end end function init.enabled(name) return (init_action("enabled", name) == 0) end function init.enable(name) return (init_action("enable", name) == 1) end function init.disable(name) return (init_action("disable", name) == 0) end function init.start(name) return (init_action("start", name) == 0) end function init.stop(name) return (init_action("stop", name) == 0) end -- Internal functions function _parse_mixed_record(cnt, delimiter) delimiter = delimiter or " " local data = {} local flags = {} for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*') if k then if x == "" then table.insert(flags, k) else data[k] = v end end end end return data, flags end
gpl-2.0
link4all/20170920openwrt
own_files/mt7628/files_wfnt_4g/usr/lib/lua/luci/sys.lua
21
15277
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local io = require "io" local os = require "os" local table = require "table" local nixio = require "nixio" local fs = require "nixio.fs" local uci = require "luci.model.uci" local luci = {} luci.util = require "luci.util" luci.ip = require "luci.ip" local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select = tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select module "luci.sys" function call(...) return os.execute(...) / 256 end exec = luci.util.exec function mounts() local data = {} local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"} local ps = luci.util.execi("df") if not ps then return else ps() end for line in ps do local row = {} local j = 1 for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end if row[k[1]] then -- this is a rather ugly workaround to cope with wrapped lines in -- the df output: -- -- /dev/scsi/host0/bus0/target0/lun0/part3 -- 114382024 93566472 15005244 86% /mnt/usb -- if not row[k[2]] then j = 2 line = ps() for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end end table.insert(data, row) end end return data end -- containing the whole environment is returned otherwise this function returns -- the corresponding string value for the given name or nil if no such variable -- exists. getenv = nixio.getenv function hostname(newname) if type(newname) == "string" and #newname > 0 then fs.writefile( "/proc/sys/kernel/hostname", newname ) return newname else return nixio.uname().nodename end end function httpget(url, stream, target) if not target then local source = stream and io.popen or luci.util.exec return source("wget -qO- '"..url:gsub("'", "").."'") else return os.execute("wget -qO '%s' '%s'" % {target:gsub("'", ""), url:gsub("'", "")}) end end function loadavg() local info = nixio.sysinfo() return info.loads[1], info.loads[2], info.loads[3] end function reboot() return os.execute("reboot >/dev/null 2>&1") end function syslog() return luci.util.exec("logread") end function dmesg() return luci.util.exec("dmesg") end function uniqueid(bytes) local rand = fs.readfile("/dev/urandom", bytes) return rand and nixio.bin.hexlify(rand) end function uptime() return nixio.sysinfo().uptime end net = {} -- The following fields are defined for arp entry objects: -- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" } function net.arptable(callback) local arp = (not callback) and {} or nil local e, r, v if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do local r = { }, v for v in e:gmatch("%S+") do r[#r+1] = v end if r[1] ~= "IP" then local x = { ["IP address"] = r[1], ["HW type"] = r[2], ["Flags"] = r[3], ["HW address"] = r[4], ["Mask"] = r[5], ["Device"] = r[6] } if callback then callback(x) else arp = arp or { } arp[#arp+1] = x end end end end return arp end local function _nethints(what, callback) local _, k, e, mac, ip, name local cur = uci.cursor() local ifn = { } local hosts = { } local function _add(i, ...) local k = select(i, ...) if k then if not hosts[k] then hosts[k] = { } end hosts[k][1] = select(1, ...) or hosts[k][1] hosts[k][2] = select(2, ...) or hosts[k][2] hosts[k][3] = select(3, ...) or hosts[k][3] hosts[k][4] = select(4, ...) or hosts[k][4] end end if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+") if ip and mac then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/etc/ethers") then for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/var/dhcp.leases") then for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, name ~= "*" and name) end end end cur:foreach("dhcp", "host", function(s) for mac in luci.util.imatch(s.mac) do _add(what, mac:upper(), s.ip, nil, s.name) end end) for _, e in ipairs(nixio.getifaddrs()) do if e.name ~= "lo" then ifn[e.name] = ifn[e.name] or { } if e.family == "packet" and e.addr and #e.addr == 17 then ifn[e.name][1] = e.addr:upper() elseif e.family == "inet" then ifn[e.name][2] = e.addr elseif e.family == "inet6" then ifn[e.name][3] = e.addr end end end for _, e in pairs(ifn) do if e[what] and (e[2] or e[3]) then _add(what, e[1], e[2], e[3], e[4]) end end for _, e in luci.util.kspairs(hosts) do callback(e[1], e[2], e[3], e[4]) end end -- Each entry contains the values in the following order: -- [ "mac", "name" ] function net.mac_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv4_hints(callback) if callback then _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then callback(v4, name) end end) else local rv = { } _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then rv[#rv+1] = { v4, name } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv6_hints(callback) if callback then _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then callback(v6, name) end end) else local rv = { } _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then rv[#rv+1] = { v6, name } end end) return rv end end function net.conntrack(callback) local connt = {} if fs.access("/proc/net/nf_conntrack", "r") then for line in io.lines("/proc/net/nf_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[6] ~= "TIME_WAIT" then entry.layer3 = flags[1] entry.layer4 = flags[3] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end elseif fs.access("/proc/net/ip_conntrack", "r") then for line in io.lines("/proc/net/ip_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[4] ~= "TIME_WAIT" then entry.layer3 = "ipv4" entry.layer4 = flags[1] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end else return nil end return connt end function net.devices() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then devs[#devs+1] = v.name end end return devs end function net.deviceinfo() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then local d = v.data d[1] = d.rx_bytes d[2] = d.rx_packets d[3] = d.rx_errors d[4] = d.rx_dropped d[5] = 0 d[6] = 0 d[7] = 0 d[8] = d.multicast d[9] = d.tx_bytes d[10] = d.tx_packets d[11] = d.tx_errors d[12] = d.tx_dropped d[13] = 0 d[14] = d.collisions d[15] = 0 d[16] = 0 devs[v.name] = d end end return devs end -- The following fields are defined for route entry tables: -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt", -- "flags", "device" } function net.routes(callback) local routes = { } for line in io.lines("/proc/net/route") do local dev, dst_ip, gateway, flags, refcnt, usecnt, metric, dst_mask, mtu, win, irtt = line:match( "([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" .. "(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)" ) if dev then gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 ) dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 ) dst_ip = luci.ip.Hex( dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4 ) local rt = { dest = dst_ip, gateway = gateway, metric = tonumber(metric), refcount = tonumber(refcnt), usecount = tonumber(usecnt), mtu = tonumber(mtu), window = tonumber(window), irtt = tonumber(irtt), flags = tonumber(flags, 16), device = dev } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end -- The following fields are defined for route entry tables: -- { "source", "dest", "nexthop", "metric", "refcount", "usecount", -- "flags", "device" } function net.routes6(callback) if fs.access("/proc/net/ipv6_route", "r") then local routes = { } for line in io.lines("/proc/net/ipv6_route") do local dst_ip, dst_prefix, src_ip, src_prefix, nexthop, metric, refcnt, usecnt, flags, dev = line:match( "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) +([^%s]+)" ) if dst_ip and dst_prefix and src_ip and src_prefix and nexthop and metric and refcnt and usecnt and flags and dev then src_ip = luci.ip.Hex( src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false ) dst_ip = luci.ip.Hex( dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false ) nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false ) local rt = { source = src_ip, dest = dst_ip, nexthop = nexthop, metric = tonumber(metric, 16), refcount = tonumber(refcnt, 16), usecount = tonumber(usecnt, 16), flags = tonumber(flags, 16), device = dev, -- lua number is too small for storing the metric -- add a metric_raw field with the original content metric_raw = metric } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end end function net.pingtest(host) return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1") end process = {} function process.info(key) local s = {uid = nixio.getuid(), gid = nixio.getgid()} return not key and s or s[key] end function process.list() local data = {} local k local ps = luci.util.execi("/bin/busybox top -bn1") if not ps then return end for line in ps do local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match( "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)" ) local idx = tonumber(pid) if idx then data[idx] = { ['PID'] = pid, ['PPID'] = ppid, ['USER'] = user, ['STAT'] = stat, ['VSZ'] = vsz, ['%MEM'] = mem, ['%CPU'] = cpu, ['COMMAND'] = cmd } end end return data end function process.setgroup(gid) return nixio.setgid(gid) end function process.setuser(uid) return nixio.setuid(uid) end process.signal = nixio.kill user = {} -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" } user.getuser = nixio.getpw function user.getpasswd(username) local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username) local pwh = pwe and (pwe.pwdp or pwe.passwd) if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then return nil, pwe else return pwh, pwe end end function user.checkpasswd(username, pass) local pwh, pwe = user.getpasswd(username) if pwe then return (pwh == nil or nixio.crypt(pass, pwh) == pwh) end return false end function user.setpasswd(username, password) if password then password = password:gsub("'", [['"'"']]) end if username then username = username:gsub("'", [['"'"']]) end return os.execute( "(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " .. "passwd '" .. username .. "' >/dev/null 2>&1" ) end wifi = {} function wifi.getiwinfo(ifname) local stat, iwinfo = pcall(require, "iwinfo") if ifname then local c = 0 local u = uci.cursor_state() local d, n = ifname:match("^(%w+)%.network(%d+)") if d and n then ifname = d n = tonumber(n) u:foreach("wireless", "wifi-iface", function(s) if s.device == d then c = c + 1 if c == n then ifname = s.ifname or s.device return false end end end) elseif u:get("wireless", ifname) == "wifi-device" then u:foreach("wireless", "wifi-iface", function(s) if s.device == ifname and s.ifname then ifname = s.ifname return false end end) end local t = stat and iwinfo.type(ifname) local x = t and iwinfo[t] or { } return setmetatable({}, { __index = function(t, k) if k == "ifname" then return ifname elseif x[k] then return x[k](ifname) end end }) end end init = {} init.dir = "/etc/init.d/" function init.names() local names = { } for name in fs.glob(init.dir.."*") do names[#names+1] = fs.basename(name) end return names end function init.index(name) if fs.access(init.dir..name) then return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null" %{ init.dir, name }) end end local function init_action(action, name) if fs.access(init.dir..name) then return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action }) end end function init.enabled(name) return (init_action("enabled", name) == 0) end function init.enable(name) return (init_action("enable", name) == 1) end function init.disable(name) return (init_action("disable", name) == 0) end function init.start(name) return (init_action("start", name) == 0) end function init.stop(name) return (init_action("stop", name) == 0) end -- Internal functions function _parse_mixed_record(cnt, delimiter) delimiter = delimiter or " " local data = {} local flags = {} for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*') if k then if x == "" then table.insert(flags, k) else data[k] = v end end end end return data, flags end
gpl-2.0
link4all/20170920openwrt
own_files/ar934x/files_yn9341_zhongxing/usr/lib/lua/luci/sys.lua
21
15277
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local io = require "io" local os = require "os" local table = require "table" local nixio = require "nixio" local fs = require "nixio.fs" local uci = require "luci.model.uci" local luci = {} luci.util = require "luci.util" luci.ip = require "luci.ip" local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select = tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select module "luci.sys" function call(...) return os.execute(...) / 256 end exec = luci.util.exec function mounts() local data = {} local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"} local ps = luci.util.execi("df") if not ps then return else ps() end for line in ps do local row = {} local j = 1 for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end if row[k[1]] then -- this is a rather ugly workaround to cope with wrapped lines in -- the df output: -- -- /dev/scsi/host0/bus0/target0/lun0/part3 -- 114382024 93566472 15005244 86% /mnt/usb -- if not row[k[2]] then j = 2 line = ps() for value in line:gmatch("[^%s]+") do row[k[j]] = value j = j + 1 end end table.insert(data, row) end end return data end -- containing the whole environment is returned otherwise this function returns -- the corresponding string value for the given name or nil if no such variable -- exists. getenv = nixio.getenv function hostname(newname) if type(newname) == "string" and #newname > 0 then fs.writefile( "/proc/sys/kernel/hostname", newname ) return newname else return nixio.uname().nodename end end function httpget(url, stream, target) if not target then local source = stream and io.popen or luci.util.exec return source("wget -qO- '"..url:gsub("'", "").."'") else return os.execute("wget -qO '%s' '%s'" % {target:gsub("'", ""), url:gsub("'", "")}) end end function loadavg() local info = nixio.sysinfo() return info.loads[1], info.loads[2], info.loads[3] end function reboot() return os.execute("reboot >/dev/null 2>&1") end function syslog() return luci.util.exec("logread") end function dmesg() return luci.util.exec("dmesg") end function uniqueid(bytes) local rand = fs.readfile("/dev/urandom", bytes) return rand and nixio.bin.hexlify(rand) end function uptime() return nixio.sysinfo().uptime end net = {} -- The following fields are defined for arp entry objects: -- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" } function net.arptable(callback) local arp = (not callback) and {} or nil local e, r, v if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do local r = { }, v for v in e:gmatch("%S+") do r[#r+1] = v end if r[1] ~= "IP" then local x = { ["IP address"] = r[1], ["HW type"] = r[2], ["Flags"] = r[3], ["HW address"] = r[4], ["Mask"] = r[5], ["Device"] = r[6] } if callback then callback(x) else arp = arp or { } arp[#arp+1] = x end end end end return arp end local function _nethints(what, callback) local _, k, e, mac, ip, name local cur = uci.cursor() local ifn = { } local hosts = { } local function _add(i, ...) local k = select(i, ...) if k then if not hosts[k] then hosts[k] = { } end hosts[k][1] = select(1, ...) or hosts[k][1] hosts[k][2] = select(2, ...) or hosts[k][2] hosts[k][3] = select(3, ...) or hosts[k][3] hosts[k][4] = select(4, ...) or hosts[k][4] end end if fs.access("/proc/net/arp") then for e in io.lines("/proc/net/arp") do ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+") if ip and mac then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/etc/ethers") then for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, nil) end end end if fs.access("/var/dhcp.leases") then for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then _add(what, mac:upper(), ip, nil, name ~= "*" and name) end end end cur:foreach("dhcp", "host", function(s) for mac in luci.util.imatch(s.mac) do _add(what, mac:upper(), s.ip, nil, s.name) end end) for _, e in ipairs(nixio.getifaddrs()) do if e.name ~= "lo" then ifn[e.name] = ifn[e.name] or { } if e.family == "packet" and e.addr and #e.addr == 17 then ifn[e.name][1] = e.addr:upper() elseif e.family == "inet" then ifn[e.name][2] = e.addr elseif e.family == "inet6" then ifn[e.name][3] = e.addr end end end for _, e in pairs(ifn) do if e[what] and (e[2] or e[3]) then _add(what, e[1], e[2], e[3], e[4]) end end for _, e in luci.util.kspairs(hosts) do callback(e[1], e[2], e[3], e[4]) end end -- Each entry contains the values in the following order: -- [ "mac", "name" ] function net.mac_hints(callback) if callback then _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4) end end) else local rv = { } _nethints(1, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 if name and name ~= mac then rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv4_hints(callback) if callback then _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then callback(v4, name) end end) else local rv = { } _nethints(2, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v4, nil, 100) or mac if name and name ~= v4 then rv[#rv+1] = { v4, name } end end) return rv end end -- Each entry contains the values in the following order: -- [ "ip", "name" ] function net.ipv6_hints(callback) if callback then _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then callback(v6, name) end end) else local rv = { } _nethints(3, function(mac, v4, v6, name) name = name or nixio.getnameinfo(v6, nil, 100) or mac if name and name ~= v6 then rv[#rv+1] = { v6, name } end end) return rv end end function net.conntrack(callback) local connt = {} if fs.access("/proc/net/nf_conntrack", "r") then for line in io.lines("/proc/net/nf_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[6] ~= "TIME_WAIT" then entry.layer3 = flags[1] entry.layer4 = flags[3] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end elseif fs.access("/proc/net/ip_conntrack", "r") then for line in io.lines("/proc/net/ip_conntrack") do line = line:match "^(.-( [^ =]+=).-)%2" local entry, flags = _parse_mixed_record(line, " +") if flags[4] ~= "TIME_WAIT" then entry.layer3 = "ipv4" entry.layer4 = flags[1] for i=1, #entry do entry[i] = nil end if callback then callback(entry) else connt[#connt+1] = entry end end end else return nil end return connt end function net.devices() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then devs[#devs+1] = v.name end end return devs end function net.deviceinfo() local devs = {} for k, v in ipairs(nixio.getifaddrs()) do if v.family == "packet" then local d = v.data d[1] = d.rx_bytes d[2] = d.rx_packets d[3] = d.rx_errors d[4] = d.rx_dropped d[5] = 0 d[6] = 0 d[7] = 0 d[8] = d.multicast d[9] = d.tx_bytes d[10] = d.tx_packets d[11] = d.tx_errors d[12] = d.tx_dropped d[13] = 0 d[14] = d.collisions d[15] = 0 d[16] = 0 devs[v.name] = d end end return devs end -- The following fields are defined for route entry tables: -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt", -- "flags", "device" } function net.routes(callback) local routes = { } for line in io.lines("/proc/net/route") do local dev, dst_ip, gateway, flags, refcnt, usecnt, metric, dst_mask, mtu, win, irtt = line:match( "([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" .. "(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)" ) if dev then gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 ) dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 ) dst_ip = luci.ip.Hex( dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4 ) local rt = { dest = dst_ip, gateway = gateway, metric = tonumber(metric), refcount = tonumber(refcnt), usecount = tonumber(usecnt), mtu = tonumber(mtu), window = tonumber(window), irtt = tonumber(irtt), flags = tonumber(flags, 16), device = dev } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end -- The following fields are defined for route entry tables: -- { "source", "dest", "nexthop", "metric", "refcount", "usecount", -- "flags", "device" } function net.routes6(callback) if fs.access("/proc/net/ipv6_route", "r") then local routes = { } for line in io.lines("/proc/net/ipv6_route") do local dst_ip, dst_prefix, src_ip, src_prefix, nexthop, metric, refcnt, usecnt, flags, dev = line:match( "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) ([a-f0-9]+) " .. "([a-f0-9]+) +([^%s]+)" ) if dst_ip and dst_prefix and src_ip and src_prefix and nexthop and metric and refcnt and usecnt and flags and dev then src_ip = luci.ip.Hex( src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false ) dst_ip = luci.ip.Hex( dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false ) nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false ) local rt = { source = src_ip, dest = dst_ip, nexthop = nexthop, metric = tonumber(metric, 16), refcount = tonumber(refcnt, 16), usecount = tonumber(usecnt, 16), flags = tonumber(flags, 16), device = dev, -- lua number is too small for storing the metric -- add a metric_raw field with the original content metric_raw = metric } if callback then callback(rt) else routes[#routes+1] = rt end end end return routes end end function net.pingtest(host) return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1") end process = {} function process.info(key) local s = {uid = nixio.getuid(), gid = nixio.getgid()} return not key and s or s[key] end function process.list() local data = {} local k local ps = luci.util.execi("/bin/busybox top -bn1") if not ps then return end for line in ps do local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match( "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)" ) local idx = tonumber(pid) if idx then data[idx] = { ['PID'] = pid, ['PPID'] = ppid, ['USER'] = user, ['STAT'] = stat, ['VSZ'] = vsz, ['%MEM'] = mem, ['%CPU'] = cpu, ['COMMAND'] = cmd } end end return data end function process.setgroup(gid) return nixio.setgid(gid) end function process.setuser(uid) return nixio.setuid(uid) end process.signal = nixio.kill user = {} -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" } user.getuser = nixio.getpw function user.getpasswd(username) local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username) local pwh = pwe and (pwe.pwdp or pwe.passwd) if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then return nil, pwe else return pwh, pwe end end function user.checkpasswd(username, pass) local pwh, pwe = user.getpasswd(username) if pwe then return (pwh == nil or nixio.crypt(pass, pwh) == pwh) end return false end function user.setpasswd(username, password) if password then password = password:gsub("'", [['"'"']]) end if username then username = username:gsub("'", [['"'"']]) end return os.execute( "(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " .. "passwd '" .. username .. "' >/dev/null 2>&1" ) end wifi = {} function wifi.getiwinfo(ifname) local stat, iwinfo = pcall(require, "iwinfo") if ifname then local c = 0 local u = uci.cursor_state() local d, n = ifname:match("^(%w+)%.network(%d+)") if d and n then ifname = d n = tonumber(n) u:foreach("wireless", "wifi-iface", function(s) if s.device == d then c = c + 1 if c == n then ifname = s.ifname or s.device return false end end end) elseif u:get("wireless", ifname) == "wifi-device" then u:foreach("wireless", "wifi-iface", function(s) if s.device == ifname and s.ifname then ifname = s.ifname return false end end) end local t = stat and iwinfo.type(ifname) local x = t and iwinfo[t] or { } return setmetatable({}, { __index = function(t, k) if k == "ifname" then return ifname elseif x[k] then return x[k](ifname) end end }) end end init = {} init.dir = "/etc/init.d/" function init.names() local names = { } for name in fs.glob(init.dir.."*") do names[#names+1] = fs.basename(name) end return names end function init.index(name) if fs.access(init.dir..name) then return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null" %{ init.dir, name }) end end local function init_action(action, name) if fs.access(init.dir..name) then return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action }) end end function init.enabled(name) return (init_action("enabled", name) == 0) end function init.enable(name) return (init_action("enable", name) == 1) end function init.disable(name) return (init_action("disable", name) == 0) end function init.start(name) return (init_action("start", name) == 0) end function init.stop(name) return (init_action("stop", name) == 0) end -- Internal functions function _parse_mixed_record(cnt, delimiter) delimiter = delimiter or " " local data = {} local flags = {} for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*') if k then if x == "" then table.insert(flags, k) else data[k] = v end end end end return data, flags end
gpl-2.0
maxolasersquad/ff_companion
final_fantasy.lua
1
11317
-- Most of the technical information provided by http://datacrystal.romhacking.net/wiki/Final_Fantasy:RAM_map bit = require 'bit32' lgi = require 'lgi' character = require 'character' Gtk = lgi.require('Gtk', '3.0') builder = Gtk.Builder() builder:add_from_file('main.glade') window = builder:get_object('window') local handlers = {} function handlers.destroy(window) os.exit() end builder:connect_signals(handlers) CharacterStats = { characterNumber = nil, properties = { 'name', 'class', 'level', 'hp', 'max_hp', 'experience', 'next_level', 'strength', 'agility', 'intelligence', 'vitality', 'luck', 'damage', 'hit_percent', 'absorb', 'evade_percent', 'magic_level_1_slot_1', 'magic_level_1_slot_2', 'magic_level_1_slot_3', 'magic_level_1_slot_4', 'magic_level_2_slot_1', 'magic_level_2_slot_2', 'magic_level_2_slot_3', 'magic_level_2_slot_4', 'magic_level_3_slot_1', 'magic_level_3_slot_2', 'magic_level_3_slot_3', 'magic_level_3_slot_4', 'magic_level_4_slot_1', 'magic_level_4_slot_2', 'magic_level_4_slot_3', 'magic_level_4_slot_4', 'magic_level_5_slot_1', 'magic_level_5_slot_2', 'magic_level_5_slot_3', 'magic_level_5_slot_4', 'magic_level_6_slot_1', 'magic_level_6_slot_2', 'magic_level_6_slot_3', 'magic_level_6_slot_4', 'magic_level_7_slot_1', 'magic_level_7_slot_2', 'magic_level_7_slot_3', 'magic_level_7_slot_4', 'magic_level_8_slot_1', 'magic_level_8_slot_2', 'magic_level_8_slot_3', 'magic_level_8_slot_4', 'magic_points_level_1', 'magic_points_level_2', 'magic_points_level_3', 'magic_points_level_4', 'magic_points_level_5', 'magic_points_level_6', 'magic_points_level_7', 'magic_points_level_8', 'max_magic_points_level_1', 'max_magic_points_level_2', 'max_magic_points_level_3', 'max_magic_points_level_4', 'max_magic_points_level_5', 'max_magic_points_level_6', 'max_magic_points_level_7', 'max_magic_points_level_8', 'weapon_slot_1', 'weapon_slot_2', 'weapon_slot_3', 'weapon_slot_4', 'armor_slot_1', 'armor_slot_2', 'armor_slot_3', 'armor_slot_4', } } function CharacterStats:new (o) setmetatable(o, self) self.__index = self o:init() return o end function CharacterStats:getPropertyName(property) return 'character_' .. self.characterNumber .. '_' .. property end function CharacterStats:init() for i in pairs(self.properties) do property = self.properties[i] self[property] = builder:get_object(self:getPropertyName(property)) end end characterStats = { CharacterStats:new{characterNumber = 1}, CharacterStats:new{characterNumber = 2}, CharacterStats:new{characterNumber = 3}, CharacterStats:new{characterNumber = 4}, } window:show_all() gameRam = { buttonPressed = 0x0020, displayMode = 0x000D, } controller = { right = 0x01, left = 0x02, down = 0x04, up = 0x08, start = 0x10, sel = 0x20, a = 0x40, b = 0x80 } controllerBits = { right = 0, left = 1, down = 2, up = 3, start = 4, sel = 5, b = 6, a = 7 } function getButtonPressed() return memory.readbyte(gameRam['buttonPressed']) end function updateButtonPressed() buttonPressed:set_text(getButtonPressed(), -1) end function updateRightButton() pressed = isButtonPressed(controllerBits['right']) buttonRight:set_text(tostring(pressed), -1) end function updateLeftButton() pressed = isButtonPressed(controllerBits['left']) buttonLeft:set_text(tostring(pressed), -1) end function updateDownButton() pressed = isButtonPressed(controllerBits['down']) buttonDown:set_text(tostring(pressed), -1) end function updateUpButton() pressed = isButtonPressed(controllerBits['up']) buttonUp:set_text(tostring(pressed), -1) end function updateStartButton() pressed = isButtonPressed(controllerBits['start']) buttonStart:set_text(tostring(pressed), -1) end function updateSelectButton() pressed = isButtonPressed(controllerBits['sel']) buttonSelect:set_text(tostring(pressed), -1) end function updateBButton() pressed = isButtonPressed(controllerBits['b']) buttonB:set_text(tostring(pressed), -1) end function updateAButton() pressed = isButtonPressed(controllerBits['a']) buttonA:set_text(tostring(pressed), -1) end function getMaskBit(mask, bitNumber) return bit.band(mask, (bit.lshift(1, bitNumber))) ~= 0 end function isButtonPressed(button) return getMaskBit(getButtonPressed(), button) end function updateDisplayMode() mode = memory.readbyte(gameRam['displayMode']) displayMode:set_text(mode, -1) end function updateCharacterName(character_index) characterStats[character_index].name:set_text(character[character_index]:getName(), -1) end function updateCharacterLevel(character_index) characterStats[character_index].level:set_text("Level: " .. character[character_index]:getLevel(), -1) end function updateCharacterHP(character_index) characterStats[character_index].hp:set_text(character[character_index]:getHP(), -1) end function updateCharacterMaxHP(character_index) characterStats[character_index].max_hp:set_text(character[character_index]:getMaxHP(), -1) end function updateCharacterExperience(character_index) characterStats[character_index].experience:set_text(character[character_index]:getExperience(), -1) end function updateCharacterNextLevel(character_index) characterStats[character_index].next_level:set_text(character[character_index]:getNextXP(), -1) end function updateCharacterStrength(character_index) characterStats[character_index].strength:set_text(character[character_index]:getStrength(), -1) end function updateCharacterAgility(character_index) characterStats[character_index].agility:set_text(character[character_index]:getAgility(), -1) end function updateCharacterIntelligence(character_index) characterStats[character_index].intelligence:set_text(character[character_index]:getIntelligence(), -1) end function updateCharacterVitality(character_index) characterStats[character_index].vitality:set_text(character[character_index]:getVitality(), -1) end function updateCharacterLuck(character_index) characterStats[character_index].luck:set_text(character[character_index]:getLuck(), -1) end function updateCharacterDamage(character_index) characterStats[character_index].damage:set_text(character[character_index]:getDamage(), -1) end function updateCharacterHitPercent(character_index) characterStats[character_index].hit_percent:set_text(character[character_index]:getHitPercent(), -1) end function updateCharacterAbsorb(character_index) characterStats[character_index].absorb:set_text(character[character_index]:getAbsorb(), -1) end function updateCharacterEvadePercent(character_index) characterStats[character_index].evade_percent:set_text(character[character_index]:getEvadePercent(), -1) end function updateCharacterWeapon(character_index, slot) equipped = '' weapon = character[character_index]:getWeapon(slot) if weapon then if character[character_index]:getEquippedWeaponIndex() == slot then equipped = 'E - ' end characterStats[character_index]['weapon_slot_' .. slot]:set_text(equipped .. weapon:getName(), -1) else characterStats[character_index]['weapon_slot_' .. slot]:set_text('', -1) end end function updateCharacterWeapons(character_index) for slot = 1,4 do updateCharacterWeapon(character_index, slot) end end function updateCharacterArmor(character_index, slot) equipped = '' armor = character[character_index]:getArmor(slot) if armor then if character[character_index]:getEquippedArmorIndex() == slot then equipped = 'E - ' end characterStats[character_index]['armor_slot_' .. slot]:set_text(equipped .. armor:getName(), -1) else characterStats[character_index]['armor_slot_' .. slot]:set_text('', -1) end end function updateCharacterArmors(character_index) for slot = 1,4 do updateCharacterArmor(character_index, slot) end end function updateCharacterMagic(character_index, level, slot) magic = character[character_index]:getMagic(level, slot) if magic then characterStats[character_index]['magic_level_' .. level .. '_slot_' .. slot]:set_text(magic:getName(), -1) else characterStats[character_index]['magic_level_' .. level .. '_slot_' .. slot]:set_text('', -1) end end function updateCharacterMagics(character_index) for level=1,8 do for slot=1,3 do updateCharacterMagic(character_index, level, slot) end end end function updateCharacterMagicPoint(character_index, level) characterStats[character_index]['magic_points_level_' .. level]:set_text(character[character_index]:getMagicPoints(level), -1) end function updateCharacterMagicPoints(character_index) for level=1,8 do updateCharacterMagicPoint(character_index, level) end end function updateCharacterMaxMagicPoint(character_index, level) characterStats[character_index]['max_magic_points_level_' .. level]:set_text(character[character_index]:getMaxMagicPoints(level), -1) end function updateCharacterMaxMagicPoints(character_index) for level=1,8 do updateCharacterMaxMagicPoint(character_index, level) end end lastMap = nil while (true) do map1 = character[1]:getHexMap() if map1 ~= lastMap1 then print(map1) lastMap1 = map1 end map2 = character[2]:getHexMap() if map2 ~= lastMap2 then print(map2) lastMap2 = map2 end map3 = character[3]:getHexMap() if map3 ~= lastMap3 then print(map3) lastMap3 = map3 end map4 = character[4]:getHexMap() if map4 ~= lastMap4 then print(map4) lastMap4 = map4 end frame_count = 0 for index = 1,4 do frame_count = frame_count + 1 if frame_count == 2 then emu.frameadvance() frame_count = 0 end updateCharacterName(index) updateCharacterLevel(index) updateCharacterHP(index) updateCharacterMaxHP(index) updateCharacterExperience(index) updateCharacterNextLevel(index) updateCharacterStrength(index) updateCharacterAgility(index) updateCharacterIntelligence(index) updateCharacterVitality(index) updateCharacterLuck(index) updateCharacterDamage(index) updateCharacterHitPercent(index) updateCharacterAbsorb(index) updateCharacterEvadePercent(index) updateCharacterWeapons(index) updateCharacterArmors(index) updateCharacterMagics(index) updateCharacterMagicPoints(index) updateCharacterMaxMagicPoints(index) end emu.frameadvance() end
gpl-3.0
alexandergall/snabbswitch
src/core/config.lua
14
2514
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- 'config' is a data structure that describes an app network. module(..., package.seeall) local lib = require("core.lib") -- API: Create a new configuration. -- Initially there are no apps or links. function new () return { apps = {}, -- list of {name, class, args} links = {} -- table with keys like "a.out -> b.in" } end -- API: Add an app to the configuration. -- -- config.app(c, name, class, arg): -- c is a config object. -- name is the name of this app in the network (a string). -- class is the Lua object with a class:new(arg) method to create the app. -- arg is the app's configuration (to be passed to new()). -- -- Example: config.app(c, "nic", Intel82599, {pciaddr = "0000:00:01.00"}) function app (config, name, class, arg) assert(type(name) == "string", "name must be a string") assert(type(class) == "table", "class must be a table") if class.config then local status, result = pcall(parse_app_arg, arg, class.config) if status then arg = result else error("failed to configure '"..name.."': "..result) end end config.apps[name] = { class = class, arg = arg} end -- API: Add a link to the configuration. -- -- Example: config.link(c, "nic.tx -> vm.rx") function link (config, spec) config.links[canonical_link(spec)] = true end -- Given "a.out -> b.in" return "a", "out", "b", "in". function parse_link (spec) local fa, fl, ta, tl = spec:gmatch(link_syntax)() if fa and fl and ta and tl then return fa, fl, ta, tl else error("link parse error: " .. spec) end end link_syntax = [[ *([%w_]+)%.([%w_]+) *-> *([%w_]+)%.([%w_]+) *]] function format_link (fa, fl, ta, tl) return ("%s.%s -> %s.%s"):format(fa, fl, ta, tl) end function canonical_link (spec) return format_link(parse_link(spec)) end -- Parse Lua object for the arg to an app based on config. Arg may be a table -- or a string encoded Lua object. function parse_app_arg (arg, config) if type(arg) == 'string' then arg = lib.load_string(arg) end return lib.parse(arg, config) end function graphviz (c) local viz = 'digraph config {\n' local function trim (name) return name:sub(0, 12) end for linkspec,_ in pairs(c.links) do local fa, fl, ta, tl = config.parse_link(linkspec) viz = viz..' '..trim(fa).." -> "..trim(ta)..' [taillabel="'..fl..'" headlabel="'..tl..'"]\n' end viz = viz..'}\n' return viz end
apache-2.0
xuejian1354/barrier_breaker
feeds/luci/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_config.lua
80
1153
--[[ LuCI - Lua Configuration Interface (c) 2009 Daniel Dickinson 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.controller.luci_diag.devinfo_common") m = Map("luci_devinfo", translate("Network Device Scanning Configuration"), translate("Configure scanning for devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices.")) s = m:section(SimpleSection, "", translate("Use Configuration")) b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)")) b.value = "" b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo") scannet = m:section(TypedSection, "netdiscover_scannet", translate("Scanning Configuration"), translate("Networks to scan for devices")) scannet.addremove = true scannet.anonymous = false luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet) return m
gpl-2.0
4aiman/MineClone
mods/WorldEdit/worldedit_infinity/init.lua
2
2754
local worldedit = {} local minetest = minetest --local copy of global local get_pointed = function(pos, nearest, distance) if distance > 100 then return false end --check for collision with node local nodename = minetest.get_node(pos).name if nodename ~= "air" and nodename ~= "default:water_source" and nodename ~= "default:water_flowing" then if nodename ~= "ignore" then return nearest end return false end end local use = function(itemstack, user, pointed_thing) if pointed_thing.type == "nothing" then --pointing at nothing local placepos = worldedit.raytrace(user:getpos(), user:get_look_dir(), get_pointed) if placepos then --extended reach pointed_thing.type = "node" pointed_thing.under = nil --wip pointed_thing.above = nil --wip end end return minetest.item_place_node(itemstack, user, pointed_thing) end -- worldedit.raytrace = function(pos, dir, callback) local base = {x=math.floor(pos.x), y=math.floor(pos.y), z=math.floor(pos.z)} local stepx, stepy, stepz = 0, 0, 0 local componentx, componenty, componentz = 0, 0, 0 local intersectx, intersecty, intersectz = 0, 0, 0 if dir.x == 0 then intersectx = math.huge elseif dir.x > 0 then stepx = 1 componentx = 1 / dir.x intersectx = ((base.x - pos.x) + 1) * componentx else stepx = -1 componentx = 1 / -dir.x intersectx = (pos.x - base.x) * componentx end if dir.y == 0 then intersecty = math.huge elseif dir.y > 0 then stepy = 1 componenty = 1 / dir.y intersecty = ((base.y - pos.y) + 1) * componenty else stepy = -1 componenty = 1 / -dir.y intersecty = (pos.y - base.y) * componenty end if dir.z == 0 then intersectz = math.huge elseif dir.z > 0 then stepz = 1 componentz = 1 / dir.z intersectz = ((base.z - pos.z) + 1) * componentz else stepz = -1 componentz = 1 / -dir.z intersectz = (pos.z - base.z) * componentz end local distance = 0 local nearest = {x=base.x, y=base.y, z=base.z} while true do local values = {callback(base, nearest, distance)} if #values > 0 then return unpack(values) end nearest.x, nearest.y, nearest.z = base.x, base.y, base.z if intersectx < intersecty then if intersectx < intersectz then base.x = base.x + stepx distance = intersectx intersectx = intersectx + componentx else base.z = base.z + stepz distance = intersectz intersectz = intersectz + componentz end elseif intersecty < intersectz then base.y = base.y + stepy distance = intersecty intersecty = intersecty + componenty else base.z = base.z + stepz distance = intersectz intersectz = intersectz + componentz end end end
lgpl-2.1
Moe-/GameJamSimulator
challenge.lua
1
7738
class "Challenge" { posx = 0; posy = 0; energy = 20; w = 0; fightIndex = 0; nextPlayer = 0; } function Challenge:__init(posx, posy) self.posx = posx self.posy = posy self.image = love.graphics.newImage("gfx/challenge.png") self.bg = love.graphics.newImage("gfx/battle_bg1.png") self.menu = love.graphics.newImage("gfx/battle_menu.png") self.quad = love.graphics.newQuad(0, 0, self.image:getWidth(), self.image:getHeight(), self.image:getWidth(), self.image:getHeight()) self.width = self.image:getWidth() self.height = self.image:getHeight() local rnd = math.random(1, 6) if rnd == 1 then self.desc = "Merge conflict!" elseif rnd == 2 then self.desc = "Application crash!" elseif rnd == 3 then self.desc = "Non-transparent background!" elseif rnd == 4 then self.desc = "Unlogical gameplay!" elseif rnd == 5 then self.desc = "Untriggered quest!" else self.desc = "Inverted colors!" end self.player = {} self.player[1] = {} self.player[1].x = 300 self.player[1].y = 100 self.player[1].image = love.graphics.newImage("gfx/marckus.png") self.player[2] = {} self.player[2].x = 300 self.player[2].y = 150 self.player[2].image = love.graphics.newImage("gfx/alex.png") self.player[3] = {} self.player[3].x = 300 self.player[3].y = 200 self.player[3].image = love.graphics.newImage("gfx/tomochan.png") self.active = true end function Challenge:update(dt) end function Challenge:draw(offsetx, offsety) love.graphics.draw(self.image, self.quad, self.posx - self.width / 2 + offsetx, self.posy - self.height / 2 + offsety) local px = self.posx + self.width / 2 + offsetx - 8 local py = self.posy + offsety - 12 love.graphics.setColor(0, 0, 0, 255) love.graphics.print(self.desc, px + 1, py + 1, 0, 1.25) love.graphics.setColor(128, 128, 255, 255) love.graphics.print(self.desc, px, py, 0, 1.25) love.graphics.setColor(255, 255, 255, 255) end function Challenge:updateBattle(dt) if self.energy <= 0 then self.active = false end return not self.active end function Challenge:drawBattle() love.graphics.print("Fight!!!", 200, 20) --background love.graphics.push() love.graphics.scale(1/gScale, 1/gScale) love.graphics.draw(self.bg, 0, 0) love.graphics.pop() --menu love.graphics.draw(self.menu, 0, 300 - 64) --draw player for i = 1, 3 do love.graphics.draw(self.player[i].image, self.player[i].x, self.player[i].y) end -- draw enemy love.graphics.draw(self.image, self.quad, 30 - self.width / 2, 150 - self.height / 2) local px = 30 + self.width / 2 - 8 local py = 150 - 12 love.graphics.setColor(0, 0, 0, 255) love.graphics.print(self.desc, px + 1, py + 1, 0, 1.25) love.graphics.print("HP " .. self.energy, 31, 121, 0, 1.25) love.graphics.setColor(128, 128, 255, 255) love.graphics.print(self.desc, px, py, 0, 1.25) love.graphics.print("HP " .. self.energy, 30, 120, 0, 1.25) love.graphics.setColor(255, 255, 255, 255) --draw menu love.graphics.print("Fight!!!", 200, 20) if self.nextPlayer == 0 then love.graphics.print("Coder", 20, 260) elseif self.nextPlayer == 1 then love.graphics.print("Designer", 20, 260) else love.graphics.print("Artist", 20, 260) end if self.fightIndex == 0 then love.graphics.setColor(128, 128, 255, 255) else love.graphics.setColor(255, 255, 255, 255) end love.graphics.print("Attack!", 200, 240) if self.fightIndex == 1 then love.graphics.setColor(128, 128, 255, 255) else love.graphics.setColor(255, 255, 255, 255) end love.graphics.print("Magic!", 200, 260) if self.fightIndex == 2 then love.graphics.setColor(128, 128, 255, 255) else love.graphics.setColor(255, 255, 255, 255) end love.graphics.print("Skip!", 200, 280) love.graphics.setColor(255, 255, 255, 255) end function Challenge:getPosition() return self.posx, self.posy end function Challenge:getSize() return self.width, self.height end function Challenge:keypressed(key) if key == "f1" then self.active = false end end function Challenge:keyreleased(key) if key == "w" then self.fightIndex = self.fightIndex - 1 if self.fightIndex < 0 then self.fightIndex = 2 end elseif key == "s" then self.fightIndex = self.fightIndex + 1 if self.fightIndex > 2 then self.fightIndex = 0 end elseif key == "return" then if self.fightIndex == 0 then -- attack if self.desc == "Merge conflict!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 3 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 3 else -- gfx guy self.energy = self.energy end elseif self.desc == "Application crash!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 3 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 3 else -- gfx guy self.energy = self.energy end elseif self.desc == "Non-transparent background!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 3 else -- gfx guy self.energy = self.energy -3 end elseif self.desc == "Unlogical gameplay!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy elseif self.nextPlayer == 1 then -- designer self.energy = self.energy - 3 else -- gfx guy self.energy = self.energy end elseif self.desc == "Untriggered quest!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 3 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy - 3 else -- gfx guy self.energy = self.energy + 3 end elseif self.desc == "Inverted colors!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 1 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 3 else -- gfx guy self.energy = self.energy - 3 end end elseif self.fightIndex == 1 then -- magic if self.desc == "Merge conflict!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 5 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 5 else -- gfx guy self.energy = self.energy end elseif self.desc == "Application crash!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 5 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 5 else -- gfx guy self.energy = self.energy end elseif self.desc == "Non-transparent background!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 5 else -- gfx guy self.energy = self.energy - 5 end elseif self.desc == "Unlogical gameplay!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy elseif self.nextPlayer == 1 then -- designer self.energy = self.energy - 5 else -- gfx guy self.energy = self.energy end elseif self.desc == "Untriggered quest!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 5 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy - 5 else -- gfx guy self.energy = self.energy + 5 end elseif self.desc == "Inverted colors!" then if self.nextPlayer == 0 then -- progger self.energy = self.energy - 2 elseif self.nextPlayer == 1 then -- designer self.energy = self.energy + 5 else -- gfx guy self.energy = self.energy - 5 end end else -- skip end self.nextPlayer = self.nextPlayer + 1 if self.nextPlayer > 2 then self.nextPlayer = 0 end end end
gpl-2.0