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
mqmaker/witi-openwrt
package/ramips/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-format.lua
80
3636
--[[ 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$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true format_au = module:option(ListValue, "format_au", "Sun Microsystems AU format (signed linear)", "") format_au:value("yes", "Load") format_au:value("no", "Do Not Load") format_au:value("auto", "Load as Required") format_au.rmempty = true format_g723 = module:option(ListValue, "format_g723", "G.723.1 Simple Timestamp File Format", "") format_g723:value("yes", "Load") format_g723:value("no", "Do Not Load") format_g723:value("auto", "Load as Required") format_g723.rmempty = true format_g726 = module:option(ListValue, "format_g726", "Raw G.726 (16/24/32/40kbps) data", "") format_g726:value("yes", "Load") format_g726:value("no", "Do Not Load") format_g726:value("auto", "Load as Required") format_g726.rmempty = true format_g729 = module:option(ListValue, "format_g729", "Raw G729 data", "") format_g729:value("yes", "Load") format_g729:value("no", "Do Not Load") format_g729:value("auto", "Load as Required") format_g729.rmempty = true format_gsm = module:option(ListValue, "format_gsm", "Raw GSM data", "") format_gsm:value("yes", "Load") format_gsm:value("no", "Do Not Load") format_gsm:value("auto", "Load as Required") format_gsm.rmempty = true format_h263 = module:option(ListValue, "format_h263", "Raw h263 data", "") format_h263:value("yes", "Load") format_h263:value("no", "Do Not Load") format_h263:value("auto", "Load as Required") format_h263.rmempty = true format_jpeg = module:option(ListValue, "format_jpeg", "JPEG (Joint Picture Experts Group) Image", "") format_jpeg:value("yes", "Load") format_jpeg:value("no", "Do Not Load") format_jpeg:value("auto", "Load as Required") format_jpeg.rmempty = true format_pcm = module:option(ListValue, "format_pcm", "Raw uLaw 8khz Audio support (PCM)", "") format_pcm:value("yes", "Load") format_pcm:value("no", "Do Not Load") format_pcm:value("auto", "Load as Required") format_pcm.rmempty = true format_pcm_alaw = module:option(ListValue, "format_pcm_alaw", "load => .so ; Raw aLaw 8khz PCM Audio support", "") format_pcm_alaw:value("yes", "Load") format_pcm_alaw:value("no", "Do Not Load") format_pcm_alaw:value("auto", "Load as Required") format_pcm_alaw.rmempty = true format_sln = module:option(ListValue, "format_sln", "Raw Signed Linear Audio support (SLN)", "") format_sln:value("yes", "Load") format_sln:value("no", "Do Not Load") format_sln:value("auto", "Load as Required") format_sln.rmempty = true format_vox = module:option(ListValue, "format_vox", "Dialogic VOX (ADPCM) File Format", "") format_vox:value("yes", "Load") format_vox:value("no", "Do Not Load") format_vox:value("auto", "Load as Required") format_vox.rmempty = true format_wav = module:option(ListValue, "format_wav", "Microsoft WAV format (8000hz Signed Line", "") format_wav:value("yes", "Load") format_wav:value("no", "Do Not Load") format_wav:value("auto", "Load as Required") format_wav.rmempty = true format_wav_gsm = module:option(ListValue, "format_wav_gsm", "Microsoft WAV format (Proprietary GSM)", "") format_wav_gsm:value("yes", "Load") format_wav_gsm:value("no", "Do Not Load") format_wav_gsm:value("auto", "Load as Required") format_wav_gsm.rmempty = true return cbimap
gpl-2.0
stanfordhpccenter/soleil-x
testcases/legacy/taylor_with_particles/taylor_green_vortex_1024_1024_512.lua
1
4179
-- This is a Lua config file for the Soleil code. return { xnum = 1024, -- number of cells in the x-direction ynum = 1024, -- number of cells in the y-direction znum = 512, -- number of cells in the z-direction -- if you increase the cell number and the calculation diverges -- right away, decrease the time step on the next line delta_time = 2.0e-3, -- Control max iterations here. Set to a very high number if -- you want to run the full calculation (it will stop once -- it hits the 20.0 second max time set below) max_iter = 10, -- Output options. All output is off by default, but we -- will need to turn it on to check results/make visualizations consoleFrequency = 10, -- Iterations between console output of statistics wrtRestart = 'OFF', wrtVolumeSolution = 'OFF', wrt1DSlice = 'OFF', wrtParticleEvolution = 'OFF', particleEvolutionIndex = 0, outputEveryTimeSteps = 50, restartEveryTimeSteps = 50, ------------------------------------------- --[ SHOULD NOT NEED TO MODIFY BELOW HERE]-- ------------------------------------------- -- Flow Initialization Options -- initCase = 'TaylorGreen3DVortex', -- Uniform, Restart, TaylorGreen2DVortex, TaylorGreen3DVortex initParams = {1.0,100.0,1.0,0.0,0.0}, -- for TGV: first three are density, pressure, velocity bodyForce = {0,0.0,0}, -- body force in x, y, z turbForcing = 'OFF', -- Turn turbulent forcing on or off turbForceCoeff = 0.0, -- Turbulent linear forcing coefficient (f = A*rho*u) restartIter = 10000, -- Grid Options -- PERIODICITY origin = {0.0, 0.0, 0.0}, -- spatial origin of the computational domain xWidth = 6.283185307179586, yWidth = 6.283185307179586, zWidth = 6.283185307179586, -- BCs on each boundary: 'periodic,' 'symmetry,' or 'wall' xBCLeft = 'periodic', xBCLeftVel = {0.0, 0.0, 0.0}, xBCLeftTemp = 0.0, xBCRight = 'periodic', xBCRightVel = {0.0, 0.0, 0.0}, xBCRightTemp = 0.0, yBCLeft = 'periodic', yBCLeftVel = {0.0, 0.0, 0.0}, yBCLeftTemp = 0.0, yBCRight = 'periodic', yBCRightVel = {0.0, 0.0, 0.0}, yBCRightTemp = 0.0, zBCLeft = 'periodic', zBCLeftVel = {0.0, 0.0, 0.0}, zBCLeftTemp = 0.0, zBCRight = 'periodic', zBCRightVel = {0.0, 0.0, 0.0}, zBCRightTemp = 0.0, --Time Integration Options -- cfl = -1.0, -- Negative CFL implies that we will used fixed delta T final_time = 20.00001, --- File Output Options -- headerFrequency = 200000, outputFormat = 'Tecplot', --Tecplot or Python -- Fluid Options -- gasConstant = 0.3333333333333333, gamma = 1.4, viscosity_model = 'PowerLaw', -- Constant, PowerLaw, Sutherland constant_visc = 0.004491, -- Value for a constant viscosity [kg/m/s] powerlaw_visc_ref = 0.000625, powerlaw_temp_ref = 300.0, prandtl = 0.7, suth_visc_ref = 1.716E-5, -- Sutherland's Law reference viscosity [kg/m/s] suth_temp_ref = 273.15, -- Sutherland's Law reference temperature [K] suth_s_ref = 110.4, -- Sutherland's Law S constant [K] -- Particle Options -- -- completely disable particles, including all data modeParticles = 'ON', initParticles = 'Uniform', -- 'Random' or 'Restart' restartParticleIter = 0, particleType = 'Free', -- Fixed or Free twoWayCoupling = 'OFF', -- ON or OFF num = 256000000, restitutionCoefficient = 1.0, convectiveCoefficient = 0.7, -- W m^-2 K^-1 heatCapacity = 0.7, -- J Kg^-1 K^-1 initialTemperature = 20, -- K density = 8900, -- kg/m^3 diameter_mean = 5e-3, -- m diameter_maxDeviation = 1e-3, -- m, for statistical distribution bodyForceParticles = {0.0,0.0,0.0}, absorptivity = 0.5, -- Equal to emissivity in thermal equilibrium maximum_num = 256000000, -- upper bound on particles with insertion insertion_rate = 0, -- per face and per time step insertion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ deletion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ -- (Kirchhoff law of thermal radiation) -- Radiation Options -- radiationType = 'OFF', -- ON or OFF radiationIntensity = 1e3, zeroAvgHeatSource = 'OFF' }
gpl-2.0
bigdogmat/wire
lua/entities/gmod_wire_egp/lib/init.lua
18
1289
EGP = {} -------------------------------------------------------- -- Include all other files -------------------------------------------------------- function EGP:Initialize() local Folder = "entities/gmod_wire_egp/lib/egplib/" local entries = file.Find( Folder .. "*.lua", "LUA") for _, entry in ipairs( entries ) do if (SERVER) then AddCSLuaFile( Folder .. entry ) end include( Folder .. entry ) end end EGP:Initialize() local EGP = EGP EGP.ConVars = {} EGP.ConVars.MaxObjects = CreateConVar( "wire_egp_max_objects", 300, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.MaxPerSec = CreateConVar( "wire_egp_max_bytes_per_sec", 10000, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) -- Keep between 2500-40000 EGP.ConVars.MaxVertices = CreateConVar( "wire_egp_max_poly_vertices", 1024, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowEmitter = CreateConVar( "wire_egp_allow_emitter", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowHUD = CreateConVar( "wire_egp_allow_hud", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowScreen = CreateConVar( "wire_egp_allow_screen", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
apache-2.0
FrisKAY/MineOS_Server
Installer/Installer.lua
1
13345
local component = require("component") local computer = require("computer") local term = require("term") local unicode = require("unicode") local event = require("event") local fs = require("filesystem") local internet = require("internet") local seri = require("serialization") local gpu = component.gpu -----------------Проверка компа на соответствие сис. требованиям-------------------------- --Создаем массив говна local govno = {} print(" ") print("Analyzing computer for matching system requirements...") --Проверяем, не планшет ли это if component.isAvailable("tablet") then table.insert(govno, "Tablet PC detected - You can't install MineOS_Server on tablet because of primitive GPU and Screen.") end --Проверяем GPU if gpu.maxResolution() < 150 then table.insert(govno, "Bad GPU or Screen - MineOS_Server requires Tier 3 GPU and Tier 3 Screen.") end --Проверяем оперативку if math.floor(computer.totalMemory() / 1536 ) < 2000 then table.insert(govno, "Not enough RAM - MineOS_Server Server requires at least 2000 KB RAM.") end if fs.get("bin/edit.lua") == nil or fs.get("bin/edit.lua").isReadOnly() then table.insert(govno, "You can't install MineOS_Server Server on floppy disk. Run \"install\" in command line and install OpenOS from floppy to HDD first. After that you're be able to install MineOS_Server Server from Pastebin.") end --Если нашло какое-то несоответствие сис. требованиям, то написать, что именно не так if #govno > 0 then print(" ") for i = 1, #govno do print(govno[i]) end print(" ") return else print("Done, everything's good. Proceed to downloading.") print(" ") end ------------------------------------------------------------------------------------------ local lang local applications local padColor = 0x262626 local installerScale = 1 local timing = 0.2 -----------------------------СТАДИЯ ПОДГОТОВКИ------------------------------------------- --ЗАГРУЗОЧКА С ГИТХАБА local function getFromGitHub(url, path) local sContent = "" local result, response = pcall(internet.request, url) if not result then return nil end if fs.exists(path) then fs.remove(path) end fs.makeDirectory(fs.path(path)) local file = io.open(path, "w") for chunk in response do file:write(chunk) sContent = sContent .. chunk end file:close() return sContent end --БЕЗОПАСНАЯ ЗАГРУЗОЧКА local function getFromGitHubSafely(url, path) local success, sRepos = pcall(getFromGitHub, url, path) if not success then io.stderr:write("Can't download \"" .. url .. "\"!\n") return -1 end return sRepos end --ЗАГРУЗОЧКА С ПАСТЕБИНА local function getFromPastebin(paste, filename) local cyka = "" local f, reason = io.open(filename, "w") if not f then io.stderr:write("Failed opening file for writing: " .. reason) return end --io.write("Downloading from pastebin.com... ") local url = "http://pastebin.com/raw.php?i=" .. paste local result, response = pcall(internet.request, url) if result then --io.write("success.\n") for chunk in response do --if not options.k then --string.gsub(chunk, "\r\n", "\n") --end f:write(chunk) cyka = cyka .. chunk end f:close() --io.write("Saved data to " .. filename .. "\n") else f:close() fs.remove(filename) io.stderr:write("HTTP request failed: " .. response .. "\n") end return cyka end local GitHubUserUrl = "https://raw.githubusercontent.com/" --------------------------------- Стадия стартовой загрузки всего необходимого --------------------------------- local preLoadApi = { { paste = "FrisKAY/MineOS_Server/master/lib/ECSAPI.lua", path = "lib/ECSAPI.lua" }, { paste = "FrisKAY/MineOS_Server/master/lib/colorlib.lua", path = "lib/colorlib.lua" }, { paste = "FrisKAY/MineOS_Server/master/lib/image.lua", path = "lib/image.lua" }, { paste = "FrisKAY/MineOS_Server/master/lib/config.lua", path = "lib/config.lua" }, { paste = "FrisKAY/MineOS_Server/master/MineOS_Server/Icons/Languages.pic", path = "MineOS_Server/System/OS/Icons/Languages.pic" }, { paste = "FrisKAY/MineOS_Server/master/MineOS_Server/Icons/OK.pic", path = "MineOS_Server/System/OS/Icons/OK.pic" }, { paste = "FrisKAY/MineOS_Server/master/MineOS_Server/Icons/Downloading.pic", path = "MineOS_Server/System/OS/Icons/Downloading.pic" }, { paste = "FrisKAY/MineOS_Server/master/MineOS_Server/Icons/OS_Logo.pic", path = "MineOS_Server/System/OS/Icons/OS_Logo.pic" }, } print("Downloading file list") applications = seri.unserialize(getFromGitHubSafely(GitHubUserUrl .. "FrisKAY/MineOS_Server/master/Applications.txt", "MineOS_Server/System/OS/Applications.txt")) print(" ") for i = 1, #preLoadApi do print("Downloading must-have files (" .. fs.name(preLoadApi[i].path) .. ")") getFromGitHubSafely(GitHubUserUrl .. preLoadApi[i].paste, preLoadApi[i].path) end print(" ") package.loaded.ecs = nil package.loaded.ECSAPI = nil _G.ecs = require("ECSAPI") _G.image = require("image") _G.config = require("config") local imageOS = image.load("MineOS_Server/System/OS/Icons/OS_Logo.pic") local imageLanguages = image.load("MineOS_Server/System/OS/Icons/Languages.pic") local imageDownloading = image.load("MineOS_Server/System/OS/Icons/Downloading.pic") local imageOK = image.load("MineOS_Server/System/OS/Icons/OK.pic") ecs.setScale(installerScale) local xSize, ySize = gpu.getResolution() local windowWidth = 80 local windowHeight = 2 + 16 + 2 + 3 + 2 local xWindow, yWindow = math.floor(xSize / 2 - windowWidth / 2), math.ceil(ySize / 2 - windowHeight / 2) local xWindowEnd, yWindowEnd = xWindow + windowWidth - 1, yWindow + windowHeight - 1 ------------------------------------------------------------------------------------------- local function clear() ecs.blankWindow(xWindow, yWindow, windowWidth, windowHeight) end --ОБЪЕКТЫ local obj = {} local function newObj(class, name, ...) obj[class] = obj[class] or {} obj[class][name] = {...} end local function drawButton(name, isPressed) local buttonColor = 0x888888 if isPressed then buttonColor = ecs.colors.blue end local d = { ecs.drawAdaptiveButton("auto", yWindowEnd - 3, 2, 1, name, buttonColor, 0xffffff) } newObj("buttons", name, d[1], d[2], d[3], d[4]) end local function waitForClickOnButton(buttonName) while true do local e = { event.pull() } if e[1] == "touch" then if ecs.clickedAtArea(e[3], e[4], obj["buttons"][buttonName][1], obj["buttons"][buttonName][2], obj["buttons"][buttonName][3], obj["buttons"][buttonName][4]) then drawButton(buttonName, true) os.sleep(timing) break end end end end ------------------------------ВЫБОР ЯЗЫКА------------------------------------ ecs.prepareToExit() local downloadWallpapers, showHelpTips = false, false do clear() image.draw(math.ceil(xSize / 2 - 30), yWindow + 2, imageLanguages) --кнопа drawButton("Select language",false) waitForClickOnButton("Select language") local data = ecs.universalWindow("auto", "auto", 36, 0x262626, true, {"EmptyLine"}, {"CenterText", ecs.colors.orange, "Select language"}, {"EmptyLine"}, {"Select", 0xFFFFFF, ecs.colors.green, "Russian", "English"}, {"EmptyLine"}, {"CenterText", ecs.colors.orange, "Change some OS properties"}, {"EmptyLine"}, {"Switch", 0xF2B233, 0xffffff, 0xFFFFFF, "Download wallpapers", true}, {"EmptyLine"}, {"Switch", 0xF2B233, 0xffffff, 0xFFFFFF, "Show help tips in OS", true}, {"EmptyLine"}, {"Button", {ecs.colors.orange, 0x262626, "OK"}}) downloadWallpapers, showHelpTips = data[2], data[3] --УСТАНАВЛИВАЕМ НУЖНЫЙ ЯЗЫК _G.OSSettings = { showHelpOnApplicationStart = showHelpTips, language = data[1] } ecs.saveOSSettings() --Качаем язык ecs.info("auto", "auto", " ", " Installing language packages...") local pathToLang = "MineOS_Server/System/OS/Installer/Language.lang" getFromGitHubSafely(GitHubUserUrl .. "FrisKAY/MineOS_Server/master/Installer/" .. _G.OSSettings.language .. ".lang", pathToLang) getFromGitHubSafely(GitHubUserUrl .. "FrisKAY/MineOS_Server/master/MineOS_Server/License/" .. _G.OSSettings.language .. ".txt", "MineOS_Server/System/OS/License.txt") --Ставим язык lang = config.readAll(pathToLang) end ------------------------------СТАВИТЬ ЛИ ОСЬ------------------------------------ do clear() image.draw(math.ceil(xSize / 2 - 15), yWindow + 2, imageOS) --Текстик по центру gpu.setBackground(ecs.windowColors.background) gpu.setForeground(ecs.colors.gray) ecs.centerText("x", yWindowEnd - 5 , lang.beginOsInstall) --кнопа drawButton("->",false) waitForClickOnButton("->") end ------------------------------ЛИЦ СОГЛАЩЕНЬКА------------------------------------------ do clear() --Откуда рисовать условия согл local from = 1 local xText, yText, TextWidth, TextHeight = xWindow + 4, yWindow + 2, windowWidth - 8, windowHeight - 7 --Читаем файл с лиц соглл local lines = {} local file = io.open("MineOS_Server/System/OS/License.txt", "r") for line in file:lines() do table.insert(lines, line) end file:close() --Штуку рисуем ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue) --Инфо рисуем --ecs.centerText("x", yWindowEnd - 5 ,"Принимаете ли вы условия лицензионного соглашения?") --кнопа drawButton(lang.acceptLicense, false) while true do local e = { event.pull() } if e[1] == "touch" then if ecs.clickedAtArea(e[3], e[4], obj["buttons"][lang.acceptLicense][1], obj["buttons"][lang.acceptLicense][2], obj["buttons"][lang.acceptLicense][3], obj["buttons"][lang.acceptLicense][4]) then drawButton(lang.acceptLicense, true) os.sleep(timing) break end elseif e[1] == "scroll" then if e[5] == -1 then if from < #lines then from = from + 1; ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue) end else if from > 1 then from = from - 1; ecs.textField(xText, yText, TextWidth, TextHeight, lines, from, 0xffffff, 0x262626, 0x888888, ecs.colors.blue) end end end end end -------------------------- Подготавливаем файловую систему ---------------------------------- --Создаем стартовые пути и прочие мелочи чисто для эстетики local desktopPath = "MineOS_Server/Desktop/" local dockPath = "MineOS_Server/System/OS/Dock/" local applicationsPath = "MineOS_Server/Applications/" local picturesPath = "MineOS_Server/Pictures/" fs.remove(desktopPath) fs.remove(dockPath) fs.makeDirectory(desktopPath .. "My files") fs.makeDirectory(picturesPath) fs.makeDirectory(dockPath) --------------------------СТАДИЯ ЗАГРУЗКИ----------------------------------- do local barWidth = math.floor(windowWidth * 2 / 3) local xBar = math.floor(xSize/2-barWidth/2) local yBar = yWindowEnd - 3 local function drawInfo(x, y, info) ecs.square(x, y, barWidth, 1, ecs.windowColors.background) ecs.colorText(x, y, ecs.colors.gray, info) end ecs.blankWindow(xWindow,yWindow,windowWidth,windowHeight) image.draw(math.floor(xSize/2 - 33), yWindow + 2, imageDownloading) ecs.colorTextWithBack(xBar, yBar - 1, ecs.colors.gray, ecs.windowColors.background, lang.osInstallation) ecs.progressBar(xBar, yBar, barWidth, 1, 0xcccccc, ecs.colors.blue, 0) os.sleep(timing) for app = 1, #applications do --ВСЕ ДЛЯ ГРАФОНА drawInfo(xBar, yBar + 1, lang.downloading .. " " .. applications[app]["name"]) local percent = app / #applications * 100 ecs.progressBar(xBar, yBar, barWidth, 1, 0xcccccc, ecs.colors.blue, percent) ecs.getOSApplication(applications[app], downloadWallpapers) end os.sleep(timing) end --Создаем базовые обои рабочего стола ecs.createShortCut(desktopPath .. "Pictures.lnk", picturesPath) if downloadWallpapers then ecs.createShortCut("MineOS_Server/System/OS/Wallpaper.lnk", picturesPath .. "Girl.pic") end --Автозагрузка local file = io.open("autorun.lua", "w") file:write("local success, reason = pcall(loadfile(\"OS.lua\")); if not success then print(\"Ошибка: \" .. tostring(reason)) end") file:close() --------------------------СТАДИЯ ПЕРЕЗАГРУЗКИ КОМПА----------------------------------- ecs.blankWindow(xWindow,yWindow,windowWidth,windowHeight) image.draw(math.floor(xSize/2 - 16), math.floor(ySize/2 - 11), imageOK) --Текстик по центру gpu.setBackground(ecs.windowColors.background) gpu.setForeground(ecs.colors.gray) ecs.centerText("x",yWindowEnd - 5, lang.needToRestart) --Кнопа drawButton(lang.restart, false) waitForClickOnButton(lang.restart) ecs.prepareToExit() computer.shutdown(true)
gpl-3.0
czlc/skynet
lualib/skynet/cluster.lua
1
1702
local skynet = require "skynet" local clusterd local cluster = {} function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(clusterd, "lua", "req", node, address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response skynet.send(clusterd, "lua", "push", node, address, skynet.pack(...)) end function cluster.open(port) if type(port) == "string" then skynet.call(clusterd, "lua", "listen", port) else skynet.call(clusterd, "lua", "listen", "0.0.0.0", port) end end function cluster.reload(config) skynet.call(clusterd, "lua", "reload", config) end -- Éú³ÉÒ»¸ö±¾µØ´úÀí¡£Ö®ºó£¬¾Í¿ÉÒÔÏñ·ÃÎÊÒ»¸ö±¾µØ·þÎñÒ»Ñù£¬ºÍÕâ¸öÔ¶³Ì·þÎñͨѶ¡£ -- ·µ»ØÕâ¸ö´úÀíµÄhandle£¬"clusterproxy" function cluster.proxy(node, name) return skynet.call(clusterd, "lua", "proxy", node, name) end function cluster.snax(node, name, address) local snax = require "skynet.snax" if not address then address = cluster.call(node, ".service", "QUERY", "snaxd" , name) end local handle = skynet.call(clusterd, "lua", "proxy", node, address) return snax.bind(handle, name) end -- °Ñ addr ×¢²áΪ cluster ¿É¼ûµÄÒ»¸ö×Ö·û´®Ãû×Ö name ¡£Èç¹û²»´« addr ±íʾ°Ñ×ÔÉí×¢²áΪ name function cluster.register(name, addr) assert(type(name) == "string") assert(addr == nil or type(addr) == "number") return skynet.call(clusterd, "lua", "register", name, addr) end -- ²éѯָ¶¨½áµãnodeÏÂnameÖ¸¶¨µÄ·þÎñ function cluster.query(node, name) return skynet.call(clusterd, "lua", "req", node, 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") -- ±¾½ÚµãΨһ end) return cluster
mit
mahdikord/baran
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
LuaDist2/lrexlib-tre
test/emacs_sets.lua
9
1481
-- See Copyright Notice in the file LICENSE local luatest = require "luatest" local N = luatest.NT local unpack = unpack or table.unpack local function norm(a) return a==nil and N or a end local function set_f_gmatch (lib, flg) -- gmatch (s, p, [cf], [ef]) local function test_gmatch (subj, patt) local out, guard = {}, 10 for a, b in lib.gmatch (subj, patt, flg.SYNTAX_EMACS, nil) do table.insert (out, { norm(a), norm(b) }) guard = guard - 1 if guard == 0 then break end end return unpack (out) end return { Name = "Function gmatch", Func = test_gmatch, --{ subj patt results } { {("abcd"):rep(3), "\\(.\\)b.\\(d\\)"}, {{"a","d"},{"a","d"},{"a","d"}} }, } end local function set_f_split (lib, flg) -- split (s, p, [cf], [ef]) local function test_split (subj, patt) local out, guard = {}, 10 for a, b, c in lib.split (subj, patt, flg.SYNTAX_EMACS, nil) do table.insert (out, { norm(a), norm(b), norm(c) }) guard = guard - 1 if guard == 0 then break end end return unpack (out) end return { Name = "Function split", Func = test_split, --{ subj patt results } { {"ab<78>c", "<\\(.\\)\\(.\\)>"}, {{"ab","7","8"}, {"c",N,N}, } }, } end return function (libname) local lib = require (libname) local flags = lib.flags () return { set_f_gmatch (lib, flags), set_f_split (lib, flags), } end
mit
mahdikord/baran
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
MonkeyFirst/DisabledBoneSlerpWithShadowedAnimation
bin/Data/LuaScripts/39_CrowdNavigation.lua
3
24869
-- CrowdNavigation example. -- This sample demonstrates: -- - Generating a dynamic navigation mesh into the scene -- - Performing path queries to the navigation mesh -- - Adding and removing obstacles/agents at runtime -- - Raycasting drawable components -- - Crowd movement management -- - Accessing crowd agents with the crowd manager -- - Using off-mesh connections to make boxes climbable -- - Using agents to simulate moving obstacles require "LuaScripts/Utilities/Sample" local INSTRUCTION = "instructionText" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() -- Setup the viewport for displaying the scene SetupViewport() -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Also create a DebugRenderer component so that we can draw debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create scene node & StaticModel component for showing a static plane local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility local boxGroup = scene_:CreateChild("Boxes") for i = 1, 20 do local boxNode = boxGroup:CreateChild("Box") local size = 1.0 + Random(10.0) boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0) boxNode:SetScale(size) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") boxObject.castShadows = true if size >= 3.0 then boxObject.occluder = true end end -- Create a DynamicNavigationMesh component to the scene root local navMesh = scene_:CreateComponent("DynamicNavigationMesh") -- Enable drawing debug geometry for obstacles and off-mesh connections navMesh.drawObstacles = true navMesh.drawOffMeshConnections = true -- Set the agent height large enough to exclude the layers under boxes navMesh.agentHeight = 10 -- Set nav mesh cell height to minimum (allows agents to be grounded) navMesh.cellHeight = 0.05 -- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the -- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable scene_:CreateComponent("Navigable") -- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes -- in the scene and still update the mesh correctly navMesh.padding = Vector3(0.0, 10.0, 0.0) -- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use -- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example) -- it will use renderable geometry instead navMesh:Build() -- Create an off-mesh connection for each box to make it climbable (tiny boxes are skipped). -- Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt. -- Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection CreateBoxOffMeshConnections(navMesh, boxGroup) -- Create some mushrooms as obstacles. Note that obstacles are non-walkable areas for i = 1, 100 do CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)) end -- Create a CrowdManager component to the scene root (mandatory for crowd agents) local crowdManager = scene_:CreateComponent("CrowdManager") local params = crowdManager:GetObstacleAvoidanceParams(0) -- Set the params to "High (66)" setting params.velBias = 0.5 params.adaptiveDivs = 7 params.adaptiveRings = 3 params.adaptiveDepth = 3 crowdManager:SetObstacleAvoidanceParams(0, params) -- Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles CreateMovingBarrels(navMesh) -- Create Jack node as crowd agent SpawnJack(Vector3(-5, 0, 20), scene_:CreateChild("Jacks")) -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load / save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane and looking down cameraNode.position = Vector3(0.0, 50.0, 0.0) pitch = 80.0 cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end function CreateUI() -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will point the raycast target local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") local cursor = Cursor:new() cursor:SetStyleAuto(style) ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text", INSTRUCTION) instructionText.text = "Use WASD keys to move, RMB to rotate view\n".. "LMB to set destination, SHIFT+LMB to spawn a Jack\n".. "MMB or O key to add obstacles or remove obstacles/agents\n".. "F5 to save scene, F7 to load\n".. "Space to toggle debug geometry\n".. "F12 to toggle this instruction text" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") -- Subscribe HandleCrowdAgentFailure() function for resolving invalidation issues with agents, during which we -- use a larger extents for finding a point on the navmesh to fix the agent's position SubscribeToEvent("CrowdAgentFailure", "HandleCrowdAgentFailure") -- Subscribe HandleCrowdAgentReposition() function for controlling the animation SubscribeToEvent("CrowdAgentReposition", "HandleCrowdAgentReposition") -- Subscribe HandleCrowdAgentFormation() function for positioning agent into a formation SubscribeToEvent("CrowdAgentFormation", "HandleCrowdAgentFormation") end function SpawnJack(pos, jackGroup) local jackNode = jackGroup:CreateChild("Jack") jackNode.position = pos local modelObject = jackNode:CreateComponent("AnimatedModel") modelObject.model = cache:GetResource("Model", "Models/Jack.mdl") modelObject.material = cache:GetResource("Material", "Materials/Jack.xml") modelObject.castShadows = true jackNode:CreateComponent("AnimationController") -- Create a CrowdAgent component and set its height and realistic max speed/acceleration. Use default radius local agent = jackNode:CreateComponent("CrowdAgent") agent.height = 2.0 agent.maxSpeed = 3.0 agent.maxAccel = 3.0 end function CreateMushroom(pos) local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = pos mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(2.0 + Random(0.5)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true -- Create the navigation Obstacle component and set its height & radius proportional to scale local obstacle = mushroomNode:CreateComponent("Obstacle") obstacle.radius = mushroomNode.scale.x obstacle.height = mushroomNode.scale.y end function CreateBoxOffMeshConnections(navMesh, boxGroup) boxes = boxGroup:GetChildren() for i, box in ipairs(boxes) do local boxPos = box.position local boxHalfSize = box.scale.x / 2 -- Create 2 empty nodes for the start & end points of the connection. Note that order matters only when using one-way/unidirectional connection. local connectionStart = box:CreateChild("ConnectionStart") connectionStart.worldPosition = navMesh:FindNearestPoint(boxPos + Vector3(boxHalfSize, -boxHalfSize, 0)) -- Base of box local connectionEnd = connectionStart:CreateChild("ConnectionEnd") connectionEnd.worldPosition = navMesh:FindNearestPoint(boxPos + Vector3(boxHalfSize, boxHalfSize, 0)) -- Top of box -- Create the OffMeshConnection component to one node and link the other node local connection = connectionStart:CreateComponent("OffMeshConnection") connection.endPoint = connectionEnd end end function CreateMovingBarrels(navMesh) local barrel = scene_:CreateChild("Barrel") local model = barrel:CreateComponent("StaticModel") model.model = cache:GetResource("Model", "Models/Cylinder.mdl") model.material = cache:GetResource("Material", "Materials/StoneTiled.xml") model.material:SetTexture(TU_DIFFUSE, cache:GetResource("Texture2D", "Textures/TerrainDetail2.dds")) model.castShadows = true for i = 1, 20 do local clone = barrel:Clone() local size = 0.5 + Random(1) clone.scale = Vector3(size / 1.5, size * 2, size / 1.5) clone.position = navMesh:FindNearestPoint(Vector3(Random(80.0) - 40.0, size * 0.5 , Random(80.0) - 40.0)) local agent = clone:CreateComponent("CrowdAgent") agent.radius = clone.scale.x * 0.5 agent.height = size agent.navigationQuality = NAVIGATIONQUALITY_LOW end barrel:Remove() end function SetPathPoint(spawning) local hitPos, hitDrawable = Raycast(250.0) if hitDrawable then local navMesh = scene_:GetComponent("DynamicNavigationMesh") local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE) local jackGroup = scene_:GetChild("Jacks") if spawning then -- Spawn a jack at the target position SpawnJack(pathPos, jackGroup) else -- Set crowd agents target position scene_:GetComponent("CrowdManager"):SetCrowdTarget(pathPos, jackGroup) end end end function AddOrRemoveObject() -- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one local hitPos, hitDrawable = Raycast(250.0) if hitDrawable then local hitNode = hitDrawable.node if hitNode.name == "Mushroom" then hitNode:Remove() elseif hitNode.name == "Jack" then hitNode:Remove() else CreateMushroom(hitPos) end end end function Raycast(maxDistance) local pos = ui.cursorPosition -- Check the cursor is visible and there is no UI element in front of the cursor if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then return nil, nil end local camera = cameraNode:GetComponent("Camera") local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height) -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit local octree = scene_:GetComponent("Octree") local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY) if result.drawable ~= nil then return result.position, result.drawable end return nil, nil end function MoveCamera(timeStep) -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees -- Only move the camera when the cursor is hidden if not ui.cursor.visible then local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- Set destination or spawn a jack with left mouse button if input:GetMouseButtonPress(MOUSEB_LEFT) then SetPathPoint(input:GetQualifierDown(QUAL_SHIFT)) -- Add new obstacle or remove existing obstacle/agent with middle mouse button elseif input:GetMouseButtonPress(MOUSEB_MIDDLE) or input:GetKeyPress(KEY_O) then AddOrRemoveObject() end -- Check for loading/saving the scene from/to the file Data/Scenes/CrowdNavigation.xml relative to the executable directory if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/CrowdNavigation.xml") elseif input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/CrowdNavigation.xml") -- Toggle debug geometry with space elseif input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug -- Toggle instruction text with F12 elseif input:GetKeyPress(KEY_F12) then instruction = ui.root:GetChild(INSTRUCTION) instruction.visible = not instruction.visible end end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandlePostRenderUpdate(eventType, eventData) if drawDebug then -- Visualize navigation mesh, obstacles and off-mesh connections scene_:GetComponent("DynamicNavigationMesh"):DrawDebugGeometry(true) -- Visualize agents' path and position to reach scene_:GetComponent("CrowdManager"):DrawDebugGeometry(true) end end function HandleCrowdAgentFailure(eventType, eventData) local node = eventData["Node"]:GetPtr("Node") local agentState = eventData["CrowdAgentState"]:GetInt() -- If the agent's state is invalid, likely from spawning on the side of a box, find a point in a larger area if agentState == CA_STATE_INVALID then -- Get a point on the navmesh using more generous extents local newPos = scene_:GetComponent("DynamicNavigationMesh"):FindNearestPoint(node.position, Vector3(5, 5, 5)) -- Set the new node position, CrowdAgent component will automatically reset the state of the agent node.position = newPos end end function HandleCrowdAgentReposition(eventType, eventData) local WALKING_ANI = "Models/Jack_Walk.ani" local node = eventData["Node"]:GetPtr("Node") local agent = eventData["CrowdAgent"]:GetPtr("CrowdAgent") local velocity = eventData["Velocity"]:GetVector3() local timeStep = eventData["TimeStep"]:GetFloat() -- Only Jack agent has animation controller local animCtrl = node:GetComponent("AnimationController") if animCtrl ~= nil then local speed = velocity:Length() if animCtrl:IsPlaying(WALKING_ANI) then local speedRatio = speed / agent.maxSpeed -- Face the direction of its velocity but moderate the turning speed based on the speed ratio and timeStep node.rotation = node.rotation:Slerp(Quaternion(Vector3.FORWARD, velocity), 10.0 * timeStep * speedRatio) -- Throttle the animation speed based on agent speed ratio (ratio = 1 is full throttle) animCtrl:SetSpeed(WALKING_ANI, speedRatio) else animCtrl:Play(WALKING_ANI, 0, true, 0.1) end -- If speed is too low then stopping the animation if speed < agent.radius then animCtrl:Stop(WALKING_ANI, 0.8) end end end function HandleCrowdAgentFormation(eventType, eventData) local index = eventData["Index"]:GetUInt() local size = eventData["Size"]:GetUInt() local position = eventData["Position"]:GetVector3() -- The first agent will always move to the exact position, all other agents will select a random point nearby if index > 0 then local crowdManager = GetEventSender() local agent = eventData["CrowdAgent"]:GetPtr("CrowdAgent") eventData["Position"] = crowdManager:GetRandomPointInCircle(position, agent.radius, agent.queryFilterType) end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element\">" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button3\" />" .. " <attribute name=\"Position\" value=\"-120 -120\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Spawn\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"LSHIFT\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </element>" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button4\" />" .. " <attribute name=\"Position\" value=\"-120 -12\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Obstacles\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"MIDDLE\" />" .. " </element>" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
4w/xtend
xfurniture/init.lua
1
1820
_xtend.init() -- Load modpath for multiple uses local modpath = _xtend.mods.xfurniture.modpath..DIR_DELIM -- Load options _xtend.mods.xfurniture.crafting_addition = { id = 'xfurniture:crafting_addition', amount = 2, recipe = {'default:cobble', 'default:dirt', 'default:dirt'}, name = _xtend.translate('Crafting Addition for xFurniture objects'), image = 'xfurniture_crafting_addition.png' } _xtend.mods.xfurniture.replace = { -- To be replaced with other default materials {'default:cloud', 'default:glass'}, {'default:coral_brown', 'default:clay_lump'}, {'default:coral_orange', 'default:apple'} } _xtend.mods.xfurniture.blacklist = { 'contains:chest', 'contains:dirt_with', 'contains:furnace', 'contains:stone_with', 'contains:trap_%w+', 'contains:trap_%w+_stone', 'drawtype:glasslike_framed_optional', 'drawtype:flowingliquid', 'drawtype:liquid', 'drawtype:mesh', 'drawtype:nodebox', 'drawtype:plantlike', 'drawtype:raillike', 'drawtype:signlike', 'group:leaves', 'group:soil', 'moreores:mineral_mithril', 'moreores:mineral_silver', } -- Prepare functionality dofile(modpath..'system'..DIR_DELIM..'get_nodes.lua') dofile(modpath..'system'..DIR_DELIM..'apply_indent.lua') dofile(modpath..'system'..DIR_DELIM..'register_furniture.lua') -- Register furniture objects dofile(modpath..'furniture'..DIR_DELIM..'recipe_patterns.lua') dofile(modpath..'system'..DIR_DELIM..'get_objects_to_create.lua') dofile(modpath..'system'..DIR_DELIM..'override_uncraftables.lua') -- print initinformation if debug messages are enabled dofile(modpath..'system'..DIR_DELIM..'init_information.lua') -- Clean up and transfer functions to the xFurniture API _xtend.clean({ 'nodes', 'register', 'apply_indent' })
gpl-3.0
bigdogmat/wire
lua/effects/thruster_ring.lua
10
1604
EFFECT.Mat = Material( "effects/select_ring" ) /*--------------------------------------------------------- Initializes the effect. The data is a table of data which was passed from the server. ---------------------------------------------------------*/ function EFFECT:Init( data ) local size = 16 self:SetCollisionBounds( Vector( -size,-size,-size ), Vector( size,size,size ) ) local Pos = data:GetOrigin() + data:GetNormal() * 2 self:SetPos( Pos ) self:SetAngles( data:GetNormal():Angle() + Angle( 0.01, 0.01, 0.01 ) ) self.Pos = data:GetOrigin() self.Normal = data:GetNormal() self.Speed = 2 self.Size = 16 self.Alpha = 255 end /*--------------------------------------------------------- THINK ---------------------------------------------------------*/ function EFFECT:Think( ) local speed = FrameTime() * self.Speed //if (self.Speed > 100) then self.Speed = self.Speed - 1000 * speed end //self.Size = self.Size + speed * self.Speed self.Alpha = self.Alpha - 250.0 * speed self:SetPos( self:GetPos() + self.Normal * speed * 128 ) if (self.Alpha < 0 ) then return false end if (self.Size < 0) then return false end return true end /*--------------------------------------------------------- Draw the effect ---------------------------------------------------------*/ function EFFECT:Render( ) if (self.Alpha < 1 ) then return end render.SetMaterial( self.Mat ) render.DrawQuadEasy( self:GetPos(), self:GetAngles():Forward(), self.Size, self.Size, Color( math.Rand( 10, 100), math.Rand( 100, 220), math.Rand( 240, 255), self.Alpha ) ) end
apache-2.0
cpascal/skynet
lualib/mysql.lua
31
15725
-- Copyright (C) 2012 Yichun Zhang (agentzh) -- Copyright (C) 2014 Chang Feng -- This file is modified version from https://github.com/openresty/lua-resty-mysql -- The license is under the BSD license. -- Modified by Cloud Wu (remove bit32 for lua 5.3) local socketchannel = require "socketchannel" local mysqlaux = require "mysqlaux.c" local crypt = require "crypt" local sub = string.sub local strgsub = string.gsub local strformat = string.format local strbyte = string.byte local strchar = string.char local strrep = string.rep local strunpack = string.unpack local strpack = string.pack local sha1= crypt.sha1 local setmetatable = setmetatable local error = error local tonumber = tonumber local new_tab = function (narr, nrec) return {} end local _M = { _VERSION = '0.13' } -- constants local STATE_CONNECTED = 1 local STATE_COMMAND_SENT = 2 local COM_QUERY = 0x03 local SERVER_MORE_RESULTS_EXISTS = 8 -- 16MB - 1, the default max allowed packet size used by libmysqlclient local FULL_PACKET_SIZE = 16777215 local mt = { __index = _M } -- mysql field value type converters local converters = new_tab(0, 8) for i = 0x01, 0x05 do -- tiny, short, long, float, double converters[i] = tonumber end converters[0x08] = tonumber -- long long converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year converters[0xf6] = tonumber -- newdecimal local function _get_byte2(data, i) return strunpack("<I2",data,i) end local function _get_byte3(data, i) return strunpack("<I3",data,i) end local function _get_byte4(data, i) return strunpack("<I4",data,i) end local function _get_byte8(data, i) return strunpack("<I8",data,i) end local function _set_byte2(n) return strpack("<I2", n) end local function _set_byte3(n) return strpack("<I3", n) end local function _set_byte4(n) return strpack("<I4", n) end local function _from_cstring(data, i) return strunpack("z", data, i) end local function _dumphex(bytes) return strgsub(bytes, ".", function(x) return strformat("%02x ", strbyte(x)) end) end local function _compute_token(password, scramble) if password == "" then return "" end --_dumphex(scramble) local stage1 = sha1(password) --print("stage1:", _dumphex(stage1) ) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) local i = 0 return strgsub(stage3,".", function(x) i = i + 1 -- ~ is xor in lua 5.3 return strchar(strbyte(x) ~ strbyte(stage1, i)) end) end local function _compose_packet(self, req, size) self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return packet end local function _send_packet(self, req, size) local sock = self.sock self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return socket.write(self.sock,packet) end local function _recv_packet(self,sock) local data = sock:read( 4) if not data then return nil, nil, "failed to receive packet header: " end local len, pos = _get_byte3(data, 1) if len == 0 then return nil, nil, "empty packet" end if len > self._max_packet_size then return nil, nil, "packet size too big: " .. len end local num = strbyte(data, pos) self.packet_no = num data = sock:read(len) if not data then return nil, nil, "failed to read packet content: " end local field_count = strbyte(data, 1) local typ if field_count == 0x00 then typ = "OK" elseif field_count == 0xff then typ = "ERR" elseif field_count == 0xfe then typ = "EOF" elseif field_count <= 250 then typ = "DATA" end return data, typ end local function _from_length_coded_bin(data, pos) local first = strbyte(data, pos) if not first then return nil, pos end if first >= 0 and first <= 250 then return first, pos + 1 end if first == 251 then return nil, pos + 1 end if first == 252 then pos = pos + 1 return _get_byte2(data, pos) end if first == 253 then pos = pos + 1 return _get_byte3(data, pos) end if first == 254 then pos = pos + 1 return _get_byte8(data, pos) end return false, pos + 1 end local function _from_length_coded_str(data, pos) local len len, pos = _from_length_coded_bin(data, pos) if len == nil then return nil, pos end return sub(data, pos, pos + len - 1), pos + len end local function _parse_ok_packet(packet) local res = new_tab(0, 5) local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) res.insert_id, pos = _from_length_coded_bin(packet, pos) res.server_status, pos = _get_byte2(packet, pos) res.warning_count, pos = _get_byte2(packet, pos) local message = sub(packet, pos) if message and message ~= "" then res.message = message end return res end local function _parse_eof_packet(packet) local pos = 2 local warning_count, pos = _get_byte2(packet, pos) local status_flags = _get_byte2(packet, pos) return warning_count, status_flags end local function _parse_err_packet(packet) local errno, pos = _get_byte2(packet, 2) local marker = sub(packet, pos, pos) local sqlstate if marker == '#' then -- with sqlstate pos = pos + 1 sqlstate = sub(packet, pos, pos + 5 - 1) pos = pos + 5 end local message = sub(packet, pos) return errno, message, sqlstate end local function _parse_result_set_header_packet(packet) local field_count, pos = _from_length_coded_bin(packet, 1) local extra extra = _from_length_coded_bin(packet, pos) return field_count, extra end local function _parse_field_packet(data) local col = new_tab(0, 2) local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) db, pos = _from_length_coded_str(data, pos) table, pos = _from_length_coded_str(data, pos) orig_table, pos = _from_length_coded_str(data, pos) col.name, pos = _from_length_coded_str(data, pos) orig_name, pos = _from_length_coded_str(data, pos) pos = pos + 1 -- ignore the filler charsetnr, pos = _get_byte2(data, pos) length, pos = _get_byte4(data, pos) col.type = strbyte(data, pos) --[[ pos = pos + 1 col.flags, pos = _get_byte2(data, pos) col.decimals = strbyte(data, pos) pos = pos + 1 local default = sub(data, pos + 2) if default and default ~= "" then col.default = default end --]] return col end local function _parse_row_data_packet(data, cols, compact) local pos = 1 local ncols = #cols local row if compact then row = new_tab(ncols, 0) else row = new_tab(0, ncols) end for i = 1, ncols do local value value, pos = _from_length_coded_str(data, pos) local col = cols[i] local typ = col.type local name = col.name if value ~= nil then local conv = converters[typ] if conv then value = conv(value) end end if compact then row[i] = value else row[name] = value end end return row end local function _recv_field_packet(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ ~= 'DATA' then return nil, "bad field packet type: " .. typ end -- typ == 'DATA' return _parse_field_packet(packet) end local function _recv_decode_packet_resp(self) return function(sock) -- don't return more than 2 results return true, (_recv_packet(self,sock)) end end local function _recv_auth_resp(self) return function(sock) local packet, typ, err = _recv_packet(self,sock) if not packet then --print("recv auth resp : failed to receive the result packet") error ("failed to receive the result packet"..err) --return nil,err end if typ == 'ERR' then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) --return nil, errno,msg, sqlstate end if typ == 'EOF' then error "old pre-4.1 authentication protocol not supported" end if typ ~= 'OK' then error "bad packet type: " end return true, true end end local function _mysql_login(self,user,password,database) return function(sockchannel) local packet, typ, err = sockchannel:response( _recv_decode_packet_resp(self) ) --local aat={} if not packet then error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end self.protocol_ver = strbyte(packet) local server_ver, pos = _from_cstring(packet, 2) if not server_ver then error "bad handshake initialization packet: bad server version" end self._server_ver = server_ver local thread_id, pos = _get_byte4(packet, pos) local scramble1 = sub(packet, pos, pos + 8 - 1) if not scramble1 then error "1st part of scramble not found" end pos = pos + 9 -- skip filler -- two lower bytes self._server_capabilities, pos = _get_byte2(packet, pos) self._server_lang = strbyte(packet, pos) pos = pos + 1 self._server_status, pos = _get_byte2(packet, pos) local more_capabilities more_capabilities, pos = _get_byte2(packet, pos) self._server_capabilities = self._server_capabilities|more_capabilities<<16 local len = 21 - 8 - 1 pos = pos + 1 + 10 local scramble_part2 = sub(packet, pos, pos + len - 1) if not scramble_part2 then error "2nd part of scramble not found" end local scramble = scramble1..scramble_part2 local token = _compute_token(password, scramble) local client_flags = 260047; local req = strpack("<I4I4c24zs1z", client_flags, self._max_packet_size, strrep("\0", 24), -- TODO: add support for charset encoding user, token, database) local packet_len = #req local authpacket=_compose_packet(self,req,packet_len) return sockchannel:request(authpacket,_recv_auth_resp(self)) end end local function _compose_query(self, query) self.packet_no = -1 local cmd_packet = strchar(COM_QUERY) .. query local packet_len = 1 + #query local querypacket = _compose_packet(self, cmd_packet, packet_len) return querypacket end local function read_result(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err --error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end if typ == 'OK' then local res = _parse_ok_packet(packet) if res and res.server_status&SERVER_MORE_RESULTS_EXISTS ~= 0 then return res, "again" end return res end if typ ~= 'DATA' then return nil, "packet type " .. typ .. " not supported" --error( "packet type " .. typ .. " not supported" ) end -- typ == 'DATA' local field_count, extra = _parse_result_set_header_packet(packet) local cols = new_tab(field_count, 0) for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self, sock) if not col then return nil, err, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end cols[i] = col end local packet, typ, err = _recv_packet(self, sock) if not packet then --error( err) return nil, err end if typ ~= 'EOF' then --error ( "unexpected packet type " .. typ .. " while eof packet is ".. "expected" ) return nil, "unexpected packet type " .. typ .. " while eof packet is ".. "expected" end -- typ == 'EOF' local compact = self.compact local rows = new_tab( 4, 0) local i = 0 while true do packet, typ, err = _recv_packet(self, sock) if not packet then --error (err) return nil, err end if typ == 'EOF' then local warning_count, status_flags = _parse_eof_packet(packet) if status_flags&SERVER_MORE_RESULTS_EXISTS ~= 0 then return rows, "again" end break end -- if typ ~= 'DATA' then -- return nil, 'bad row packet type: ' .. typ -- end -- typ == 'DATA' local row = _parse_row_data_packet(packet, cols, compact) i = i + 1 rows[i] = row end return rows end local function _query_resp(self) return function(sock) local res, err, errno, sqlstate = read_result(self,sock) if not res then local badresult ={} badresult.badresult = true badresult.err = err badresult.errno = errno badresult.sqlstate = sqlstate return true , badresult end if err ~= "again" then return true, res end local mulitresultset = {res} mulitresultset.mulitresultset = true local i =2 while err =="again" do res, err, errno, sqlstate = read_result(self,sock) if not res then return true, mulitresultset end mulitresultset[i]=res i=i+1 end return true, mulitresultset end end function _M.connect( opts) local self = setmetatable( {}, mt) local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB end self._max_packet_size = max_packet_size self.compact = opts.compact_arrays local database = opts.database or "" local user = opts.user or "" local password = opts.password or "" local channel = socketchannel.channel { host = opts.host, port = opts.port or 3306, auth = _mysql_login(self,user,password,database ), } -- try connect first only once channel:connect(true) self.sockchannel = channel return self end function _M.disconnect(self) self.sockchannel:close() setmetatable(self, nil) end function _M.query(self, query) local querypacket = _compose_query(self, query) local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request( querypacket, self.query_resp ) end function _M.server_ver(self) return self._server_ver end function _M.quote_sql_str( str) return mysqlaux.quote_sql_str(str) end function _M.set_compact_arrays(self, value) self.compact = value end return _M
mit
mqmaker/witi-openwrt
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/statistics/rrdtool.lua
69
15320
--[[ Luci statistics - rrdtool interface library / diagram model interpreter (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$ ]]-- module("luci.statistics.rrdtool", package.seeall) require("luci.statistics.datatree") require("luci.statistics.rrdtool.colors") require("luci.statistics.i18n") require("luci.model.uci") require("luci.util") require("luci.sys") local fs = require "nixio.fs" Graph = luci.util.class() function Graph.__init__( self, timespan, opts ) opts = opts or { } local uci = luci.model.uci.cursor() local sections = uci:get_all( "luci_statistics" ) -- options opts.timespan = timespan or sections.rrdtool.default_timespan or 900 opts.rrasingle = opts.rrasingle or ( sections.collectd_rrdtool.RRASingle == "1" ) opts.host = opts.host or sections.collectd.Hostname or luci.sys.hostname() opts.width = opts.width or sections.rrdtool.image_width or 400 opts.rrdpath = opts.rrdpath or sections.collectd_rrdtool.DataDir or "/tmp/rrd" opts.imgpath = opts.imgpath or sections.rrdtool.image_path or "/tmp/rrdimg" opts.rrdpath = opts.rrdpath:gsub("/$","") opts.imgpath = opts.imgpath:gsub("/$","") -- helper classes self.colors = luci.statistics.rrdtool.colors.Instance() self.tree = luci.statistics.datatree.Instance(opts.host) self.i18n = luci.statistics.i18n.Instance( self ) -- rrdtool default args self.args = { "-a", "PNG", "-s", "NOW-" .. opts.timespan, "-w", opts.width } -- store options self.opts = opts end function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance ) local t = self.opts.host .. "/" .. plugin if type(plugin_instance) == "string" and plugin_instance:len() > 0 then t = t .. "-" .. plugin_instance end t = t .. "/" .. dtype if type(dtype_instance) == "string" and dtype_instance:len() > 0 then t = t .. "-" .. dtype_instance end return t end function Graph.mkrrdpath( self, ... ) return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) ) end function Graph.mkpngpath( self, ... ) return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan ) end function Graph.strippngpath( self, path ) return path:sub( self.opts.imgpath:len() + 2 ) end function Graph._forcelol( self, list ) if type(list[1]) ~= "table" then return( { list } ) end return( list ) end function Graph._rrdtool( self, def, rrd ) -- prepare directory local dir = def[1]:gsub("/[^/]+$","") fs.mkdirr( dir ) -- construct commandline local cmdline = "rrdtool graph" -- copy default arguments to def stack for i, opt in ipairs(self.args) do table.insert( def, 1 + i, opt ) end -- construct commandline from def stack for i, opt in ipairs(def) do opt = opt .. "" -- force string if rrd then opt = opt:gsub( "{file}", rrd ) end if opt:match("[^%w]") then cmdline = cmdline .. " '" .. opt .. "'" else cmdline = cmdline .. " " .. opt end end -- execute rrdtool local rrdtool = io.popen( cmdline ) rrdtool:close() end function Graph._generic( self, opts, plugin, plugin_instance, dtype, index ) -- generated graph defs local defs = { } -- internal state variables local _args = { } local _sources = { } local _stack_neg = { } local _stack_pos = { } local _longest_name = 0 local _has_totals = false -- some convenient aliases local _ti = table.insert local _sf = string.format -- local helper: append a string.format() formatted string to given table function _tif( list, fmt, ... ) table.insert( list, string.format( fmt, ... ) ) end -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg function __def(source) local inst = source.sname local rrd = source.rrd local ds = source.ds if not ds or ds:len() == 0 then ds = "value" end _tif( _args, "DEF:%s_avg_raw=%s:%s:AVERAGE", inst, rrd, ds ) _tif( _args, "CDEF:%s_avg=%s_avg_raw,%s", inst, inst, source.transform_rpn ) if not self.opts.rrasingle then _tif( _args, "DEF:%s_min_raw=%s:%s:MIN", inst, rrd, ds ) _tif( _args, "CDEF:%s_min=%s_min_raw,%s", inst, inst, source.transform_rpn ) _tif( _args, "DEF:%s_max_raw=%s:%s:MAX", inst, rrd, ds ) _tif( _args, "CDEF:%s_max=%s_max_raw,%s", inst, inst, source.transform_rpn ) end _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst ) end -- local helper: create cdefs depending on source options like flip and overlay function __cdef(source) local prev -- find previous source, choose stack depending on flip state if source.flip then prev = _stack_neg[#_stack_neg] else prev = _stack_pos[#_stack_pos] end -- is first source in stack or overlay source: source_stk = source_nnl if not prev or source.overlay then -- create cdef statement for cumulative stack (no NaNs) and also -- for display (preserving NaN where no points should be displayed) _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname ) _tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname ) -- is subsequent source without overlay: source_stk = source_nnl + previous_stk else -- create cdef statement _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev ) _tif( _args, "CDEF:%s_plot=%s_avg,%s_stk,+", source.sname, source.sname, prev ) end -- create multiply by minus one cdef if flip is enabled if source.flip then -- create cdef statement: source_stk = source_stk * -1 _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname ) -- push to negative stack if overlay is disabled if not source.overlay then _ti( _stack_neg, source.sname ) end -- no flipping, push to positive stack if overlay is disabled elseif not source.overlay then -- push to positive stack _ti( _stack_pos, source.sname ) end -- calculate total amount of data if requested if source.total then _tif( _args, "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*", source.sname, source.sname, source.sname ) _tif( _args, "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+", source.sname, source.sname, source.sname ) end end -- local helper: create cdefs required for calculating total values function __cdef_totals() if _has_totals then _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname ) _ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" ) _ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" ) end end -- local helper: create line and area statements function __line(source) local line_color local area_color local legend local var -- find colors: try source, then opts.colors; fall back to random color if type(source.color) == "string" then line_color = source.color area_color = self.colors:from_string( line_color ) elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then line_color = opts.colors[source.name:gsub("[^%w]","_")] area_color = self.colors:from_string( line_color ) else area_color = self.colors:random() line_color = self.colors:to_string( area_color ) end -- derive area background color from line color area_color = self.colors:to_string( self.colors:faded( area_color ) ) -- choose source_plot or source_neg variable depending on flip state if source.flip then var = "neg" else var = "plot" end -- create legend legend = _sf( "%-" .. _longest_name .. "s", source.title ) -- create area if not disabled if not source.noarea then _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color ) end -- create line1 statement _tif( _args, "LINE%d:%s_%s#%s:%s", source.noarea and 2 or 1, source.sname, var, line_color, legend ) end -- local helper: create gprint statements function __gprint(source) local numfmt = opts.number_format or "%6.1lf" local totfmt = opts.totals_format or "%5.1lf%s" -- don't include MIN if rrasingle is enabled if not self.opts.rrasingle then _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt ) end -- always include AVERAGE _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt ) -- don't include MAX if rrasingle is enabled if not self.opts.rrasingle then _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt ) end -- include total count if requested else include LAST if source.total then _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt ) else _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt ) end end -- -- find all data sources -- -- find data types local data_types if dtype then data_types = { dtype } else data_types = opts.data.types or { } end if not ( dtype or opts.data.types ) then if opts.data.instances then for k, v in pairs(opts.data.instances) do _ti( data_types, k ) end elseif opts.data.sources then for k, v in pairs(opts.data.sources) do _ti( data_types, k ) end end end -- iterate over data types for i, dtype in ipairs(data_types) do -- find instances local data_instances if not opts.per_instance then if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then data_instances = opts.data.instances[dtype] else data_instances = self.tree:data_instances( plugin, plugin_instance, dtype ) end end if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end -- iterate over data instances for i, dinst in ipairs(data_instances) do -- construct combined data type / instance name local dname = dtype if dinst:len() > 0 then dname = dname .. "_" .. dinst end -- find sources local data_sources = { "value" } if type(opts.data.sources) == "table" then if type(opts.data.sources[dname]) == "table" then data_sources = opts.data.sources[dname] elseif type(opts.data.sources[dtype]) == "table" then data_sources = opts.data.sources[dtype] end end -- iterate over data sources for i, dsource in ipairs(data_sources) do local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource local altname = dtype .. "__" .. dsource --assert(dtype ~= "ping", dsname .. " or " .. altname) -- find datasource options local dopts = { } if type(opts.data.options) == "table" then if type(opts.data.options[dsname]) == "table" then dopts = opts.data.options[dsname] elseif type(opts.data.options[altname]) == "table" then dopts = opts.data.options[altname] elseif type(opts.data.options[dname]) == "table" then dopts = opts.data.options[dname] elseif type(opts.data.options[dtype]) == "table" then dopts = opts.data.options[dtype] end end -- store values _ti( _sources, { rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ), color = dopts.color or self.colors:to_string( self.colors:random() ), flip = dopts.flip or false, total = dopts.total or false, overlay = dopts.overlay or false, transform_rpn = dopts.transform_rpn or "0,+", noarea = dopts.noarea or false, title = dopts.title or nil, ds = dsource, type = dtype, instance = dinst, index = #_sources + 1, sname = ( #_sources + 1 ) .. dtype } ) -- generate datasource title _sources[#_sources].title = self.i18n:ds( _sources[#_sources] ) -- find longest name ... if _sources[#_sources].title:len() > _longest_name then _longest_name = _sources[#_sources].title:len() end -- has totals? if _sources[#_sources].total then _has_totals = true end end end end -- -- construct diagrams -- -- if per_instance is enabled then find all instances from the first datasource in diagram -- if per_instance is disabled then use an empty pseudo instance and use model provided values local instances = { "" } if opts.per_instance then instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type ) end -- iterate over instances for i, instance in ipairs(instances) do -- store title and vlabel _ti( _args, "-t" ) _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) ) _ti( _args, "-v" ) _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) ) if opts.y_max then _ti ( _args, "-u" ) _ti ( _args, opts.y_max ) end if opts.y_min then _ti ( _args, "-l" ) _ti ( _args, opts.y_min ) end if opts.units_exponent then _ti ( _args, "-X" ) _ti ( _args, opts.units_exponent ) end -- store additional rrd options if opts.rrdopts then for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end end -- create DEF statements for each instance for i, source in ipairs(_sources) do -- fixup properties for per instance mode... if opts.per_instance then source.instance = instance source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance ) end __def( source ) end -- create CDEF required for calculating totals __cdef_totals() -- create CDEF statements for each instance in reversed order for i, source in ipairs(_sources) do __cdef( _sources[1 + #_sources - i] ) end -- create LINE1, AREA and GPRINT statements for each instance for i, source in ipairs(_sources) do __line( source ) __gprint( source ) end -- prepend image path to arg stack _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) ) -- push arg stack to definition list _ti( defs, _args ) -- reset stacks _args = { } _stack_pos = { } _stack_neg = { } end return defs end function Graph.render( self, plugin, plugin_instance, is_index ) dtype_instances = dtype_instances or { "" } local pngs = { } -- check for a whole graph handler local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin local stat, def = pcall( require, plugin_def ) if stat and def and type(def.rrdargs) == "function" then -- temporary image matrix local _images = { } -- get diagram definitions for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do if not is_index or not opts.detail then _images[i] = { } -- get diagram definition instances local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i ) -- render all diagrams for j, def in ipairs( diagrams ) do -- remember image _images[i][j] = def[1] -- exec self:_rrdtool( def ) end end end -- remember images - XXX: fixme (will cause probs with asymmetric data) for y = 1, #_images[1] do for x = 1, #_images do table.insert( pngs, _images[x][y] ) end end end return pngs end
gpl-2.0
tianxiawuzhei/cocos-quick-lua
quick/framework/shortcodes.lua
19
13473
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------- -- @module shortcodes --[[-- shortcode ]] local c = cc local Node = c.Node -------------------------------- -- @module Node -- start -- -------------------------------- -- 在当前结点中加入一个子结点 -- @function [parent=#Node] add -- @param node child 要加入的结点 -- @param number zorder 要加入结点的Z值 -- @param number tag 要加入结点的tag -- @return Node#Node 当前结点 -- end -- function Node:add(child, zorder, tag) self:addChild(child, zorder or child:getLocalZOrder(), tag or child:getTag()) return self end -- start -- -------------------------------- -- 把当前结点作为一个子结点加到target中 -- @function [parent=#Node] addTo -- @param node target 想作为其子结点的结点 -- @param number zorder 当前结点的Z值 -- @param number tag 当前结点的tag -- @return Node#Node 当前结点 -- end -- function Node:addTo(target, zorder, tag) target:addChild(self, zorder or self:getLocalZOrder(), tag or self:getTag()) return self end -- start -- -------------------------------- -- 显示当前结点,让当前结点可显示 -- @function [parent=#Node] show -- @return Node#Node 当前结点 -- end -- function Node:show() self:setVisible(true) return self end -- start -- -------------------------------- -- 隐藏当前结点,让当前结点不可显示 -- @function [parent=#Node] hide -- @return Node#Node 当前结点 -- end -- function Node:hide() self:setVisible(false) return self end -- start -- -------------------------------- -- 设置当前结点的位置 -- @function [parent=#Node] pos -- @param number x X值 -- @param number y Y值 -- @return Node#Node 当前结点 -- end -- function Node:pos(x, y) self:setPosition(x, y) return self end -- start -- -------------------------------- -- 设置当前结点在屏幕的中心 -- @function [parent=#Node] center -- @return Node#Node 当前结点 -- end -- function Node:center() self:setPosition(display.cx, display.cy) return self end -- start -- -------------------------------- -- 设置当前结点的缩放值 -- @function [parent=#Node] scale -- @param number scale 要缩放的值 -- @return Node#Node 当前结点 -- end -- function Node:scale(scale) self:setScale(scale) return self end -- start -- -------------------------------- -- 设置当前结点的旋转角度值 -- @function [parent=#Node] rotation -- @param number r 旋转角度 -- @return Node#Node 当前结点 -- end -- function Node:rotation(r) self:setRotation(r) return self end -- start -- -------------------------------- -- 设置当前结点的大小 -- @function [parent=#Node] size -- @param mixed width 宽度或cc.size表 -- @param number height 高度 -- @return Node#Node 当前结点 -- end -- function Node:size(width, height) if type(width) == "table" then self:setContentSize(width) else self:setContentSize(cc.size(width, height)) end return self end -- start -- -------------------------------- -- 设置当前结点的透明度, 0到255,0为完全透明 -- @function [parent=#Node] opacity -- @param number opacity 透明度 -- @return Node#Node 当前结点 -- end -- function Node:opacity(opacity) self:setOpacity(opacity) return self end -- start -- -------------------------------- -- 设置当前结点z值 -- @function [parent=#Node] zorder -- @param number z z值 -- @return Node#Node 当前结点 -- end -- function Node:zorder(z) self:setLocalZOrder(z) return self end -------------------------------- -- @module Sprite local Sprite = c.Sprite Sprite.playOnce = Sprite.playAnimationOnce Sprite.playForever = Sprite.playAnimationForever -- start -- -------------------------------- -- 设置当前精灵的显示帧 -- @function [parent=#Sprite] displayFrame -- @param mixed frame 要显示的图片名或图片帧的frame -- @return Sprite#Sprite 当前精灵 -- end -- function Sprite:displayFrame(frame) self:setSpriteFrame(frame) return self end -- start -- -------------------------------- -- 在X方向上翻转当前精灵 -- @function [parent=#Sprite] flipX -- @param boolean b 是否翻转 -- @return Sprite#Sprite 当前精灵 -- end -- function Sprite:flipX(b) self:setFlippedX(b) return self end -- start -- -------------------------------- -- 在Y方向上翻转当前精灵 -- @function [parent=#Sprite] flipY -- @param boolean b 是否翻转 -- @return Sprite#Sprite 当前精灵 -- end -- function Sprite:flipY(b) self:setFlippedY(b) return self end -------------------------------- -- @module Layer -- Layer local Layer = c.Layer -- start -- -------------------------------- -- 在层上注册触摸监听 -- @function [parent=#Layer] onTouch -- @param function listener 监听函数 -- @return Layer#Layer 当前层 --[[-- 在层上注册触摸监听 ]] -- end -- function Layer:onTouch(listener) if USE_DEPRECATED_EVENT_ARGUMENTS then self:addNodeEventListener(c.NODE_TOUCH_EVENT, function(event) return listener(event.name, event.x, event.y, event.prevX, event.prevY) end) else self:addNodeEventListener(c.NODE_TOUCH_EVENT, listener) end return self end -- start -- -------------------------------- -- 设置层的触摸是否打开 -- @function [parent=#Layer] enableTouch -- @param boolean enabled 是否打开触摸 -- @return Layer#Layer 当前层 -- end -- function Layer:enableTouch(enabled) self:setTouchEnabled(enabled) return self end -- start -- -------------------------------- -- 在层上注册键盘监听 -- @function [parent=#Layer] onKeypad -- @param function listener 监听函数 -- @return Layer#Layer 当前层 -- end -- function Layer:onKeypad(listener) if USE_DEPRECATED_EVENT_ARGUMENTS then self:addNodeEventListener(c.KEYPAD_EVENT, function(event) return listener(event.name) end) else self:addNodeEventListener(c.KEYPAD_EVENT, listener) end return self end -- start -- -------------------------------- -- 设置层的键盘事件是否打开 -- @function [parent=#Layer] enableKeypad -- @param boolean enabled 是否打开键盘事件 -- @return Layer#Layer 当前层 -- end -- function Layer:enableKeypad(enabled) self:setKeypadEnabled(enabled) return self end -- start -- -------------------------------- -- 在层上注册重力感应监听 -- @function [parent=#Layer] onAccelerate -- @param function listener 监听函数 -- @return Layer#Layer 当前层 -- end -- function Layer:onAccelerate(listener) if USE_DEPRECATED_EVENT_ARGUMENTS then self:addNodeEventListener(c.ACCELERATE_EVENT, function(event) return listener(event.x, event.y, event.z, event.timestamp) end) else self:addNodeEventListener(c.ACCELERATE_EVENT, listener) end return self end -- start -- -------------------------------- -- 设置层的重力感应事件是否打开 -- @function [parent=#Layer] enableAccelerometer -- @param boolean enabled 是否打开加速度事件 -- @return Layer#Layer 当前层 -- end -- function Layer:enableAccelerometer(enabled) self:setAccelerometerEnabled(enabled) return self end -- actions -- start -- -------------------------------- -- 停止结点的所有动作 -- @function [parent=#Node] stop -- @return Node#Node 当前结点 -- end -- function Node:stop() self:stopAllActions() return self end -- start -- -------------------------------- -- 渐显动画 -- @function [parent=#Node] fadeIn -- @param number time 渐显时间 -- @return Node#Node 当前结点 -- end -- function Node:fadeIn(time) self:runAction(cc.FadeIn:create(time)) return self end -- start -- -------------------------------- -- 渐隐动画 -- @function [parent=#Node] fadeOut -- @param number time 渐隐时间 -- @return Node#Node 当前结点 -- end -- function Node:fadeOut(time) self:runAction(cc.FadeOut:create(time)) return self end -- start -- -------------------------------- -- 渐变到一个固定透明度 -- @function [parent=#Node] fadeTo -- @param number time 渐变时间 -- @param number opacity 最终的透明度 -- @return Node#Node 当前结点 -- end -- function Node:fadeTo(time, opacity) self:runAction(cc.FadeTo:create(time, opacity)) return self end -- start -- -------------------------------- -- 在一段时间内移动结点到特定位置 -- @function [parent=#Node] moveTo -- @param number time 移动时间 -- @param number x 要移动到的X点 -- @param number y 要移动到的Y点 -- @return Node#Node 当前结点 -- end -- function Node:moveTo(time, x, y) self:runAction(cc.MoveTo:create(time, cc.p(x or self:getPositionX(), y or self:getPositionY()))) return self end -- start -- -------------------------------- -- 在一段时间内移动相对位置 -- @function [parent=#Node] moveBy -- @param number time 移动时间 -- @param number x 要移动的相对X值 -- @param number y 要移动的相对Y值 -- @return Node#Node 当前结点 -- end -- function Node:moveBy(time, x, y) self:runAction(cc.MoveBy:create(time, cc.p(x or 0, y or 0))) return self end -- start -- -------------------------------- -- 在一段时间内旋转的角度 -- @function [parent=#Node] rotateTo -- @param number time 移动时间 -- @param number rotation 旋转的角度 -- @return Node#Node 当前结点 -- end -- function Node:rotateTo(time, rotation) self:runAction(cc.RotateTo:create(time, rotation)) return self end -- start -- -------------------------------- -- 在一段时间内旋转的相对角度 -- @function [parent=#Node] rotateBy -- @param number time 移动时间 -- @param number rotation 旋转的相对角度 -- @return Node#Node 当前结点 -- end -- function Node:rotateBy(time, rotation) self:runAction(cc.RotateBy:create(time, rotation)) return self end -- start -- -------------------------------- -- 在一段时间内缩放 -- @function [parent=#Node] scaleTo -- @param number time 移动时间 -- @param number scale 缩放的值 -- @return Node#Node 当前结点 -- end -- function Node:scaleTo(time, scale) self:runAction(cc.ScaleTo:create(time, scale)) return self end -- start -- -------------------------------- -- 在一段时间内的相对缩放 -- @function [parent=#Node] scaleBy -- @param number time 移动时间 -- @param number scale 相对缩放的值 -- @return Node#Node 当前结点 -- end -- function Node:scaleBy(time, scale) self:runAction(cc.ScaleBy:create(time, scale)) return self end -- start -- -------------------------------- -- 在一段时间内倾斜的大小 -- @function [parent=#Node] skewTo -- @param number time 移动时间 -- @param number sx 倾斜的X值 -- @param number sy 倾斜的Y值 -- @return Node#Node 当前结点 -- end -- function Node:skewTo(time, sx, sy) self:runAction(cc.SkewTo:create(time, sx or self:getSkewX(), sy or self:getSkewY())) return self end -- start -- -------------------------------- -- 在一段时间内倾斜的相对大小 -- @function [parent=#Node] skewBy -- @param number time 移动时间 -- @param number sx 倾斜的相对X值 -- @param number sy 倾斜的相对Y值 -- @return Node#Node 当前结点 -- end -- function Node:skewBy(time, sx, sy) self:runAction(cc.SkewBy:create(time, sx or 0, sy or 0)) return self end -- start -- -------------------------------- -- 在一段时间内染色 -- @function [parent=#Node] tintTo -- @param number time 移动时间 -- @param number r 染色的R值 -- @param number g 染色的G值 -- @param number b 染色的B值 -- @return Node#Node 当前结点 -- end -- function Node:tintTo(time, r, g, b) self:runAction(cc.TintTo:create(time, r or 0, g or 0, b or 0)) return self end -- start -- -------------------------------- -- 在一段时间内相对染色 -- @function [parent=#Node] tintBy -- @param number time 移动时间 -- @param number r 染色的相对R值 -- @param number g 染色的相对G值 -- @param number b 染色的相对B值 -- @return Node#Node 当前结点 -- end -- function Node:tintBy(time, r, g, b) self:runAction(cc.TintBy:create(time, r or 0, g or 0, b or 0)) return self end
mit
czlc/skynet
examples/login/logind.lua
1
2435
local login = require "snax.loginserver" local crypt = require "skynet.crypt" local skynet = require "skynet" local server = { host = "127.0.0.1", port = 8001, multilogin = false, -- disallow multilogin name = "login_master", -- ²»ÒªºÍ skynet ÆäËü·þÎñÖØÃû } local server_list = {} local user_online = {} local user_login = {} -- Èç¹ûÑé֤ͨ¹ý£¬ÐèÒª·µ»ØÓû§Ï£Íû½øÈëµÄµÇ½µã£¨µÇ½µã¿ÉÒÔÊǰüº¬ÔÚ token ÄÚÓÉÓû§×ÔÐоö¶¨,Ò²¿ÉÒÔÔÚÕâÀïʵÏÖÒ»¸ö¸ºÔؾùºâÆ÷À´Ñ¡Ôñ£©£»ÒÔ¼°Óû§Ãû¡£ -- login step 4.1: L УÑétoken µÄºÏ·¨ÐÔ£¨´Ë´¦ÓпÉÄÜÐèÒª L ºÍ A ×öÒ»´ÎÈ·ÈÏ£©¡£ -- slave function server.auth_handler(token) -- the token is base64(user)@base64(server):base64(password) local user, server, password = token:match("([^@]+)@([^:]+):(.+)") user = crypt.base64decode(user) server = crypt.base64decode(server) password = crypt.base64decode(password) assert(password == "password", "Invalid password") return server, user end -- ´¦Àíµ±Óû§ÒѾ­Ñé֤ͨ¹ýºó£¬¸ÃÈçºÎ֪ͨ¾ßÌåµÄµÇ½µã£¨server £© -- ¿ò¼Ü»á½»¸øÄãÓû§Ãû£¨uid£©ºÍÒѾ­°²È«½»»»µ½µÄͨѶÃÜÔ¿¡£ÄãÐèÒª°ÑËüÃǽ»¸øµÇ½µã£¬²¢µÃµ½È·ÈÏ£¨µÈ´ýµÇ½µã×¼±¸ºÃºó£©²Å¿ÉÒÔ·µ»Ø¡£ -- master function server.login_handler(server, uid, secret) print(string.format("%s@%s is login, secret is %s", uid, server, crypt.hexencode(secret))) local gameserver = assert(server_list[server], "Unknown server") -- login step 4.2: L УÑéµÇ½µãÊÇ·ñ´æÔÚ -- only one can login, because disallow multilogin local last = user_online[uid] -- login step 5:£¨¿ÉÑ¡²½Ö裩L ¼ì²é C ÊÇ·ñÒѾ­µÇ½£¬Èç¹ûÒѾ­µÇ½£¬ÏòËüËùÔڵĵǽµã£¨¿ÉÒÔÊÇÒ»¸ö£¬Ò²¿ÉÒÔÊǶà¸ö£©·¢ËÍÐźţ¬µÈ´ýµÇ½µãÈ·ÈÏ¡£Í¨³£Õâ¸ö²½Öè¿ÉÒÔ½«ÒѵǽµÄÓû§µÇ³ö¡£ if last then skynet.call(last.address, "lua", "kick", uid, last.subid) end if user_online[uid] then error(string.format("user %s is already online", uid)) end -- login step 6:L Ïò G1 ·¢ËÍÓû§ C ½«µÇ½µÄÇëÇ󣬲¢Í¬Ê±·¢ËÍ secret ¡£ local subid = tostring(skynet.call(gameserver, "lua", "login", uid, secret)) user_online[uid] = { address = gameserver, subid = subid , server = server} return subid end local CMD = {} -- ¶¯Ì¬×¢²áеĵǽµã function CMD.register_gate(server, address) server_list[server] = address end function CMD.logout(uid, subid) local u = user_online[uid] if u then print(string.format("%s@%s is logout", uid, u.server)) user_online[uid] = nil end end -- master function server.command_handler(command, ...) local f = assert(CMD[command]) return f(...) end login(server)
mit
robert00s/koreader
frontend/ui/gesturerange.lua
7
2083
local TimeVal = require("ui/timeval") local GestureRange = { -- gesture matching type ges = nil, -- spatial range limits the gesture emitting position range = nil, -- temproal range limits the gesture emitting rate rate = nil, -- scale limits of this gesture scale = nil, } function GestureRange:new(from_o) local o = from_o or {} setmetatable(o, self) self.__index = self return o end function GestureRange:match(gs) if gs.ges ~= self.ges then return false end if self.range then -- sometimes widget dimenension is not available when creating a gesturerage -- for some action, now we accept a range function that will be later called -- and the result of which will be used to check gesture match -- e.g. range = function() return self.dimen end -- for inputcontainer given that the x and y field of `self.dimen` is only -- filled when the inputcontainer is painted into blitbuffer local range if type(self.range) == "function" then range = self.range() else range = self.range end if not range:contains(gs.pos) then return false end end if self.rate then -- This filed restraints the upper limit rate(matches per second). -- It's most useful for e-ink devices with less powerfull CPUs and -- screens that cannot handle gesture events that otherwise will be -- generated local last_time = self.last_time or TimeVal:new{} if gs.time - last_time > TimeVal:new{usec = 1000000 / self.rate} then self.last_time = gs.time else return false end end if self.scale then local scale = gs.distance or gs.span if self.scale[1] > scale or self.scale[2] < scale then return false end end if self.direction then if self.direction ~= gs.direction then return false end end return true end return GestureRange
agpl-3.0
Movimento5StelleLazio/WebMCP
framework/env/ui/form_element.lua
3
2498
--[[-- ui.form_element( args, -- external arguments { -- options for this function call fetch_value = fetch_value_flag, -- true causes automatic determination of args.value, if nil fetch_record = fetch_record_flag, -- true causes automatic determination of args.record, if nil disable_label_for_id = disable_label_for_id_flag, -- true suppresses automatic setting of args.attr.id for a HTML label_for reference }, function(args) ... -- program code end ) This function helps other form helpers by preprocessing arguments passed to the helper, e.g. fetching a value from a record stored in a state-table of the currently active slot. --]]-- -- TODO: better documentation function ui.form_element(args, extra_args, func) local args = table.new(args) if extra_args then for key, value in pairs(extra_args) do args[key] = value end end local slot_state = slot.get_state_table() args.html_name = args.html_name or args.name if args.fetch_value then if args.value == nil then if not args.record and slot_state then args.record = slot_state.form_record end if args.record then args.value = args.record[args.name] end else args.value = nihil.lower(args.value) end elseif args.fetch_record then if not args.record and slot_state then args.record = slot_state.form_record end end if args.html_name and not args.readonly and slot_state.form_readonly == false then args.readonly = false local prefix if args.html_name_prefix == nil then prefix = slot_state.html_name_prefix else prefix = args.html_name_prefix end if prefix then args.html_name = prefix .. args.html_name end else args.readonly = true end if args.label then if not args.disable_label_for_id then if not args.attr then args.attr = { id = ui.create_unique_id() } elseif not args.attr.id then args.attr.id = ui.create_unique_id() end end if not args.label_attr then args.label_attr = { class = "ui_field_label" } elseif not args.label_attr.class then args.label_attr.class = "ui_field_label" end end ui.container{ auto_args = args, content = function() return func(args) end } end
mit
bigdogmat/wire
lua/wire/stools/turret.lua
1
4086
WireToolSetup.setCategory( "Other" ) WireToolSetup.open( "turret", "Turret", "gmod_wire_turret", nil, "Turrets" ) -- Precache these sounds.. Sound( "ambient.electrical_zap_3" ) Sound( "NPC_FloorTurret.Shoot" ) -- Add Default Language translation (saves adding it to the txt files) if CLIENT then language.Add( "tool.wire_turret.name", "Turret" ) language.Add( "tool.wire_turret.desc", "Throws bullets at things" ) language.Add( "Tool_wire_turret_spread", "Bullet Spread" ) language.Add( "Tool_wire_turret_numbullets", "Bullets per Shot" ) language.Add( "Tool_wire_turret_force", "Bullet Force" ) language.Add( "Tool_wire_turret_sound", "Shoot Sound" ) language.Add( "Tool_wire_turret_tracernum", "Tracer Every x Bullets:" ) TOOL.Information = { { name = "left", text = "Create/Update " .. TOOL.Name } } end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 20 ) TOOL.ClientConVar = { delay = 0.05, force = 1, sound = 0, damage = 10, spread = 0, numbullets = 1, automatic = 1, tracer = "Tracer", tracernum = 1, model = "models/weapons/w_smg1.mdl" } TOOL.GhostAngle = Angle(-90,0,0) TOOL.GetGhostMin = function() return -2 end if SERVER then function TOOL:GetConVars() return self:GetClientNumber("delay"), self:GetClientNumber("damage"), self:GetClientNumber("force"), self:GetClientInfo("sound"), self:GetClientNumber("numbullets"), self:GetClientNumber("spread"), self:GetClientInfo("tracer"), self:GetClientNumber("tracernum") end end local ValidTurretModels = { ["models/weapons/w_smg1.mdl"] = true, ["models/weapons/w_smg_mp5.mdl"] = true, ["models/weapons/w_smg_mac10.mdl"] = true, ["models/weapons/w_rif_m4a1.mdl"] = true, ["models/weapons/w_357.mdl"] = true, ["models/weapons/w_shot_m3super90.mdl"] = true } function TOOL:GetModel() local model = WireToolObj.GetModel(self) return ValidTurretModels[model] and model or "models/weapons/w_smg1.mdl" end function TOOL.BuildCPanel( CPanel ) WireToolHelpers.MakePresetControl(CPanel, "wire_turret") -- Shot sounds local weaponSounds = {Label = "#Tool_wire_turret_sound", MenuButton = 0, Options={}, CVars = {}} weaponSounds["Options"]["#No Weapon"] = { wire_turret_sound = "" } weaponSounds["Options"]["#Pistol"] = { wire_turret_sound = "Weapon_Pistol.Single" } weaponSounds["Options"]["#SMG"] = { wire_turret_sound = "Weapon_SMG1.Single" } weaponSounds["Options"]["#AR2"] = { wire_turret_sound = "Weapon_AR2.Single" } weaponSounds["Options"]["#Shotgun"] = { wire_turret_sound = "Weapon_Shotgun.Single" } weaponSounds["Options"]["#Floor Turret"] = { wire_turret_sound = "NPC_FloorTurret.Shoot" } weaponSounds["Options"]["#Airboat Heavy"] = { wire_turret_sound = "Airboat.FireGunHeavy" } weaponSounds["Options"]["#Zap"] = { wire_turret_sound = "ambient.electrical_zap_3" } CPanel:AddControl("ComboBox", weaponSounds ) WireDermaExts.ModelSelect(CPanel, "wire_turret_model", list.Get( "WireTurretModels" ), 2) -- Tracer local TracerType = {Label = "#Tracer", MenuButton = 0, Options={}, CVars = {}} TracerType["Options"]["#Default"] = { wire_turret_tracer = "Tracer" } TracerType["Options"]["#AR2 Tracer"] = { wire_turret_tracer = "AR2Tracer" } TracerType["Options"]["#Airboat Tracer"] = { wire_turret_tracer = "AirboatGunHeavyTracer" } TracerType["Options"]["#Laser"] = { wire_turret_tracer = "LaserTracer" } CPanel:AddControl("ComboBox", TracerType ) -- Various controls that you should play with! if game.SinglePlayer() then CPanel:NumSlider("#Tool_wire_turret_numbullets", "wire_turret_numbullets", 1, 10, 0) end CPanel:NumSlider("#Damage", "wire_turret_damage", 0, 100, 0) CPanel:NumSlider("#Tool_wire_turret_spread", "wire_turret_spread", 0, 1.0, 2) CPanel:NumSlider("#Tool_wire_turret_force", "wire_turret_force", 0, 500, 1) -- The delay between shots. if game.SinglePlayer() then CPanel:NumSlider("#Delay", "wire_turret_delay", 0.01, 1.0, 2) CPanel:NumSlider("#Tool_wire_turret_tracernum", "wire_turret_tracernum", 0, 15, 0) else CPanel:NumSlider("#Delay", "wire_turret_delay", 0.05, 1.0, 2) end end
apache-2.0
Weol/WUMA
lua/wuma/hooks.lua
1
7842
WUMA = WUMA or {} --Hooks WUMA.USERRESTRICTIONADDED = "WUMAUserRestrictionAdded" WUMA.USERRESTRICTIONREMOVED = "WUMAUserRestrictionRemoved" function WUMA.PlayerSpawnSENT(ply, sent) --WUMADebug("WUMA.PlayerSpawnSENT(%s, %s)", tostring(ply) or "NIL", tostring(sent) or "NIL") if not ply or not sent then return end if (ply:CheckRestriction("entity", sent) == false) then return false end if (ply:CheckLimit("sents", sent) == false) then return false end end hook.Add("PlayerSpawnSENT", "WUMAPlayerSpawnSENT", WUMA.PlayerSpawnSENT, -1) function WUMA.PlayerSpawnedSENT(ply, ent) --WUMADebug("WUMA.PlayerSpawnedSENT(%s, %s)", tostring(ply) or "NIL", tostring(sent) or "NIL") if not ply or not ent then return end ply:AddCount("sents", ent, ent:GetClass()) end hook.Add("PlayerSpawnedSENT", "WUMAPlayerSpawnedProp", WUMA.PlayerSpawnedSENT, -2) function WUMA.PlayerSpawnProp(ply, mdl) --WUMADebug("WUMA.PlayerSpawnProp(%s, %s)", tostring(ply) or "NIL", tostring(mdl) or "NIL") if not ply or not mdl then return end mdl = string.lower(mdl) --Models are alwyas lowercase if (ply:CheckRestriction("prop", mdl) == false) then return false end if (ply:CheckLimit("props", mdl) == false) then return false end end hook.Add("PlayerSpawnProp", "WUMAPlayerSpawnProp", WUMA.PlayerSpawnProp, -1) function WUMA.PlayerSpawnedProp(ply, model, ent) --WUMADebug("WUMA.PlayerSpawnedProp(%s, %s, %s)", tostring(ply) or "NIL", tostring(model) or "NIL", tostring(ent) or "NIL") if not ply or not model or not ent then return end model = string.lower(model) --Models are alwyas lowercase ply:AddCount("props", ent, model) end hook.Add("PlayerSpawnedProp", "WUMAPlayerSpawnedProp", WUMA.PlayerSpawnedProp, -2) function WUMA.CanTool(ply, tr, tool) --WUMADebug("WUMA.CanTool(%s, %s, %s)", tostring(ply) or "NIL", tostring(tr) or "NIL", tostring(tool) or "NIL") if not ply or not tool then return end return ply:CheckRestriction("tool", tool) end hook.Add("CanTool", "WUMACanTool", WUMA.CanTool, -1) function WUMA.PlayerUse(ply, ent) --WUMADebug("WUMA.PlayerUse(%s, %s)", tostring(ply) or "NIL", tostring(ent) or "NIL") if not ply or not ent then return end if ent:GetTable().VehicleName then ent = ent:GetTable().VehicleName else ent = ent:GetClass() end return ply:CheckRestriction("use", ent) end hook.Add("PlayerUse", "WUMAPlayerUse", WUMA.PlayerUse) function WUMA.PlayerSpawnEffect(ply, mdl) --WUMADebug("WUMA.PlayerSpawnEffect(%s, %s)", tostring(ply) or "NIL", tostring(mdl) or "NIL") if not ply or not mdl then return end mdl = string.lower(mdl) --Models are alwyas lowercase if (ply:CheckRestriction("effect", mdl) == false) then return false end if (ply:CheckLimit("effects", mdl) == false) then return false end end hook.Add("PlayerSpawnEffect", "WUMAPlayerSpawnEffect", WUMA.PlayerSpawnEffect, -1) function WUMA.PlayerSpawnedEffect(ply, model, ent) --WUMADebug("WUMA.PlayerSpawnedEffect(%s, %s, %s)", tostring(ply) or "NIL", tostring(model) or "NIL", tostring(ent) or "NIL") if not ply or not model or not ent then return end model = string.lower(model) --Models are alwyas lowercase ply:AddCount("effects", ent, model) end hook.Add("PlayerSpawnedEffect", "WUMAPlayerSpawnedEffect", WUMA.PlayerSpawnedEffect, -2) function WUMA.PlayerSpawnNPC(ply, npc, weapon) --WUMADebug("WUMA.PlayerSpawnNPC(%s, %s, %s)", tostring(ply) or "NIL", tostring(npc) or "NIL", tostring(weapon) or "NIL") if not ply or not npc then return end if (ply:CheckRestriction("npc", npc) == false) then return false end if (ply:CheckLimit("npcs", npc) == false) then return false end end hook.Add("PlayerSpawnNPC", "WUMAPlayerSpawnNPC", WUMA.PlayerSpawnNPC, -1) function WUMA.PlayerSpawnedNPC(ply, ent) --WUMADebug("WUMA.PlayerSpawnedNPC(%s, %s)", tostring(ply) or "NIL", tostring(ent) or "NIL") if not ply or not ent then return end ply:AddCount("npcs", ent, ent:GetClass()) end hook.Add("PlayerSpawnedNPC", "WUMAPlayerSpawnedNPC", WUMA.PlayerSpawnedNPC, -2) function WUMA.PlayerSpawnRagdoll(ply, mdl) --WUMADebug("WUMA.PlayerSpawnRagdoll(%s, %s)", tostring(ply) or "NIL", tostring(mdl) or "NIL") if not ply or not mdl then return end mdl = string.lower(mdl) --Models are alwyas lowercase if (ply:CheckRestriction("ragdoll", mdl) == false) then return false end if (ply:CheckLimit("ragdolls", mdl) == false) then return false end end hook.Add("PlayerSpawnRagdoll", "WUMAPlayerSpawnRagdoll", WUMA.PlayerSpawnRagdoll, -1) function WUMA.PlayerSpawnedRagdoll(ply, model, ent) --WUMADebug("WUMA.PlayerSpawnedRagdoll(%s, %s, %s)", tostring(ply) or "NIL", tostring(model) or "NIL", tostring(ent) or "NIL") if not ply or not model or not ent then return end model = string.lower(model) --Models are alwyas lowercase ply:AddCount("ragdolls", ent, model) end hook.Add("PlayerSpawnedRagdoll", "WUMAPlayerSpawnedRagdoll", WUMA.PlayerSpawnedRagdoll, -2) function WUMA.PlayerSpawnSWEP(ply, class, weapon) --WUMADebug("WUMA.PlayerSpawnSWEP(%s, %s, %s)", tostring(ply) or "NIL", tostring(class) or "NIL", tostring(weapon) or "NIL") if not ply or not class then return end if (ply:CheckRestriction("swep", class) == false) then return false end if (ply:CheckLimit("sents", class) == false) then return false end end hook.Add("PlayerSpawnSWEP", "WUMAPlayerSpawnSWEP", WUMA.PlayerSpawnSWEP, -1) function WUMA.PlayerGiveSWEP(ply, class, weapon) --WUMADebug("WUMA.PlayerGiveSWEP(%s, %s, %s)", tostring(ply) or "NIL", tostring(class) or "NIL", tostring(weapon) or "NIL") if not ply or not class then return end if (ply:CheckRestriction("swep", class) == false) then return false end ply:DisregardNextPickup(class) end hook.Add("PlayerGiveSWEP", "WUMAPlayerGiveSWEP", WUMA.PlayerGiveSWEP, -1) function WUMA.PlayerSpawnedSWEP(ply, ent) --WUMADebug("WUMA.PlayerSpawnedSWEP(%s, %s)", tostring(ply) or "NIL", tostring(ent) or "NIL") if not ply or not ent then return end ply:AddCount("sents", ent, ent:GetClass()) end hook.Add("PlayerSpawnedSWEP", "WUMAPlayerSpawnedSWEP", WUMA.PlayerSpawnedSWEP, -2) local pickup_last function WUMA.PlayerCanPickupWeapon(ply, weapon) --WUMADebug("WUMA.PlayerCanPickupWeapon(%s, %s)", tostring(ply) or "NIL", tostring(weapon) or "NIL") if not ply or not weapon then return end if ply:ShouldDisregardPickup(weapon:GetClass()) then return end return ply:CheckRestriction("pickup", weapon:GetClass()) end hook.Add("PlayerCanPickupWeapon", "WUMAPlayerCanPickupWeapon", WUMA.PlayerCanPickupWeapon, -1) function WUMA.PlayerSpawnVehicle(ply, mdl, name, vehicle_table) --WUMADebug("WUMA.PlayerSpawnVehicle(%s, %s, %s, %s)", tostring(ply) or "NIL", tostring(mdl) or "NIL", tostring(name) or "NIL", tostring(vehicle_table) or "NIL") if not ply or not name then return end if (ply:CheckRestriction("vehicle", name) == false) then return false end if (ply:CheckLimit("vehicles", name) == false) then return false end end hook.Add("PlayerSpawnVehicle", "WUMAPlayerSpawnVehicle", WUMA.PlayerSpawnVehicle, -1) function WUMA.PlayerSpawnedVehicle(ply, ent) --WUMADebug("WUMA.PlayerSpawnedVehicle(%s, %s)", tostring(ply) or "NIL", tostring(ent) or "NIL") if not ply or not ent then return end ply:AddCount("vehicles", ent, ent:GetTable().VehicleName) end hook.Add("PlayerSpawnedVehicle", "WUMAPlayerSpawnedVehicle", WUMA.PlayerSpawnedVehicle, -2) function WUMA.PlayerCanProperty(ply, property, ent) --WUMADebug("WUMA.PlayerSpawnedVehicle(%s, %s, %s)", tostring(ply) or "NIL", tostring(property) or "NIL", tostring(ent) or "NIL") if not ply or not property then return end if (ply:CheckRestriction("property", property) == false) then return false end end hook.Add( "CanProperty", "WUMAPlayerCanProperty", WUMA.PlayerCanProperty, -1)
apache-2.0
dicebox/minetest-france
mods/moreblocks/crafting.lua
1
10671
--[[ More Blocks: crafting recipes Copyright (c) 2011-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] minetest.register_craft({ output = "default:stick", recipe = {{"default:dry_shrub"},} }) minetest.register_craft({ output = "default:stick", recipe = {{"default:sapling"},} }) minetest.register_craft({ output = "default:stick", recipe = {{"default:junglesapling"},} }) minetest.register_craft({ output = "default:wood", recipe = { {"default:stick", "default:stick"}, {"default:stick", "default:stick"}, } }) minetest.register_craft({ output = "default:dirt_with_grass", type = "shapeless", recipe = {"default:junglegrass", "default:dirt"}, }) minetest.register_craft({ output = "default:dirt_with_grass", type = "shapeless", recipe = {"default:mese", "default:dirt"}, }) minetest.register_craft({ output = "default:mossycobble", type = "shapeless", recipe = {"default:junglegrass", "default:cobble"}, }) minetest.register_craft({ output = "default:mossycobble", type = "shapeless", recipe = {"default:mese_crystal_fragment", "default:cobble"}, }) minetest.register_craft({ output = "moreblocks:wood_tile 9", recipe = { {"default:wood", "default:wood", "default:wood"}, {"default:wood", "default:wood", "default:wood"}, {"default:wood", "default:wood", "default:wood"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_flipped", recipe = {{"moreblocks:wood_tile"},} }) minetest.register_craft({ output = "moreblocks:wood_tile_center 9", recipe = { {"default:wood", "default:wood", "default:wood"}, {"default:wood", "moreblocks:wood_tile", "default:wood"}, {"default:wood", "default:wood", "default:wood"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_full 4", recipe = { {"moreblocks:wood_tile", "moreblocks:wood_tile"}, {"moreblocks:wood_tile", "moreblocks:wood_tile"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_up", recipe = { {"default:stick"}, {"moreblocks:wood_tile_center"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_down", recipe = { {"moreblocks:wood_tile_center"}, {"default:stick"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_left", recipe = { {"default:stick", "moreblocks:wood_tile_center"}, } }) minetest.register_craft({ output = "moreblocks:wood_tile_right", recipe = { {"moreblocks:wood_tile_center", "default:stick"}, } }) minetest.register_craft({ output = "moreblocks:circle_stone_bricks 8", recipe = { {"default:stone", "default:stone", "default:stone"}, {"default:stone", "", "default:stone"}, {"default:stone", "default:stone", "default:stone"}, } }) minetest.register_craft({ output = "moreblocks:all_faces_tree 8", recipe = { {"default:tree", "default:tree", "default:tree"}, {"default:tree", "", "default:tree"}, {"default:tree", "default:tree", "default:tree"}, } }) minetest.register_craft({ output = "moreblocks:all_faces_jungle_tree 8", recipe = { {"default:jungletree", "default:jungletree", "default:jungletree"}, {"default:jungletree", "", "default:jungletree"}, {"default:jungletree", "default:jungletree", "default:jungletree"}, } }) minetest.register_craft({ output = "moreblocks:sweeper 4", recipe = { {"default:junglegrass"}, {"default:stick"}, } }) minetest.register_craft({ output = "moreblocks:stone_tile 4", recipe = { {"default:cobble", "default:cobble"}, {"default:cobble", "default:cobble"}, } }) minetest.register_craft({ output = "moreblocks:split_stone_tile", recipe = { {"moreblocks:stone_tile"}, } }) minetest.register_craft({ output = "moreblocks:split_stone_tile_alt", recipe = { {"moreblocks:split_stone_tile"}, } }) minetest.register_craft({ output = "moreblocks:grey_bricks 2", type = "shapeless", recipe = {"default:stone", "default:brick"}, }) minetest.register_craft({ output = "moreblocks:grey_bricks 2", type = "shapeless", recipe = {"default:stonebrick", "default:brick"}, }) minetest.register_craft({ output = "moreblocks:empty_bookshelf", type = "shapeless", recipe = {"moreblocks:sweeper", "default:bookshelf"}, replacements = {{"default:bookshelf", "default:book 3"}}, -- When obtaining an empty bookshelf, return the books used in it as well }) minetest.register_craft({ output = "moreblocks:coal_stone_bricks 4", recipe = { {"moreblocks:coal_stone", "moreblocks:coal_stone"}, {"moreblocks:coal_stone", "moreblocks:coal_stone"}, } }) minetest.register_craft({ output = "moreblocks:iron_stone_bricks 4", recipe = { {"moreblocks:iron_stone", "moreblocks:iron_stone"}, {"moreblocks:iron_stone", "moreblocks:iron_stone"}, } }) minetest.register_craft({ output = "moreblocks:plankstone 4", recipe = { {"default:stone", "default:wood"}, {"default:wood", "default:stone"}, } }) minetest.register_craft({ output = "moreblocks:plankstone 4", recipe = { {"default:wood", "default:stone"}, {"default:stone", "default:wood"}, } }) minetest.register_craft({ output = "moreblocks:coal_checker 4", recipe = { {"default:stone", "default:coal_lump"}, {"default:coal_lump", "default:stone"}, } }) minetest.register_craft({ output = "moreblocks:coal_checker 4", recipe = { {"default:coal_lump", "default:stone"}, {"default:stone", "default:coal_lump"}, } }) minetest.register_craft({ output = "moreblocks:iron_checker 4", recipe = { {"default:steel_ingot", "default:stone"}, {"default:stone", "default:steel_ingot"}, } }) minetest.register_craft({ output = "moreblocks:iron_checker 4", recipe = { {"default:stone", "default:steel_ingot"}, {"default:steel_ingot", "default:stone"}, } }) minetest.register_craft({ output = "default:chest_locked", type = "shapeless", recipe = {"default:steel_ingot", "default:chest"}, }) minetest.register_craft({ output = "default:chest_locked", type = "shapeless", recipe = {"default:copper_ingot", "default:chest"}, }) minetest.register_craft({ output = "default:chest_locked", type = "shapeless", recipe = {"default:bronze_ingot", "default:chest"}, }) minetest.register_craft({ output = "default:chest_locked", type = "shapeless", recipe = {"default:gold_ingot", "default:chest"}, }) minetest.register_craft({ output = "moreblocks:iron_glass", type = "shapeless", recipe = {"default:steel_ingot", "default:glass"}, }) minetest.register_craft({ output = "default:glass", type = "shapeless", recipe = {"default:coal_lump", "moreblocks:iron_glass"}, }) minetest.register_craft({ output = "moreblocks:coal_glass", type = "shapeless", recipe = {"default:coal_lump", "default:glass"}, }) minetest.register_craft({ output = "default:glass", type = "shapeless", recipe = {"default:steel_ingot", "moreblocks:coal_glass"}, }) minetest.register_craft({ output = "moreblocks:clean_glass", type = "shapeless", recipe = {"moreblocks:sweeper", "default:glass"}, }) minetest.register_craft({ output = "moreblocks:glow_glass", type = "shapeless", recipe = {"default:torch", "default:glass"}, }) minetest.register_craft({ output = "moreblocks:trap_glow_glass", type = "shapeless", recipe = {"default:mese_crystal_fragment", "default:glass", "default:torch"}, }) minetest.register_craft({ output = "moreblocks:trap_glow_glass", type = "shapeless", recipe = {"default:mese_crystal_fragment", "moreblocks:glow_glass"}, }) minetest.register_craft({ output = "moreblocks:super_glow_glass", type = "shapeless", recipe = {"default:torch", "default:torch", "default:glass"}, }) minetest.register_craft({ output = "moreblocks:super_glow_glass", type = "shapeless", recipe = {"default:torch", "moreblocks:glow_glass"}, }) minetest.register_craft({ output = "moreblocks:trap_super_glow_glass", type = "shapeless", recipe = {"default:mese_crystal_fragment", "default:glass", "default:torch", "default:torch"}, }) minetest.register_craft({ output = "moreblocks:trap_super_glow_glass", type = "shapeless", recipe = {"default:mese_crystal_fragment", "moreblocks:super_glow_glass"}, }) minetest.register_craft({ output = "moreblocks:coal_stone", type = "shapeless", recipe = {"default:coal_lump", "default:stone"}, }) minetest.register_craft({ output = "default:stone", type = "shapeless", recipe = {"default:steel_ingot", "moreblocks:coal_stone"}, }) minetest.register_craft({ output = "moreblocks:iron_stone", type = "shapeless", recipe = {"default:steel_ingot", "default:stone"}, }) minetest.register_craft({ output = "default:stone", type = "shapeless", recipe = {"default:coal_lump", "moreblocks:iron_stone"}, }) minetest.register_craft({ output = "moreblocks:trap_stone", type = "shapeless", recipe = {"default:mese_crystal_fragment", "default:stone"}, }) minetest.register_craft({ output = "moreblocks:trap_glass", type = "shapeless", recipe = {"default:mese_crystal_fragment", "default:glass"}, }) minetest.register_craft({ output = "moreblocks:cactus_brick", type = "shapeless", recipe = {"default:cactus", "default:brick"}, }) minetest.register_craft({ output = "moreblocks:cactus_checker 4", recipe = { {"default:cactus", "default:stone"}, {"default:stone", "default:cactus"}, } }) minetest.register_craft({ output = "moreblocks:cactuschecker 4", recipe = { {"default:stone", "default:cactus"}, {"default:cactus", "default:stone"}, } }) minetest.register_craft({ output = "moreblocks:rope 3", recipe = { {"default:junglegrass"}, {"default:junglegrass"}, {"default:junglegrass"}, } }) minetest.register_craft({ output = "moreblocks:cobble_compressed", recipe = { {"default:cobble", "default:cobble", "default:cobble"}, {"default:cobble", "default:cobble", "default:cobble"}, {"default:cobble", "default:cobble", "default:cobble"}, } }) minetest.register_craft({ output = "default:cobble 9", recipe = { {"moreblocks:cobble_compressed"}, } }) minetest.register_craft({ type = "cooking", output = "moreblocks:tar", recipe = "default:gravel", }) minetest.register_craft({ type = "shapeless", output = "moreblocks:copperpatina", recipe = {"bucket:bucket_water", "default:copperblock"}, replacements = { {"bucket:bucket_water", "bucket:bucket_empty"} } }) minetest.register_craft({ output = "default:copper_ingot 9", recipe = { {"moreblocks:copperpatina"}, } }) if minetest.setting_getbool("moreblocks.circular_saw_crafting") ~= false then -- “If nil or true then” minetest.register_craft({ output = "moreblocks:circular_saw", recipe = { { "", "default:steel_ingot", "" }, { "group:wood", "group:wood", "group:wood"}, { "group:wood", "", "group:wood"}, } }) end
gpl-3.0
silverhammermba/awesome
spec/awful/keyboardlayout_spec.lua
11
3466
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2015 Uli Schlachter and Kazunobu Kuriyama --------------------------------------------------------------------------- local kb = require("awful.widget.keyboardlayout") describe("awful.widget.keyboardlayout get_groups_from_group_names", function() it("nil", function() assert.is_nil(kb.get_groups_from_group_names(nil)) end) local tests = { -- possible worst cases [""] = { }, ["empty"] = { }, ["empty(basic)"] = { }, -- contrived cases for robustness test ["pc()+de+jp+group()"] = { { file = "de", group_idx = 1 }, { file = "jp", group_idx = 1 } }, ["us(altgr-intl)"] = { { file = "us", group_idx = 1, section = "altgr-intl" } }, -- possible eight variations of a single term ["de"] = { { file = "de", group_idx = 1 } }, ["de:2" ] = { { file = "de", group_idx = 2 } }, ["de(nodeadkeys)"] = { { file = "de", group_idx = 1, section = "nodeadkeys" } }, ["de(nodeadkeys):2"] = { { file = "de", group_idx = 2, section = "nodeadkeys" } }, ["macintosh_vndr/de"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de:2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr" } }, ["macintosh_vndr/de(nodeadkeys)"] = { { file = "de", group_idx = 1, vendor = "macintosh_vndr", section = "nodeadkeys" } }, ["macintosh_vndr/de(nodeadkeys):2"] = { { file = "de", group_idx = 2, vendor = "macintosh_vndr", section = "nodeadkeys" } }, -- multiple terms ["pc+de"] = { { file = "de", group_idx = 1 } }, ["pc+us+inet(evdev)+terminate(ctrl_alt_bksp)"] = { { file = "us", group_idx = 1 } }, ["pc(pc105)+us+group(caps_toggle)+group(ctrl_ac)"] = { { file = "us", group_idx = 1 } }, ["pc+us(intl)+inet(evdev)+group(win_switch)"] = { { file = "us", group_idx = 1, section = "intl" } }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, }, -- multiple layouts ["pc+jp+us:2+inet(evdev)+capslock(hyper)"] = { { file = "jp", group_idx = 1 }, { file = "us", group_idx = 2 } }, ["pc+us+ru:2+de:3+ba:4+inet"] = { { file = "us", group_idx = 1 }, { file = "ru", group_idx = 2 }, { file = "de", group_idx = 3 }, { file = "ba", group_idx = 4 }, }, ["macintosh_vndr/apple(alukbd)+macintosh_vndr/jp(usmac)+macintosh_vndr/jp(mac):2+group(shifts_toggle)"] = { { file = "jp", group_idx = 1, vendor = "macintosh_vndr", section = "usmac" }, { file = "jp", group_idx = 2, vendor = "macintosh_vndr", section = "mac" }, }, } for arg, expected in pairs(tests) do it(arg, function() assert.is.same(expected, kb.get_groups_from_group_names(arg)) end) end end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
tianxiawuzhei/cocos-quick-lua
quick/samples/anysdk/src/cocos/extension/DeprecatedExtensionFunc.lua
39
1309
--tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of CCControl will be deprecated end local CCControlDeprecated = { } function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent) deprecatedTip("addHandleOfControlEvent","registerControlEventHandler") print("come in addHandleOfControlEvent") self:registerControlEventHandler(func,controlEvent) end CCControl.addHandleOfControlEvent = CCControlDeprecated.addHandleOfControlEvent --functions of CCControl will be deprecated end --Enums of CCTableView will be deprecated begin CCTableView.kTableViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL CCTableView.kTableViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM CCTableView.kTableCellTouched = cc.TABLECELL_TOUCHED CCTableView.kTableCellSizeForIndex = cc.TABLECELL_SIZE_FOR_INDEX CCTableView.kTableCellSizeAtIndex = cc.TABLECELL_SIZE_AT_INDEX CCTableView.kNumberOfCellsInTableView = cc.NUMBER_OF_CELLS_IN_TABLEVIEW --Enums of CCTableView will be deprecated end --Enums of CCScrollView will be deprecated begin CCScrollView.kScrollViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL CCScrollView.kScrollViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM --Enums of CCScrollView will be deprecated end
mit
cshore/luci
applications/luci-app-privoxy/luasrc/controller/privoxy.lua
23
8560
-- Copyright 2014-2016 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed under the Apache License, Version 2.0 module("luci.controller.privoxy", package.seeall) local NX = require "nixio" local NXFS = require "nixio.fs" local DISP = require "luci.dispatcher" local HTTP = require "luci.http" local I18N = require "luci.i18n" -- not globally avalible here local IPKG = require "luci.model.ipkg" local UCI = require "luci.model.uci" local UTIL = require "luci.util" local SYS = require "luci.sys" local srv_name = "privoxy" local srv_ver_min = "3.0.23" -- minimum version of service required local srv_ver_cmd = [[/usr/sbin/privoxy --version | awk {'print $3'}]] local app_name = "luci-app-privoxy" local app_title = "Privoxy WEB proxy" local app_version = "1.0.6-1" function index() entry( {"admin", "services", "privoxy"}, cbi("privoxy"), _("Privoxy WEB proxy"), 59) entry( {"admin", "services", "privoxy", "logview"}, call("logread") ).leaf = true entry( {"admin", "services", "privoxy", "startstop"}, post("startstop") ).leaf = true entry( {"admin", "services", "privoxy", "status"}, call("get_pid") ).leaf = true end -- Application specific information functions function app_description() return I18N.translate("Privoxy is a non-caching web proxy with advanced filtering " .. "capabilities for enhancing privacy, modifying web page data and HTTP headers, " .. "controlling access, and removing ads and other obnoxious Internet junk.") .. [[<br /><strong>]] .. I18N.translate("For help use link at the relevant option") .. [[</strong>]] end -- Standardized application/service functions function app_title_main() return [[<a href="javascript:alert(']] .. I18N.translate("Version Information") .. [[\n\n]] .. app_name .. [[\n\t]] .. I18N.translate("Version") .. [[:\t]] .. app_version .. [[\n\n]] .. srv_name .. [[ ]] .. I18N.translate("required") .. [[:]] .. [[\n\t]] .. I18N.translate("Version") .. [[:\t]] .. srv_ver_min .. [[ ]] .. I18N.translate("or higher") .. [[\n\n]] .. srv_name .. [[ ]] .. I18N.translate("installed") .. [[:]] .. [[\n\t]] .. I18N.translate("Version") .. [[:\t]] .. (service_version() or I18N.translate("NOT installed")) .. [[\n\n]] .. [[')">]] .. I18N.translate(app_title) .. [[</a>]] end function service_version() local ver = nil IPKG.list_installed(srv_name, function(n, v, d) if v and (#v > 0) then ver = v end end ) if not ver or (#ver == 0) then ver = UTIL.exec(srv_ver_cmd) if #ver == 0 then ver = nil end end return ver end function service_ok() return IPKG.compare_versions((service_version() or "0"), ">=", srv_ver_min) end function service_update() local url = DISP.build_url("admin", "system", "packages") if not service_version() then return [[<h3><strong><br /><font color="red">&nbsp;&nbsp;&nbsp;&nbsp;]] .. I18N.translate("Software package '%s' is not installed." % srv_name) .. [[</font><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. I18N.translate("required") .. [[: ]] .. srv_name .. [[ ]] .. srv_ver_min .. " " .. I18N.translate("or higher") .. [[<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. [[<a href="]] .. url ..[[">]] .. I18N.translate("Please install current version !") .. [[</a><br />&nbsp;</strong></h3>]] else return [[<h3><strong><br /><br /><font color="red">&nbsp;&nbsp;&nbsp;&nbsp;]] .. I18N.translate("Software package '%s' is outdated." % srv_name) .. [[</font><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. I18N.translate("installed") .. ": " .. service_version() .. [[<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. I18N.translate("required") .. ": " .. srv_ver_min .. " " .. I18N.translate("or higher") .. [[<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. [[<a href="]] .. url ..[[">]] .. I18N.translate("Please update to the current version!") .. [[</a><br /><br />&nbsp;</strong></h3>]] end end -- called by XHR.get from detail_logview.htm function logread() -- read application settings local uci = UCI.cursor() local logdir = uci:get("privoxy", "privoxy", "logdir") or "/var/log" local logfile = uci:get("privoxy", "privoxy", "logfile") or "privoxy.log" uci:unload("privoxy") local ldata=NXFS.readfile(logdir .. "/" .. logfile) if not ldata or #ldata == 0 then ldata="_nodata_" end HTTP.write(ldata) end -- called by XHR.get from detail_startstop.htm function startstop() local pid = get_pid(true) if pid > 0 then SYS.call("/etc/init.d/privoxy stop") NX.nanosleep(1) -- sleep a second if NX.kill(pid, 0) then -- still running NX.kill(pid, 9) -- send SIGKILL end pid = 0 else SYS.call("/etc/init.d/privoxy start") NX.nanosleep(1) -- sleep a second pid = tonumber(NXFS.readfile("/var/run/privoxy.pid") or 0 ) if pid > 0 and not NX.kill(pid, 0) then pid = 0 -- process did not start end end HTTP.write(tostring(pid)) -- HTTP needs string not number end -- called by XHR.poll from detail_startstop.htm -- and from lua (with parameter "true") function get_pid(from_lua) local pid = tonumber(NXFS.readfile("/var/run/privoxy.pid") or 0 ) if pid > 0 and not NX.kill(pid, 0) then pid = 0 end if from_lua then return pid else HTTP.write(tostring(pid)) -- HTTP needs string not number end end -- replacement of build-in parse of UCI option -- modified AbstractValue.parse(self, section, novld) from cbi.lua -- validate is called if rmempty/optional true or false -- write is called if rmempty/optional true or false function value_parse(self, section, novld) local fvalue = self:formvalue(section) local fexist = ( fvalue and (#fvalue > 0) ) -- not "nil" and "not empty" local cvalue = self:cfgvalue(section) local rm_opt = ( self.rmempty or self.optional ) local eq_cfg -- flag: equal cfgvalue -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then eq_cfg = (#fvalue == #cvalue) if eq_cfg then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then eq_cfg = false end end end if eq_cfg then fvalue = cvalue end end -- removed parameter "section" from function call because used/accepted nowhere -- also removed call to function "transfer" local vvalue, errtxt = self:validate(fvalue) -- error handling; validate return "nil" if not vvalue then if novld then -- and "novld" set return -- then exit without raising an error end if fexist then -- and there is a formvalue self:add_error(section, "invalid", errtxt or self.title .. ": invalid") return -- so data are invalid elseif not rm_opt then -- and empty formvalue but NOT (rmempty or optional) set self:add_error(section, "missing", errtxt or self.title .. ": missing") return -- so data is missing elseif errtxt then self:add_error(section, "invalid", errtxt) return end -- error ("\n option: " .. self.option .. -- "\n fvalue: " .. tostring(fvalue) .. -- "\n fexist: " .. tostring(fexist) .. -- "\n cvalue: " .. tostring(cvalue) .. -- "\n vvalue: " .. tostring(vvalue) .. -- "\n vexist: " .. tostring(vexist) .. -- "\n rm_opt: " .. tostring(rm_opt) .. -- "\n eq_cfg: " .. tostring(eq_cfg) .. -- "\n eq_def: " .. tostring(eq_def) .. -- "\n novld : " .. tostring(novld) .. -- "\n errtxt: " .. tostring(errtxt) ) end -- lets continue with value returned from validate eq_cfg = ( vvalue == cvalue ) -- update equal_config flag local vexist = ( vvalue and (#vvalue > 0) ) and true or false -- not "nil" and "not empty" local eq_def = ( vvalue == self.default ) -- equal_default flag -- (rmempty or optional) and (no data or equal_default) if rm_opt and (not vexist or eq_def) then if self:remove(section) then -- remove data from UCI self.section.changed = true -- and push events end return end -- not forcewrite and no changes, so nothing to write if not self.forcewrite and eq_cfg then return end -- we should have a valid value here assert (vvalue, "\n option: " .. self.option .. "\n fvalue: " .. tostring(fvalue) .. "\n fexist: " .. tostring(fexist) .. "\n cvalue: " .. tostring(cvalue) .. "\n vvalue: " .. tostring(vvalue) .. "\n vexist: " .. tostring(vexist) .. "\n rm_opt: " .. tostring(rm_opt) .. "\n eq_cfg: " .. tostring(eq_cfg) .. "\n eq_def: " .. tostring(eq_def) .. "\n errtxt: " .. tostring(errtxt) ) -- write data to UCI; raise event only on changes if self:write(section, vvalue) and not eq_cfg then self.section.changed = true end end
apache-2.0
jintiao/some-mmorpg
server/lualib/map/quadtree.lua
6
1951
local quadtree = {} local mt = { __index = quadtree } function quadtree.new (l, t, r, b) return setmetatable ({ left = l, top = t, right = r, bottom = b, object = {}, }, mt) end function quadtree:insert (id, x, y) if x < self.left or x > self.right or y < self.top or y > self.bottom then return end if self.children then local t for _, v in pairs (self.children) do t = v:insert (id, x, y) if t then return t end end else self.object[id] = { x = x, y = y } if #self.object >= 2 then return self:subdivide (id) end return self end end function quadtree:subdevide (last) local left, top, right, bottom = self.left, self.top, self.right, self.bottom local centerx = (left + right) // 2 local centery = (top + bottom) // 2 self.children = { quadtree.new (left, top, centerx, centery), quadtree.new (centerx, top, right, centery), quadtree.new (left, centery, centerx, bottom), quadtree.new (centerx, centery, right, bottom), } local ret local t for k, v in pairs (self.object) do for _, c in self.children do t = c:insert (k, v.x, v.y) if t then if k == last then ret = t end break end end end self.object = nil return ret end function quadtree:remove (id) if self.object then if self.object[id] ~= nil then self.object[id] = nil return true end elseif self.children then for _, v in pairs (self.children) do if v:remove (id) then return true end end end end function quadtree:query (id, left, top, right, bottom, result) if left > self.right or right < self.left or top > self.bottom or bottom < self.top then return end if self.children then for _, v in pairs (self.children) do v:query (id, left, top, right, bottom, result) end else for k, v in pairs (self.object) do if k ~= id and v.x > left and v.x < right and v.y > top and v.y < bottom then table.insert (result, k) end end end end return quadtree
mit
tianxiawuzhei/cocos-quick-lua
quick/samples/luajavabridge/src/scenes/MainScene.lua
2
2040
local MainScene = class("MainScene", function() return display.newScene("MainScene") end) function MainScene:ctor() local btn btn = cc.ui.UIPushButton.new() :setButtonLabel(cc.ui.UILabel.new({text = "call Java - showAlertDialog()", size = 64})) :onButtonClicked(function() if device.platform ~= "android" then print("please run this on android device") btn:setButtonLabel(cc.ui.UILabel.new({text = "please run this on android device", size = 32})) return end -- call Java method local javaClassName = "org/cocos2dx/lua/AppActivity" local javaMethodName = "showAlertDialog" local javaParams = { "How are you ?", "I'm great !", function(event) local str = "Java method callback value is [" .. event .. "]" btn:setButtonLabel(cc.ui.UILabel.new({text = str, size = 32})) end } local javaMethodSig = "(Ljava/lang/String;Ljava/lang/String;I)V" luaj.callStaticMethod(javaClassName, javaMethodName, javaParams, javaMethodSig) end) :align(display.CENTER, display.cx, display.cy) :addTo(self) btn:setKeypadEnabled(true) btn:addNodeEventListener(cc.KEYPAD_EVENT, function (event) dump(event) local str = "event.key is [ " .. event.key .. " ]" btn:setButtonLabel(cc.ui.UILabel.new({text = str, size = 32})) if event.key == "back" then print("back") cc.Director:getInstance():endToLua() if device.platform == "windows" or device.platform == "mac" then os.exit() end elseif event.key == "menu" then print("menu") end end) end function MainScene:onEnter() end return MainScene
mit
mrbangi/mbangi
plugins/spammer.lua
14
75190
local function run(msg) if msg.text == "[!/]spam" and is_sudo(msg) then return "".. [[ ]] end end return { description = "Spammer for Creed bot", usage = "!spam : send 25000pm for spaming", patterns = { "^[!/](spam)$" }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
jonmaur/draggin-framework
samples/8-box2d-rube/main/main.lua
1
1433
-- make sure the draggin framework is found package.path = package.path .. ';' .. os.getenv("DRAGGIN_FRAMEWORK") .. '/src/?.lua' -- makes output work better on most hosts, or when running through Sublime Text. io.stdout:setvbuf("no") local Draggin = require "draggin/draggin" local Display = require "draggin/display" ---------------------------------------------------------------- -- App Title Draggin.appTitle = "RUBE Scene!" ---------------------------------------------------------------- -- Display -- params: <string> window text, <number> virtual width, <number> virtual height, <number> screen width, <number> screen height Display:init(Draggin.appTitle, 1920/4, 1080/4, 1920/2, 1080/2, false) local GameStateManager = require "draggin/gamestatemanager" local RubeState = require "rubestate" --- Main MOAIThread function of the application. -- The whole application starts here to make sure you can always call coroutine.yield() local function mainFunc() local rubestate = RubeState.new() GameStateManager.pushState(rubestate) Draggin:waitForAnyInput() os.exit() end -- Let's just run the main function in a co-routine so we can use functions like Draggin:waitForAnyInput() -- coroutines wake up once every frame, at the end of the frame they need to yield or reach the end of -- the main coroutine function, effectively destroying that coroutine local mainThread = MOAIThread.new() mainThread:run(mainFunc)
mit
abasshacker/abab
plugins/quran.lua
20
1243
do umbrella = "http://umbrella.shayan-soft.ir/quran/" -- database -- get sound of sura local function read_sura(chat_id, target) local readq = http.request(umbrella.."Sura"..target..".mp3") local url = umbrella.."Sura"..target..".mp3" local file = download_to_file(url) local cb_extra = {file_path=file} return send_document("chat#id"..chat_id, file, rmtmp_cb, cb_extra) end -- get text of sura local function view_sura(chat_id, target) local viewq = http.request(umbrella.."quran ("..target..").txt") return viewq end -- run script local function run(msg, matches) local chat_id = msg.to.id if matches[1] == "read" then local target = matches[2] return read_sura(chat_id, target) elseif matches[1] == "sura" then local target = matches[2] return view_sura(chat_id, target) elseif matches [1] == "quran" then local qlist = http.request(umbrella.."list.txt") -- list of suras return qlist end end -- other help and commands return { description = "Umbrella Quran Project", usage = { "!sura (num) : view arabic sura", "!read (num) : send sound of sura", "!quran : sura list of quran", }, patterns = { "^[!/](sura) (.+)$", "^[!/](read) (.+)$", "^[!/](quran)$", }, run = run, } end
gpl-2.0
cshore/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/system.lua
17
5674
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local sys = require "luci.sys" local zones = require "luci.sys.zoneinfo" local fs = require "nixio.fs" local conf = require "luci.config" local m, s, o local has_ntpd = fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(zones.TZ) do o:value(zone[1]) end function o.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(zones.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "log_proto", translate("External system log server protocol")) o:value("udp", "UDP") o:value("tcp", "TCP") o = s:taboption("logging", Value, "log_file", translate("Write system log to file")) o.optional = true o.placeholder = "/tmp/system.log" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(conf.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(conf.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then -- timeserver setup was requested, create section and reload page if m:formvalue("cbid.system._timeserver._enable") then m.uci:section("system", "timeserver", "ntp", { server = { "0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org", "2.openwrt.pool.ntp.org", "3.openwrt.pool.ntp.org" } } ) m.uci:save("system") luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1])) return end local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.cfgsections = function() return { "_timeserver" } end x = s:option(Button, "_enable") x.title = translate("Time Synchronization is not configured yet.") x.inputtitle = translate("Set up Time Synchronization") x.inputstyle = "apply" else s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false o = s:option(Flag, "enable", translate("Enable NTP client")) o.rmempty = false function o.cfgvalue(self) return sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then sys.init.enable("sysntpd") sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") sys.init.disable("sysntpd") end end o = s:option(Flag, "enable_server", translate("Provide NTP server")) o:depends("enable", "1") o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host(0)" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end end return m
apache-2.0
guard163/tarantool
test/wal_off/itr_lt_gt.test.lua
6
1034
-- test for https://github.com/tarantool/tarantool/issues/769 s = box.schema.create_space('test') i = s:create_index('primary', { type = 'TREE', parts = {1, 'num', 2, 'num'} }) s:insert{0, 0} s:insert{2, 0} for i=1,10000 do s:insert{1, i} end test_itrs = {'EQ', 'REQ', 'GT', 'LT', 'GE', 'LE'} test_res = {} too_longs = {} --# setopt delimiter ';' function test_run_itr(itr, key) for i=1,50 do local gen, param, state = s.index.primary:pairs({key}, {iterator = itr}) local state, v = gen(param, state) test_res[itr .. ' ' .. key] = v end end; function test_itr(itr, key) test_run_itr(itr, key) end; for _,itr in pairs(test_itrs) do local t = os.clock() for key = 0,2 do test_itr(itr, key) end local diff = os.clock() - t if diff > 0.05 then table.insert(too_longs, 'Some of the iterators takes too long to position: '.. diff) end end; --# setopt delimiter '' test_res too_longs s:drop() test_itr = nil test_run_itr = nil test_itrs = nil s = nil 'done'
bsd-2-clause
AlexArendsen/computercraft
monitor-wrapper.lua
1
1987
-- Computercraft Monitor Wrapper, written by Alex Arendsen MonitorWrapper = { selector = "top" } function MonitorWrapper:new(o) o = o or {} setmetatable(o, self) self.__index = self o.mon = peripheral.wrap(o.selector) return o end function MonitorWrapper:write (str) self.mon.write(str) end function MonitorWrapper:blit (str, colors, background) self.mon.blit(str,color,background) end function MonitorWrapper:clear() self.mon.clear() end function MonitorWrapper:clearLine() self.mon.clearLine() end function MonitorWrapper:getCursorPos() return self.mon.getCursorPos() end function MonitorWrapper:setCursorPos(x,y) self.mon.setCursorPos(x,y) end function MonitorWrapper:setCursorBlink(state) self.mon.setCursorBlink(state) end function MonitorWrapper:isColor() return self.mon.isColor() end function MonitorWrapper:getSize() return self.mon.getSize() end function MonitorWrapper:scroll(amount) self.mon.scroll(amount) end function MonitorWrapper:redirect(target) self.mon.redirect(target) end function MonitorWrapper:current() return self.mon.current() end function MonitorWrapper:native() return self.mon.native() end function MonitorWrapper:setTextColor(color) self.mon.setTextColor(color) end function MonitorWrapper:getTextColor() return self.mon.getTextColor() end function MonitorWrapper:setBackgroundColor(color) self.mon.setBackgroundColor(color) end function MonitorWrapper:getBackgroundColor() return self.mon.getBackgroundColor() end function MonitorWrapper:setTextScale(scale) self.mon.setTextScale(scale) end -- Wrapper-specific methods function MonitorWrapper:draw() -- Leaving in for fewer bugs end -- Get string prepresentation of some input function MonitorWrapper:repr(value) t = type(value) if t == "string" then return value elseif t == "number" then suf = "" if value % 1 == 0 then suf = ".0" end return tostring(value)..suf end return tostring(value) end
gpl-3.0
Relintai/Relintais-Enemy-Kooldown-Tracker-WotLK
lib/AceGUI-3.0/widgets/AceGUIWidget-Heading.lua
68
2216
--[[----------------------------------------------------------------------------- Heading Widget -------------------------------------------------------------------------------]] local Type, Version = "Heading", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetText() self:SetFullWidth() self:SetHeight(18) end, -- ["OnRelease"] = nil, ["SetText"] = function(self, text) self.label:SetText(text or "") if text and text ~= "" then self.left:SetPoint("RIGHT", self.label, "LEFT", -5, 0) self.right:Show() else self.left:SetPoint("RIGHT", -3, 0) self.right:Hide() end end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontNormal") label:SetPoint("TOP") label:SetPoint("BOTTOM") label:SetJustifyH("CENTER") local left = frame:CreateTexture(nil, "BACKGROUND") left:SetHeight(8) left:SetPoint("LEFT", 3, 0) left:SetPoint("RIGHT", label, "LEFT", -5, 0) left:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") left:SetTexCoord(0.81, 0.94, 0.5, 1) local right = frame:CreateTexture(nil, "BACKGROUND") right:SetHeight(8) right:SetPoint("RIGHT", -3, 0) right:SetPoint("LEFT", label, "RIGHT", 5, 0) right:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") right:SetTexCoord(0.81, 0.94, 0.5, 1) local widget = { label = label, left = left, right = right, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
cshore/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/ifaces.lua
11
15480
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local ut = require "luci.util" local pt = require "luci.tools.proto" local nw = require "luci.model.network" local fw = require "luci.model.firewall" arg[1] = arg[1] or "" local has_dnsmasq = fs.access("/etc/config/dhcp") local has_firewall = fs.access("/etc/config/firewall") m = Map("network", translate("Interfaces") .. " - " .. arg[1]:upper(), translate("On this page you can configure the network interfaces. You can bridge several interfaces by ticking the \"bridge interfaces\" field and enter the names of several network interfaces separated by spaces. You can also use <abbr title=\"Virtual Local Area Network\">VLAN</abbr> notation <samp>INTERFACE.VLANNR</samp> (<abbr title=\"for example\">e.g.</abbr>: <samp>eth0.1</samp>).")) m.redirect = luci.dispatcher.build_url("admin", "network", "network") m:chain("wireless") if has_firewall then m:chain("firewall") end nw.init(m.uci) fw.init(m.uci) local net = nw:get_network(arg[1]) local function backup_ifnames(is_bridge) if not net:is_floating() and not m:get(net:name(), "_orig_ifname") then local ifcs = net:get_interfaces() or { net:get_interface() } if ifcs then local _, ifn local ifns = { } for _, ifn in ipairs(ifcs) do ifns[#ifns+1] = ifn:name() end if #ifns > 0 then m:set(net:name(), "_orig_ifname", table.concat(ifns, " ")) m:set(net:name(), "_orig_bridge", tostring(net:is_bridge())) end end end end -- redirect to overview page if network does not exist anymore (e.g. after a revert) if not net then luci.http.redirect(luci.dispatcher.build_url("admin/network/network")) return end -- protocol switch was requested, rebuild interface config and reload page if m:formvalue("cbid.network.%s._switch" % net:name()) then -- get new protocol local ptype = m:formvalue("cbid.network.%s.proto" % net:name()) or "-" local proto = nw:get_protocol(ptype, net:name()) if proto then -- backup default backup_ifnames() -- if current proto is not floating and target proto is not floating, -- then attempt to retain the ifnames --error(net:proto() .. " > " .. proto:proto()) if not net:is_floating() and not proto:is_floating() then -- if old proto is a bridge and new proto not, then clip the -- interface list to the first ifname only if net:is_bridge() and proto:is_virtual() then local _, ifn local first = true for _, ifn in ipairs(net:get_interfaces() or { net:get_interface() }) do if first then first = false else net:del_interface(ifn) end end m:del(net:name(), "type") end -- if the current proto is floating, the target proto not floating, -- then attempt to restore ifnames from backup elseif net:is_floating() and not proto:is_floating() then -- if we have backup data, then re-add all orphaned interfaces -- from it and restore the bridge choice local br = (m:get(net:name(), "_orig_bridge") == "true") local ifn local ifns = { } for ifn in ut.imatch(m:get(net:name(), "_orig_ifname")) do ifn = nw:get_interface(ifn) if ifn and not ifn:get_network() then proto:add_interface(ifn) if not br then break end end end if br then m:set(net:name(), "type", "bridge") end -- in all other cases clear the ifnames else local _, ifc for _, ifc in ipairs(net:get_interfaces() or { net:get_interface() }) do net:del_interface(ifc) end m:del(net:name(), "type") end -- clear options local k, v for k, v in pairs(m:get(net:name())) do if k:sub(1,1) ~= "." and k ~= "type" and k ~= "ifname" and k ~= "_orig_ifname" and k ~= "_orig_bridge" then m:del(net:name(), k) end end -- set proto m:set(net:name(), "proto", proto:proto()) m.uci:save("network") m.uci:save("wireless") -- reload page luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1])) return end end -- dhcp setup was requested, create section and reload page if m:formvalue("cbid.dhcp._enable._enable") then m.uci:section("dhcp", "dhcp", arg[1], { interface = arg[1], start = "100", limit = "150", leasetime = "12h" }) m.uci:save("dhcp") luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1])) return end local ifc = net:get_interface() s = m:section(NamedSection, arg[1], "interface", translate("Common Configuration")) s.addremove = false s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) s:tab("physical", translate("Physical Settings")) if has_firewall then s:tab("firewall", translate("Firewall Settings")) end st = s:taboption("general", DummyValue, "__status", translate("Status")) local function set_status() -- if current network is empty, print a warning if not net:is_floating() and net:is_empty() then st.template = "cbi/dvalue" st.network = nil st.value = translate("There is no device assigned yet, please attach a network device in the \"Physical Settings\" tab") else st.template = "admin_network/iface_status" st.network = arg[1] st.value = nil end end m.on_init = set_status m.on_after_save = set_status p = s:taboption("general", ListValue, "proto", translate("Protocol")) p.default = net:proto() if not net:is_installed() then p_install = s:taboption("general", Button, "_install") p_install.title = translate("Protocol support is not installed") p_install.inputtitle = translate("Install package %q" % net:opkg_package()) p_install.inputstyle = "apply" p_install:depends("proto", net:proto()) function p_install.write() return luci.http.redirect( luci.dispatcher.build_url("admin/system/packages") .. "?submit=1&install=%s" % net:opkg_package() ) end end p_switch = s:taboption("general", Button, "_switch") p_switch.title = translate("Really switch protocol?") p_switch.inputtitle = translate("Switch protocol") p_switch.inputstyle = "apply" local _, pr for _, pr in ipairs(nw:get_protocols()) do p:value(pr:proto(), pr:get_i18n()) if pr:proto() ~= net:proto() then p_switch:depends("proto", pr:proto()) end end auto = s:taboption("advanced", Flag, "auto", translate("Bring up on boot")) auto.default = (net:proto() == "none") and auto.disabled or auto.enabled delegate = s:taboption("advanced", Flag, "delegate", translate("Use builtin IPv6-management")) delegate.default = delegate.enabled if not net:is_virtual() then br = s:taboption("physical", Flag, "type", translate("Bridge interfaces"), translate("creates a bridge over specified interface(s)")) br.enabled = "bridge" br.rmempty = true br:depends("proto", "static") br:depends("proto", "dhcp") br:depends("proto", "none") stp = s:taboption("physical", Flag, "stp", translate("Enable <abbr title=\"Spanning Tree Protocol\">STP</abbr>"), translate("Enables the Spanning Tree Protocol on this bridge")) stp:depends("type", "bridge") stp.rmempty = true end if not net:is_floating() then ifname_single = s:taboption("physical", Value, "ifname_single", translate("Interface")) ifname_single.template = "cbi/network_ifacelist" ifname_single.widget = "radio" ifname_single.nobridges = true ifname_single.rmempty = false ifname_single.network = arg[1] ifname_single:depends("type", "") function ifname_single.cfgvalue(self, s) -- let the template figure out the related ifaces through the network model return nil end function ifname_single.write(self, s, val) local i local new_ifs = { } local old_ifs = { } for _, i in ipairs(net:get_interfaces() or { net:get_interface() }) do old_ifs[#old_ifs+1] = i:name() end for i in ut.imatch(val) do new_ifs[#new_ifs+1] = i -- if this is not a bridge, only assign first interface if self.option == "ifname_single" then break end end table.sort(old_ifs) table.sort(new_ifs) for i = 1, math.max(#old_ifs, #new_ifs) do if old_ifs[i] ~= new_ifs[i] then backup_ifnames() for i = 1, #old_ifs do net:del_interface(old_ifs[i]) end for i = 1, #new_ifs do net:add_interface(new_ifs[i]) end break end end end end if not net:is_virtual() then ifname_multi = s:taboption("physical", Value, "ifname_multi", translate("Interface")) ifname_multi.template = "cbi/network_ifacelist" ifname_multi.nobridges = true ifname_multi.rmempty = false ifname_multi.network = arg[1] ifname_multi.widget = "checkbox" ifname_multi:depends("type", "bridge") ifname_multi.cfgvalue = ifname_single.cfgvalue ifname_multi.write = ifname_single.write end if has_firewall then fwzone = s:taboption("firewall", Value, "_fwzone", translate("Create / Assign firewall-zone"), translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it.")) fwzone.template = "cbi/firewall_zonelist" fwzone.network = arg[1] fwzone.rmempty = false function fwzone.cfgvalue(self, section) self.iface = section local z = fw:get_zone_by_network(section) return z and z:name() end function fwzone.write(self, section, value) local zone = fw:get_zone(value) if not zone and value == '-' then value = m:formvalue(self:cbid(section) .. ".newzone") if value and #value > 0 then zone = fw:add_zone(value) else fw:del_network(section) end end if zone then fw:del_network(section) zone:add_network(section) end end end function p.write() end function p.remove() end function p.validate(self, value, section) if value == net:proto() then if not net:is_floating() and net:is_empty() then local ifn = ((br and (br:formvalue(section) == "bridge")) and ifname_multi:formvalue(section) or ifname_single:formvalue(section)) for ifn in ut.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end end return value end local form, ferr = loadfile( ut.libpath() .. "/model/cbi/admin_network/proto_%s.lua" % net:proto() ) if not form then s:taboption("general", DummyValue, "_error", translate("Missing protocol extension for proto %q" % net:proto()) ).value = ferr else setfenv(form, getfenv(1))(m, s, net) end local _, field for _, field in ipairs(s.children) do if field ~= st and field ~= p and field ~= p_install and field ~= p_switch then if next(field.deps) then local _, dep for _, dep in ipairs(field.deps) do dep.proto = net:proto() end else field:depends("proto", net:proto()) end end end -- -- Display DNS settings if dnsmasq is available -- if has_dnsmasq and net:proto() == "static" then m2 = Map("dhcp", "", "") local has_section = false m2.uci:foreach("dhcp", "dhcp", function(s) if s.interface == arg[1] then has_section = true return false end end) if not has_section and has_dnsmasq then s = m2:section(TypedSection, "dhcp", translate("DHCP Server")) s.anonymous = true s.cfgsections = function() return { "_enable" } end x = s:option(Button, "_enable") x.title = translate("No DHCP Server configured for this interface") x.inputtitle = translate("Setup DHCP Server") x.inputstyle = "apply" elseif has_section then s = m2:section(TypedSection, "dhcp", translate("DHCP Server")) s.addremove = false s.anonymous = true s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) s:tab("ipv6", translate("IPv6 Settings")) function s.filter(self, section) return m2.uci:get("dhcp", section, "interface") == arg[1] end local ignore = s:taboption("general", Flag, "ignore", translate("Ignore interface"), translate("Disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " .. "this interface.")) local start = s:taboption("general", Value, "start", translate("Start"), translate("Lowest leased address as offset from the network address.")) start.optional = true start.datatype = "or(uinteger,ip4addr)" start.default = "100" local limit = s:taboption("general", Value, "limit", translate("Limit"), translate("Maximum number of leased addresses.")) limit.optional = true limit.datatype = "uinteger" limit.default = "150" local ltime = s:taboption("general", Value, "leasetime", translate("Leasetime"), translate("Expiry time of leased addresses, minimum is 2 minutes (<code>2m</code>).")) ltime.rmempty = true ltime.default = "12h" local dd = s:taboption("advanced", Flag, "dynamicdhcp", translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"), translate("Dynamically allocate DHCP addresses for clients. If disabled, only " .. "clients having static leases will be served.")) dd.default = dd.enabled s:taboption("advanced", Flag, "force", translate("Force"), translate("Force DHCP on this network even if another server is detected.")) -- XXX: is this actually useful? --s:taboption("advanced", Value, "name", translate("Name"), -- translate("Define a name for this network.")) mask = s:taboption("advanced", Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("Override the netmask sent to clients. Normally it is calculated " .. "from the subnet that is served.")) mask.optional = true mask.datatype = "ip4addr" s:taboption("advanced", DynamicList, "dhcp_option", translate("DHCP-Options"), translate("Define additional DHCP options, for example \"<code>6,192.168.2.1," .. "192.168.2.2</code>\" which advertises different DNS servers to clients.")) for i, n in ipairs(s.children) do if n ~= ignore then n:depends("ignore", "") end end o = s:taboption("ipv6", ListValue, "ra", translate("Router Advertisement-Service")) o:value("", translate("disabled")) o:value("server", translate("server mode")) o:value("relay", translate("relay mode")) o:value("hybrid", translate("hybrid mode")) o = s:taboption("ipv6", ListValue, "dhcpv6", translate("DHCPv6-Service")) o:value("", translate("disabled")) o:value("server", translate("server mode")) o:value("relay", translate("relay mode")) o:value("hybrid", translate("hybrid mode")) o = s:taboption("ipv6", ListValue, "ndp", translate("NDP-Proxy")) o:value("", translate("disabled")) o:value("relay", translate("relay mode")) o:value("hybrid", translate("hybrid mode")) o = s:taboption("ipv6", ListValue, "ra_management", translate("DHCPv6-Mode"), translate("Default is stateless + stateful")) o:value("0", translate("stateless")) o:value("1", translate("stateless + stateful")) o:value("2", translate("stateful-only")) o:depends("dhcpv6", "server") o:depends("dhcpv6", "hybrid") o.default = "1" o = s:taboption("ipv6", Flag, "ra_default", translate("Always announce default router"), translate("Announce as default router even if no public prefix is available.")) o:depends("ra", "server") o:depends("ra", "hybrid") s:taboption("ipv6", DynamicList, "dns", translate("Announced DNS servers")) s:taboption("ipv6", DynamicList, "domain", translate("Announced DNS domains")) else m2 = nil end end return m, m2
apache-2.0
ariakabiryan/tnt_aria_bot
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
jonmaur/draggin-framework
samples/3-text/main/textstate.lua
1
3551
local Draggin = require "draggin/draggin" local Display = require "draggin/display" local TextBox = require "draggin/textbox" local viewport = Display.viewport local virtualWidth = Display.virtualWidth local virtualHeight = Display.virtualHeight local textstate = {} function textstate.new() -- Uncomment this to see the textbox debug draws --Draggin:debugDraw(true) local state = {} state.name = "TextState" local layers = {} local mainlayer local textboxes = {} function state:init() -- create the main layer mainlayer = MOAILayer2D.new() mainlayer:setViewport(viewport) layers[#layers+1] = mainlayer -- create the text boxes local txt = TextBox.new("LiberationSansNarrow-Regular", 42) txt:setDimensions(virtualWidth*0.5, virtualHeight*0.75, virtualWidth/2, virtualHeight/3, 0.5, 0.5) txt:setAlignment(MOAITextBox.CENTER_JUSTIFY, MOAITextBox.CENTER_JUSTIFY) txt:setSpeed(15) txt:insertIntoLayer(mainlayer) table.insert(textboxes, txt) txt = TextBox.new("PressStart16") txt:setColor(0, 1, 0, 1) txt:setShadowOffset(2, 2) txt:setDimensions(0, 0, virtualWidth/4, virtualHeight/8, 0, 0) txt:setAlignment(MOAITextBox.LEFT_JUSTIFY, MOAITextBox.BOTTOM_JUSTIFY) txt:setString('BOTTOM LEFT') table.insert(textboxes, txt) txt = TextBox.new("PressStart16") txt:setColor(0, 1, 0, 1) txt:setShadowColor(1, 0, 0, 0.75) txt:setShadowOffset(-2, 2) txt:setDimensions(virtualWidth, 0, virtualWidth/4, virtualHeight/8, 1, 0) txt:setAlignment(MOAITextBox.RIGHT_JUSTIFY, MOAITextBox.BOTTOM_JUSTIFY) txt:setString('BOTTOM RIGHT') table.insert(textboxes, txt) txt = TextBox.new("PressStart16") txt:setColor(0.75, 0, 0, 1) txt:setShadowColor(0, 0, 0, 0.75) txt:setShadowOffset(2, -2) txt:setDimensions(0, virtualHeight, virtualWidth/4, virtualHeight/8, 0, 1) txt:setAlignment(MOAITextBox.LEFT_JUSTIFY, MOAITextBox.TOP_JUSTIFY) txt:setString('TOP LEFT') table.insert(textboxes, txt) txt = TextBox.new("PressStart16") txt:setColor(0, 0, 1, 1) txt:setShadowColor(0, 0, 0.5, 1) txt:setShadowOffset(-2, -2) txt:setDimensions(virtualWidth, virtualHeight, virtualWidth/4, virtualHeight/8, 1, 1) txt:setAlignment(MOAITextBox.RIGHT_JUSTIFY, MOAITextBox.TOP_JUSTIFY) txt:setString('TOP RIGHT') table.insert(textboxes, txt) txt = TextBox.new("LiberationSansNarrow-Regular", 24) txt:setColor(1, 1, 0, 1) txt:setDimensions(virtualWidth/2, virtualHeight/8, virtualWidth/4, virtualHeight/16, 0.5, 0.5) txt:setAlignment(MOAITextBox.CENTER_JUSTIFY, MOAITextBox.CENTER_JUSTIFY) txt:setString('Press something to exit') table.insert(textboxes, txt) print(state.name.." init() done.") end function state:gotFocus() print(state.name.." got focus") local function introFunc() textboxes[1]:setString('I guess this is the\n"HELLO WORLD!"\nexample.') local spoolAction = textboxes[1]:spool() MOAIThread.blockOnAction(spoolAction) Draggin:wait(1) for i = 2, #textboxes - 1 do textboxes[i]:insertIntoLayer(mainlayer) end Draggin:wait(1) textboxes[#textboxes]:insertIntoLayer(mainlayer) textboxes[#textboxes]:blink(1) end state.introThread = MOAIThread.new() state.introThread:run(introFunc) -- Make this state's layers the current render table -- Only one render table can be actively rendered MOAIRenderMgr.setRenderTable(layers) end function state:lostFocus() print(state.name.." lost focus") for i = 1, #textboxes do textboxes[i]:removeFromLayer() end end return state end return textstate
mit
ShieldTeams/oldsdp
plugins/admin.lua
1
10316
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Function to add log supergroup local function logadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = {} save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id save_data(_config.moderation.data, data) local text = 'Log SuperGroup has has been set!' reply_msg(msg.id,text,ok_cb,false) return end --Function to remove log supergroup local function logrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = nil save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'Log SuperGroup has has been removed!' reply_msg(msg.id,text,ok_cb,false) return end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairsByKeys(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function reload_plugins( ) plugins = {} return load_plugins() end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if not is_admin1(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then local text = "Message From "..(msg.from.username or msg.from.last_name).."\n\nMessage : "..matches[3] send_large_msg("user#id"..matches[2],text) return "Message has been sent" end if matches[1] == "pmblock" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "pmunblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then if not is_sudo(msg) then-- Sudo only return end get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then if not is_sudo(msg) then-- Sudo only return end del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "addcontact" and is_sudo(msg) then phone = matches[2] first_name = matches[3] last_name = matches[4] add_contact(phone, first_name, last_name, ok_cb, false) return "User With Phone +"..matches[2].." has been added" end if matches[1] == "sendcontact" and is_sudo(msg) then phone = matches[2] first_name = matches[3] last_name = matches[4] send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false) end if matches[1] == "mycontact" and is_sudo(msg) then if not msg.from.phone then return "I must Have Your Phone Number!" end phone = msg.from.phone first_name = (msg.from.first_name or msg.from.phone) last_name = (msg.from.last_name or msg.from.id) send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false) end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent a group dialog list with both json and text format to your private messages" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end if matches[1] == 'reload' then receiver = get_receiver(msg) reload_plugins(true) post_msg(receiver, "", ok_cb, false) return "♻ تغییرات و بروز رسانی انجام شد :)\n➖➖➖➖➖➖➖➖➖➖➖\n🆔 Channel ™ : @Shield_Tm" end --[[*For Debug* if matches[1] == "vardumpmsg" and is_admin1(msg) then local text = serpent.block(msg, {comment=false}) send_large_msg("channel#id"..msg.to.id, text) end]] if matches[1] == 'updateid' then local data = load_data(_config.moderation.data) local long_id = data[tostring(msg.to.id)]['long_id'] if not long_id then data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) return "Updated ID WaderTG" end end if matches[1] == 'addlog' and not matches[2] then if is_log_group(msg) then return "Already a Log SuperGroup" end print("Log SuperGroup "..msg.to.title.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log SuperGroup") logadd(msg) end if matches[1] == 'remlog' and not matches[2] then if not is_log_group(msg) then return "Not a Log SuperGroup" end print("Log SuperGroup "..msg.to.title.."("..msg.to.id..") removed") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log SuperGroup") logrem(msg) end return end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(pmunblock) (%d+)$", "^(pmblock) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(addcontact) (.*) (.*) (.*)$", "^(sendcontact) (.*) (.*) (.*)$", "^(mycontact)$", "^(reload)$", "^(updateid)$", "^(addlog)$", "^(remlog)$", "%[(photo)%]", }, run = run, pre_process = pre_process } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/test/plugins/admin.lua ---Modified by @Rondoozle for supergroups
agpl-3.0
abbasgh12345/abbas
plugins/welcome.lua
190
3526
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nAbout :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n" local text = sambutan..about..rules.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Bye '..bye_name end end return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
bigdogmat/wire
lua/entities/gmod_wire_hologrid.lua
1
1780
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Holo Grid" ENT.Author = "Chad 'Jinto'" ENT.WireDebugName = "Holo Grid" if CLIENT then return end -- No more client function ENT:Initialize( ) self:PhysicsInit( SOLID_VPHYSICS ); self:SetMoveType( MOVETYPE_VPHYSICS ); self:SetSolid( SOLID_VPHYSICS ); self:SetUseType(SIMPLE_USE) self:Setup(false) -- create inputs. self.Inputs = WireLib.CreateSpecialInputs(self, { "UseGPS", "Reference" }, { "NORMAL", "ENTITY" }) self.reference = self end function ENT:Setup(UseGPS) if UseGPS then self.usesgps = true self:SetNWEntity( "reference", ents.GetByIndex(-1) ) self:SetOverlayText( "(GPS)" ) else self.usesgps = false self:SetNWEntity( "reference", self.reference ) self:SetOverlayText( "(Local)" ) end end function ENT:TriggerInput( inputname, value ) -- store values. if inputname == "UseGPS" then self:Setup(value ~= 0) elseif inputname == "Reference" then if IsValid(value) then self.reference = value else self.reference = self end self:Setup(self.usesgps) end end function ENT:Use( activator, caller ) if caller:IsPlayer() then self:Setup(not self.usesgps) end end duplicator.RegisterEntityClass("gmod_wire_hologrid", WireLib.MakeWireEnt, "Data", "usegps") function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.hologrid_usegps = self.usesgps and 1 or 0 if IsValid(self.reference) then info.reference = self.reference:EntIndex() else info.reference = nil end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.reference = GetEntByID(info.reference, self) self:Setup(info.hologrid_usegps ~= 0) end
apache-2.0
ld-test/oil
lua/oil/corba/services/event/ProxyPushConsumer.lua
7
3053
local oil = require "oil" local oo = require "oil.oo" local assert = require "oil.assert" module("oil.corba.services.event.ProxyPushConsumer", oo.class) -- Proxies are in one of three states: disconnected, connected, or destroyed. -- Push/pull operations are only valid in the connected state. function __init(class, admin) assert.results(admin) return oo.rawnew(class, { admin = admin, connected = false, push_supplier = nil }) end -- A supplier communicates event data to the consumer by invoking the push -- operation and passing the event data as a parameter. function push(self, data) if not self.connected then assert.exception{"IDL:omg.org/CosEventComm/Disconnected:1.0"} end local channel = self.admin.channel local event = channel.event_factory:create(data) channel.event_queue:enqueue(event) end -- A nil object reference may be passed to the connect_push_supplier operation. -- If so a channel cannot invoke the disconnect_push_supplier operation on the -- supplier. The supplier may be disconnected from the channel without being -- informed. If a nonnil reference is passed to connect_push_supplier, the -- implementation calls disconnect_push_supplier via that reference when the -- ProxyPushConsumer is destroyed. -- -- If the ProxyPushConsumer is already connected to a PushSupplier, then the -- AlreadyConnected exception is raised. function connect_push_supplier(self, push_supplier) if self.connected then assert.exception{"IDL:omg.org/CosEventChannelAdmin/AlreadyConnected:1.0"} end self.push_supplier = push_supplier self.admin:add_push_supplier(self, push_supplier) self.connected = true end -- The disconnect_push_consumer operation terminates the event communication. -- It releases resources used at the consumer to support the event -- communication. The PushConsumer object reference is disposed. Calling -- disconnect_push_consumer causes the implementation to call the -- disconnect_push_supplier operation on the corresponding PushSupplier -- interface (if that interface is known). -- -- Calling a disconnect operation on a consumer or supplier interface may cause -- a call to the corresponding disconnect operation on the connected supplier -- or consumer. Implementations must take care to avoid infinite recursive -- calls to these disconnect operations. If a consumer or supplier has received -- a disconnect call and subsequently receives another disconnect call, it shall -- raise a CORBA::OBJECT_NOT_EXIST exception. function disconnect_push_consumer(self) if not self.connected then assert.exception{"IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0"} end self.connected = false if self.push_supplier then -- supplier may be nil self.admin:rem_push_supplier(self, push_supplier) oil.pcall(self.push_supplier.disconnect_push_supplier, self.push_supplier) self.push_supplier = nil end end
mit
iceman1001/proxmark3
client/scripts/Legic_clone.lua
1
17251
--[[ script to create a clone-dump with new crc Author: mosci my Fork: https://github.com/icsom/proxmark3.git Upstream: https://github.com/Proxmark/proxmark3.git 1. read tag-dump, xor byte 22..end with byte 0x05 of the inputfile 2. write to outfile 3. set byte 0x05 to newcrc 4. until byte 0x21 plain like in inputfile 5. from 0x22..end xored with newcrc 6. calculate new crc on each segment (needs to know the new MCD & MSN0..2) simplest usage: read a valid legic tag with 'hf legic reader' save the dump with 'hf legic save orig.hex' place your 'empty' tag on the reader and run 'script run Legic_clone -i orig.hex -w' you will see some output like: read 1024 bytes from legic_dumps/j_0000.hex place your empty tag onto the PM3 to read and display the MCD & MSN0..2 the values will be shown below confirm whnen ready [y/n] ?y #db# setting up legic card #db# MIM 256 card found, reading card ... #db# Card read, use 'hf legic decode' or #db# 'data hexsamples 8' to view results 0b ad c0 de <- !! here you'll see the MCD & MSN of your empty tag, which has to be typed in manually as seen below !! type in MCD as 2-digit value - e.g.: 00 (default: 79 ) > 0b type in MSN0 as 2-digit value - e.g.: 01 (default: 28 ) > ad type in MSN1 as 2-digit value - e.g.: 02 (default: d1 ) > c0 type in MSN2 as 2-digit value - e.g.: 03 (default: 43 ) > de MCD:0b, MSN:ad c0 de, MCC:79 <- this crc is calculated from the MCD & MSN and must match the one on yout empty tag wrote 1024 bytes to myLegicClone.hex enter number of bytes to write? (default: 86 ) loaded 1024 samples #db# setting up legic card #db# MIM 256 card found, writing 0x00 - 0x01 ... #db# write successful ... #db# setting up legic card #db# MIM 256 card found, writing 0x56 - 0x01 ... #db# write successful proxmark3> the default value (number of bytes to write) is calculated over all valid segments and should be ok - just hit enter, wait until write has finished and your clone should be ready (except there has to be a additional KGH-CRC to be calculated - which credentials are unknown until yet) the '-w' switch will only work with my fork - it needs the binary legic_crc8 which is not part of the proxmark3-master-branch also the ability to write DCF is not possible with the proxmark3-master-branch but creating dumpfile-clone files will be possible (without valid segment-crc - this has to done manually with) (example) Legic-Prime Layout with 'Kaba Group Header' +----+----+----+----+----+----+----+----+ 0x00|MCD |MSN0|MSN1|MSN2|MCC | 60 | ea | 9f | +----+----+----+----+----+----+----+----+ 0x08| ff | 00 | 00 | 00 | 11 |Bck0|Bck1|Bck2| +----+----+----+----+----+----+----+----+ 0x10|Bck3|Bck4|Bck5|BCC | 00 | 00 |Seg0|Seg1| +----+----+----+----+----+----+----+----+ 0x18|Seg2|Seg3|SegC|Stp0|Stp1|Stp2|Stp3|UID0| +----+----+----+----+----+----+----+----+ 0x20|UID1|UID2|kghC| +----+----+----+ MCD= ManufacturerID (1 Byte) MSN0..2= ManufactureSerialNumber (3 Byte) MCC= CRC (1 Byte) calculated over MCD,MSN0..2 DCF= DecrementalField (2 Byte) 'credential' (enduser-Tag) seems to have always DCF-low=0x60 DCF-high=0xea Bck0..5= Backup (6 Byte) Bck0 'dirty-flag', Bck1..5 SegmentHeader-Backup BCC= BackupCRC (1 Byte) CRC calculated over Bck1..5 Seg0..3= SegmentHeader (on MIM 4 Byte ) SegC= SegmentCRC (1 Byte) calculated over MCD,MSN0..2,Seg0..3 Stp0..n= Stamp0... (variable length) length = Segment-Len - UserData - 1 UID0..n= UserDater (variable length - with KGH hex 0x00-0x63 / dec 0-99) length = Segment-Len - WRP - WRC - 1 kghC= KabaGroupHeader (1 Byte + addr 0x0c must be 0x11) as seen on ths example: addr 0x05..0x08 & 0x0c must have been set to this values - otherwise kghCRC will not be created by a official reader (not accepted) --]] example = "Script create a clone-dump of a dump from a Legic Prime Tag" author = "Mosci" desc = [[ This is a script which create a clone-dump of a dump from a Legic Prime Tag (MIM256 or MIM1024) (created with 'hf legic save my_dump.hex') requiered arguments: -i <input file> (file to read data from) optional arguments : -h - Help text -o <output file> - requieres option -c to be given -c <new-tag crc> - requieres option -o to be given -d - Display content of found Segments -s - Display summary at the end -w - write directly to Tag - a file myLegicClone.hex wille be generated also e.g.: hint: using the CRC '00' will result in a plain dump ( -c 00 ) Examples : script run legic_clone -i my_dump.hex -o my_clone.hex -c f8 script run legic_clone -i my_dump.hex -d -s ]] local utils = require('utils') local getopt = require('getopt') local bxor = bit32.bxor -- we need always 2 digits function prepend_zero(s) if (string.len(s)==1) then return "0" .. s else if (string.len(s)==0) then return "00" else return s end end end --- -- This is only meant to be used when errors occur function oops(err) print("ERROR: ",err) return nil, err end --- -- Usage help function help() print(desc) print("Example usage") print(example) end -- Check availability of file function file_check(file_name) local file_found=io.open(file_name, "r") if file_found==nil then file_found=false else file_found=true end return file_found end --- xor-wrapper -- xor all from addr 0x22 (start counting from 1 => 23) function xorme(hex, xor, index) if ( index >= 23 ) then return ('%02x'):format(bxor( tonumber(hex,16) , tonumber(xor,16) )) else return hex end end -- read input-file into array function getInputBytes(infile) local line local bytes = {} local fhi,err = io.open(infile) if err then print("OOps ... faild to read from file ".. infile); return false; end while true do line = fhi:read() if line == nil then break end for byte in line:gmatch("%w+") do table.insert(bytes, byte) end end fhi:close() print("\nread ".. #bytes .." bytes from ".. infile) return bytes end -- write to file function writeOutputBytes(bytes, outfile) local line local bcnt=0 local fho,err = io.open(outfile,"w") if err then print("OOps ... faild to open output-file ".. outfile); return false; end for i = 1, #bytes do if (bcnt == 0) then line=bytes[i] elseif (bcnt <= 7) then line=line.." "..bytes[i] end if (bcnt == 7) then -- write line to new file fho:write(line.."\n") -- reset counter & line bcnt=-1 line="" end bcnt=bcnt+1 end fho:close() print("\nwrote ".. #bytes .." bytes to " .. outfile) return true end -- xore certain bytes function xorBytes(inBytes, crc) local bytes = {} for index = 1, #inBytes do bytes[index] = xorme(inBytes[index], crc, index) end if (#inBytes == #bytes) then -- replace crc bytes[5] = string.sub(crc,-2) return bytes else print("error: byte-count missmatch") return false end end -- get raw segment-data function getSegmentData(bytes, start, index) local raw, len, valid, last, wrp, wrc, rd, crc local segment = {} segment[0] = bytes[start].." "..bytes[start+1].." "..bytes[start+2].." "..bytes[start+3] -- flag = high nibble of byte 1 segment[1] = string.sub(bytes[start+1],0,1) -- valid = bit 6 of byte 1 segment[2] = tonumber(bit32.extract("0x"..bytes[start+1],6,1),16) -- last = bit 7 of byte 1 segment[3] = tonumber(bit32.extract("0x"..bytes[start+1],7,1),16) -- len = (byte 0)+(bit0-3 of byte 1) segment[4] = tonumber(("%03x"):format(tonumber(bit32.extract("0x"..bytes[start+1],0,3),16)..tonumber(bytes[start],16)),16) -- wrp (write proteted) = byte 2 segment[5] = tonumber(bytes[start+2]) -- wrc (write control) - bit 4-6 of byte 3 segment[6] = tonumber(bit32.extract("0x"..bytes[start+3],4,3),16) -- rd (read disabled) - bit 7 of byte 3 segment[7] = tonumber(bit32.extract("0x"..bytes[start+3],7,1),16) -- crc byte 4 segment[8] = bytes[start+4] -- segment index segment[9] = index -- # crc-byte segment[10] = start+4 return segment end --- Kaba Group Header -- checks if a segment does have a kghCRC -- returns boolean false if no kgh has being detected or the kghCRC if a kgh was detected function CheckKgh(bytes, segStart, segEnd) if (bytes[8]=='9f' and bytes[9]=='ff' and bytes[13]=='11') then local i local data = {} segStart=tonumber(segStart,10) segEnd=tonumber(segEnd,10) local dataLen = segEnd-segStart-5 --- gather creadentials for verify local WRP = bytes[(segStart+2)] local WRC = ("%02x"):format(tonumber(bit32.extract("0x"..bytes[segStart+3],4,3),16)) local RD = ("%02x"):format(tonumber(bit32.extract("0x"..bytes[segStart+3],7,1),16)) local XX = "00" cmd = bytes[1]..bytes[2]..bytes[3]..bytes[4]..WRP..WRC..RD..XX for i=(segStart+5), (segStart+5+dataLen-2) do cmd = cmd..bytes[i] end local KGH=("%02x"):format(utils.Crc8Legic(cmd)) if (KGH==bytes[segEnd-1]) then return KGH else return false end else return false end end -- get only the addresses of segemnt-crc's and the length of bytes function getSegmentCrcBytes(bytes) local start=23 local index=0 local crcbytes = {} repeat seg = getSegmentData(bytes,start,index) crcbytes[index]= seg[10] start = start + seg[4] index = index + 1 until (seg[3] == 1 or tonumber(seg[9]) == 126 ) crcbytes[index] = start return crcbytes end -- print segment-data (hf legic decode like) function displaySegments(bytes) --display segment header(s) start=23 index="00" --repeat until last-flag ist set to 1 or segment-index has reached 126 repeat wrc="" wrp="" pld="" Seg = getSegmentData(bytes,start,index) KGH = CheckKgh(bytes,start,(start+tonumber(Seg[4],10))) printSegment(Seg) -- wrc if(Seg[6]>0) then print("WRC protected area:") -- length of wrc = wrc for i=1, Seg[6] do -- starts at (segment-start + segment-header + segment-crc)-1 wrc = wrc..bytes[(start+4+1+i)-1].." " end print(wrc) elseif(Seg[5]>0) then print("Remaining write protected area:") -- length of wrp = (wrp-wrc) for i=1, (Seg[5]-Seg[6]) do -- starts at (segment-start + segment-header + segment-crc + wrc)-1 wrp = wrp..bytes[(start+4+1+Seg[6]+i)-1].." " end print(wrp) end -- payload print("Remaining segment payload:") --length of payload = segment-len - segment-header - segment-crc - wrp -wrc for i=1, (Seg[4]-4-1-Seg[5]-Seg[6]) do -- starts at (segment-start + segment-header + segment-crc + segment-wrp + segemnt-wrc)-1 pld = pld..bytes[(start+4+1+Seg[5]+Seg[6]+i)-1].." " end print(pld) if (KGH) then print("'Kaba Group Header' detected"); end start = start+Seg[4] index = prepend_zero(tonumber(Seg[9])+1) until (Seg[3] == 1 or tonumber(Seg[9]) == 126 ) end -- print Segment values function printSegment(SegmentData) res = "\nSegment "..SegmentData[9]..": " res = res.. "raw header="..SegmentData[0]..", " res = res.. "flag="..SegmentData[1].." (valid="..SegmentData[2].." last="..SegmentData[3].."), " res = res.. "len="..("%04d"):format(SegmentData[4])..", " res = res.. "WRP="..prepend_zero(SegmentData[5])..", " res = res.. "WRC="..prepend_zero(SegmentData[6])..", " res = res.. "RD="..SegmentData[7]..", " res = res.. "crc="..SegmentData[8] print(res) end -- write clone-data to tag function writeToTag(plainBytes) local SegCrcs = {} if(utils.confirm("\nplace your empty tag onto the PM3 to read and display the MCD & MSN0..2\nthe values will be shown below\n confirm when ready") == false) then return end -- gather MCD & MSN from new Tag - this must be enterd manually cmd = 'hf legic read 0x00 0x04' core.console(cmd) print("\nthese are the MCD MSN0 MSN1 MSN2 from the Tag that has being read:") cmd = 'data hexsamples 4' core.console(cmd) print("^^ use this values as input for the following answers (one 2-digit-value per question/answer):") -- enter MCD & MSN (in hex) MCD = utils.input("type in MCD as 2-digit value - e.g.: 00", plainBytes[1]) MSN0 = utils.input("type in MSN0 as 2-digit value - e.g.: 01", plainBytes[2]) MSN1 = utils.input("type in MSN1 as 2-digit value - e.g.: 02", plainBytes[3]) MSN2 = utils.input("type in MSN2 as 2-digit value - e.g.: 03", plainBytes[4]) -- calculate crc8 over MCD & MSN cmd = MCD..MSN0..MSN1..MSN2 MCC = ("%02x"):format(utils.Crc8Legic(cmd)) print("MCD:"..MCD..", MSN:"..MSN0.." "..MSN1.." "..MSN2..", MCC:"..MCC) -- calculate new Segment-CRC for each valid segment SegCrcs = getSegmentCrcBytes(plainBytes) for i=0, (#SegCrcs-1) do -- SegCrcs[i]-4 = address of first byte of segmentHeader (low byte segment-length) segLen=tonumber(("%1x"):format(tonumber(bit32.extract("0x"..plainBytes[(SegCrcs[i]-3)],0,3),16))..("%02x"):format(tonumber(plainBytes[SegCrcs[i]-4],16)),16) segStart=(SegCrcs[i]-4) segEnd=(SegCrcs[i]-4+segLen) KGH=CheckKgh(plainBytes,segStart,segEnd) if (KGH) then print("'Kaba Group Header' detected - re-calculate...") end cmd = MCD..MSN0..MSN1..MSN2..plainBytes[SegCrcs[i]-4]..plainBytes[SegCrcs[i]-3]..plainBytes[SegCrcs[i]-2]..plainBytes[SegCrcs[i]-1] plainBytes[SegCrcs[i]] = ("%02x"):format(utils.Crc8Legic(cmd)) end -- apply MCD & MSN to plain data plainBytes[1] = MCD plainBytes[2] = MSN0 plainBytes[3] = MSN1 plainBytes[4] = MSN2 plainBytes[5] = MCC -- prepare plainBytes for writing (xor plain data with new MCC) bytes = xorBytes(plainBytes, MCC) -- write data to file if (writeOutputBytes(bytes, "myLegicClone.hex")) then WriteBytes = utils.input("enter number of bytes to write?", SegCrcs[#SegCrcs]) -- load file into pm3-buffer cmd = 'hf legic load myLegicClone.hex' core.console(cmd) -- write pm3-buffer to Tag for i=0, WriteBytes do if ( i<5 or i>6) then cmd = ('hf legic write 0x%02x 0x01'):format(i) core.console(cmd) elseif (i == 6) then -- write DCF in reverse order (requires 'mosci-patch') cmd = 'hf legic write 0x05 0x02' core.console(cmd) else print("skipping byte 0x05 - will be written next step") end utils.Sleep(0.2) end end end -- main function function main(args) -- some variables local i=0 local oldcrc, newcrc, infile, outfile local bytes = {} local segments = {} -- parse arguments for the script for o, a in getopt.getopt(args, 'hwsdc:i:o:') do -- output file if o == "o" then outfile = a ofs = true if (file_check(a)) then local answer = utils.confirm("\nthe output-file "..a.." alredy exists!\nthis will delete the previous content!\ncontinue?") if (answer==false) then return oops("quiting") end end end -- input file if o == "i" then infile = a if (file_check(infile)==false) then return oops("input file: "..infile.." not found") else bytes = getInputBytes(infile) oldcrc = bytes[5] ifs = true if (bytes == false) then return oops('couldnt get input bytes') end end i = i+1 end -- new crc if o == "c" then newcrc = a ncs = true end -- display segments switch if o == "d" then ds = true; end -- display summary switch if o == "s" then ss = true; end -- write to tag switch if o == "w" then ws = true; end -- help if o == "h" then return help() end end if (not ifs) then return oops("option -i <input file> is required but missing") end -- bytes to plain bytes = xorBytes(bytes, oldcrc) -- show segments (works only on plain bytes) if (ds) then print("+------------------------------------------- Segments -------------------------------------------+") displaySegments(bytes); end if (ofs and ncs) then -- xor bytes with new crc newBytes = xorBytes(bytes, newcrc) -- write output if (writeOutputBytes(newBytes, outfile)) then -- show summary if requested if (ss) then -- information res = "\n+-------------------------------------------- Summary -------------------------------------------+" res = res .."\ncreated clone_dump from\n\t"..infile.." crc: "..oldcrc.."\ndump_file:" res = res .."\n\t"..outfile.." crc: "..string.sub(newcrc,-2) res = res .."\nyou may load the new file with: hf legic load "..outfile res = res .."\n\nif you don't write to tag immediately ('-w' switch) you will need to recalculate each segmentCRC" res = res .."\nafter writing this dump to a tag!" res = res .."\n\na segmentCRC gets calculated over MCD,MSN0..3,Segment-Header0..3" res = res .."\ne.g. (based on Segment00 of the data from "..infile.."):" res = res .."\nhf legic crc8 "..bytes[1]..bytes[2]..bytes[3]..bytes[4]..bytes[23]..bytes[24]..bytes[25]..bytes[26] -- this can not be calculated without knowing the new MCD, MSN0..2 print(res) end end else if (ss) then -- show why the output-file was not written print("\nnew file not written - some arguments are missing ..") print("output file: ".. (ofs and outfile or "not given")) print("new crc: ".. (ncs and newcrc or "not given")) end end -- write to tag if (ws and #bytes == 1024) then writeToTag(bytes) end end -- call main with arguments main(args)
gpl-2.0
wrxck/mattata
plugins/administration/allowlist.lua
2
4984
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local allowlist = {} local mattata = require('mattata') local redis = require('libs.redis') function allowlist:init() allowlist.commands = mattata.commands(self.info.username):command('allowlist').table allowlist.help = '/allowlist [user] - Allowlists a user to use the bot in the current chat. This command can only be used by moderators and administrators of a supergroup.' end function allowlist:on_message(message, configuration, language) if message.chat.type ~= 'supergroup' then return mattata.send_reply( message, language['errors']['supergroup'] ) elseif not mattata.is_group_admin( message.chat.id, message.from.id ) then return mattata.send_reply( message, language['errors']['admin'] ) end local reason = false local input = message.reply and ( message.reply.from.username or tostring(message.reply.from.id) ) or mattata.input(message.text) if not input then local success = mattata.send_force_reply( message, language['allowlist']['1'] ) if success then redis:set( string.format( 'action:%s:%s', message.chat.id, success.result.message_id ), '/allowlist' ) end return elseif not message.reply then if input:match('^.- .-$') then reason = input:match(' (.-)$') input = input:match('^(.-) ') end elseif mattata.input(message.text) then reason = mattata.input(message.text) end if tonumber(input) == nil and not input:match('^%@') then input = '@' .. input end local user = mattata.get_user(input) or mattata.get_chat(input) -- Resolve the username/ID to a user object. if not user then return mattata.send_reply( message, language['errors']['unknown'] ) elseif user.result.id == self.info.id then return end user = user.result local status = mattata.get_chat_member( message.chat.id, user.id ) if not status then return mattata.send_reply( message, language['errors']['generic'] ) elseif mattata.is_group_admin( message.chat.id, user.id ) or status.result.status == 'creator' or status.result.status == 'administrator' then -- We won't try and allowlist moderators and administrators. return mattata.send_reply( message, language['allowlist']['2'] ) elseif status.result.status == 'left' or status.result.status == 'kicked' then -- Check if the user is in the group or not. return mattata.send_reply( message, status.result.status == 'left' and language['allowlist']['3'] or language['allowlist']['4'] ) end redis:del('group_allowlist:' .. message.chat.id .. ':' .. user.id) redis:hincrby( string.format( 'chat:%s:%s', message.chat.id, user.id ), 'allowlists', 1 ) if redis:hget( string.format( 'chat:%s:settings', message.chat.id ), 'log administrative actions' ) then mattata.send_message( mattata.get_log_chat(message.chat.id), string.format( '<pre>%s%s [%s] has allowlisted %s%s [%s] in %s%s [%s]%s.</pre>', message.from.username and '@' or '', message.from.username or mattata.escape_html(message.from.first_name), message.from.id, user.username and '@' or '', user.username or mattata.escape_html(user.first_name), user.id, message.chat.username and '@' or '', message.chat.username or mattata.escape_html(message.chat.title), message.chat.id, reason and ', for ' .. reason or '' ), 'html' ) end mattata.unban_chat_member(message.chat.id, user.id) -- attempt to unban the user too return mattata.send_message( message.chat.id, string.format( '<pre>%s%s has allowlisted %s%s%s.</pre>', message.from.username and '@' or '', message.from.username or mattata.escape_html(message.from.first_name), user.username and '@' or '', user.username or mattata.escape_html(user.first_name), reason and ', for ' .. reason or '' ), 'html' ) end return allowlist
mit
FrisKAY/MineOS_Server
lib/bigLetters.lua
1
10633
local unicode = require("unicode") local buffer = require("doubleBuffering") local bigLetters = {} local pixelHeight = 5 local lettersInterval = 2 local unknownSymbol = "*" local spaceWidth = 2 local letters = { ["0"] = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, }, ["1"] = { { 0, 1, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 0, 1, 0 }, { 1, 1, 1 }, }, ["2"] = { { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 }, }, ["3"] = { { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, }, ["4"] = { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, }, ["5"] = { { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, }, ["6"] = { { 1, 1, 1 }, { 1, 0, 0 }, { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, }, ["7"] = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, { 0, 0, 1 }, }, ["8"] = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, }, ["9"] = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 0, 1 }, { 1, 1, 1 }, }, ["a"] = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["b"] = { { 1, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 1, 1, 1}, }, ["c"] = { { 0, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 0, 1, 1, 1 }, }, ["d"] = { { 1, 1, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 0, 1, 0, 0, 1 }, { 0, 1, 0, 0, 1 }, { 1, 1, 1, 1, 0 }, }, ["e"] = { { 1, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 1 }, }, ["f"] = { { 1, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, }, ["g"] = { { 0, 1, 1, 1}, { 1, 0, 0, 0}, { 1, 0, 1, 1}, { 1, 0, 0, 1}, { 0, 1, 1, 1}, }, ["h"] = { { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 1, 1, 1, 1}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, }, ["i"] = { { 1, 1, 1}, { 0, 1, 0}, { 0, 1, 0}, { 0, 1, 0}, { 1, 1, 1}, }, ["j"] = { { 0, 0, 1}, { 0, 0, 1}, { 0, 0, 1}, { 1, 0, 1}, { 0, 1, 0}, }, ["k"] = { { 1, 0, 0, 1}, { 1, 0, 1, 0}, { 1, 1, 0, 0}, { 1, 0, 1, 0}, { 1, 0, 0, 1}, }, ["l"] = { { 1, 0, 0}, { 1, 0, 0}, { 1, 0, 0}, { 1, 0, 0}, { 1, 1, 1}, }, ["m"] = { { 1, 0, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, }, ["n"] = { { 1, 0, 0, 0, 1 }, { 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1 }, { 1, 0, 0, 1, 1 }, { 1, 0, 0, 0, 1 }, }, ["o"] = { { 0, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 0, 1, 1, 0}, }, ["p"] = { { 1, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, }, ["q"] = { { 0, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 1, 0, 1, 1}, { 0, 1, 1, 0}, }, ["r"] = { { 1, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, }, ["s"] = { { 0, 1, 1, 1}, { 1, 0, 0, 0}, { 0, 1, 1, 0}, { 0, 0, 0, 1}, { 1, 1, 1, 0}, }, ["t"] = { { 1, 1, 1, 1, 1 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, }, ["u"] = { { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 1, 0, 0, 1}, { 0, 1, 1, 0}, }, ["v"] = { { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0 }, }, ["w"] = { { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 }, { 0, 1, 0, 1, 0 }, }, ["x"] = { { 1, 0, 0, 0, 1 }, { 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 1, 0, 0, 0, 1 }, }, ["y"] = { { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["z"] = { { 1, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 0 }, { 1, 1, 1, 1, 1 }, }, ["а"] = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["б"] = { { 1, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["в"] = { { 1, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["г"] = { { 1, 1, 1 }, { 1, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, }, ["д"] = { { 0, 0, 1, 1, 0 }, { 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0 }, { 1, 1, 1, 1, 1 }, }, ["е"] = { { 1, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 1 }, }, ["ё"] = { { 1, 0, 1, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 1 }, }, ["ж"] = { { 1, 0, 1, 0, 1 }, { 0, 1, 1, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, }, ["з"] = { { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 1 }, { 0, 0, 1, 1, 0 }, { 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 0 }, }, ["и"] = { { 1, 0, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, }, ["й"] = { { 0, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, }, ["к"] = { { 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0 }, { 1, 1, 0, 0, 0 }, { 1, 0, 1, 0, 0 }, { 1, 0, 0, 1, 0 }, }, ["л"] = { { 0, 0, 1, 1 }, { 0, 1, 0, 1 }, { 0, 1, 0, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["м"] = { { 1, 0, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, }, ["н"] = { { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["о"] = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 0 }, }, ["п"] = { { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["р"] = { { 1, 1, 1, 0}, { 1, 0, 0, 1}, { 1, 1, 1, 0}, { 1, 0, 0, 0}, { 1, 0, 0, 0}, }, ["с"] = { { 0, 1, 1, 1 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 0, 1, 1, 1 }, }, ["т"] = { { 1, 1, 1, 1, 1 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, }, ["у"] = { { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["ф"] = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 0, 1, 1, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, }, ["х"] = { { 1, 0, 0, 0, 1 }, { 0, 1, 0, 1, 0 }, { 0, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0 }, { 1, 0, 0, 0, 1 }, }, ["ц"] = { { 1, 0, 0, 1, 0 }, { 1, 0, 0, 1, 0 }, { 1, 0, 0, 1, 0 }, { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, }, ["ч"] = { { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, }, ["ш"] = { { 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 }, { 1, 1, 1, 1, 1 }, }, ["щ"] = { { 1, 0, 0, 0, 1, 0 }, { 1, 0, 0, 0, 1, 0 }, { 1, 0, 1, 0, 1, 0 }, { 1, 0, 1, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1 }, }, ["ъ"] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 0 }, { 0, 1, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 0, 1, 1, 1, 0 }, }, ["ы"] = { { 1, 0, 0, 0, 0, 1 }, { 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 0, 1 }, { 1, 0, 0, 1, 0, 1 }, { 1, 1, 1, 0, 0, 1 }, }, ["ь"] = { { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["э"] = { { 1, 1, 1, 0 }, { 0, 0, 0, 1 }, { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 1, 1, 1, 0 }, }, ["ю"] = { { 1, 0, 0, 1, 1, 0 }, { 1, 0, 1, 0, 0, 1 }, { 1, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1, 0 }, }, ["я"] = { { 0, 1, 1, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, }, ["-"] = { { 0, 0, 0 }, { 0, 0, 0 }, { 1, 1, 1 }, { 0, 0, 0 }, { 0, 0, 0 }, }, ["_"] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 1, 1, 1 }, }, ["+"] = { { 0, 0, 0 }, { 0, 1, 0 }, { 1, 1, 1 }, { 0, 1, 0 }, { 0, 0, 0 }, }, ["*"] = { { 0, 0, 0 }, { 1, 0, 1 }, { 0, 1, 0 }, { 1, 0, 1 }, { 0, 0, 0 }, }, ["…"] = { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 }, }, } function bigLetters.draw(x, y, color, symbol, drawWithSymbol) if symbol == " " then return spaceWidth elseif not letters[symbol] then symbol = unknownSymbol end for j = 1, #letters[symbol] do for i = 1, #letters[symbol][j] do if letters[symbol][j][i] == 1 then if not drawWithSymbol then buffer.square(x + i * 2 - 2, y + (pixelHeight - #letters[symbol]) + j - 1, 2, 1, color, 0xFFFFFF, " ") else buffer.text(x + i * 2 - 2, y + (pixelHeight - #letters[symbol]) + j - 1, color, "*") end end end end return #letters[symbol][1] end function bigLetters.drawText(x, y, color, stroka, drawWithSymbol) checkArg(4, stroka, "string") for i = 1, unicode.len(stroka) do x = x + bigLetters.draw(x, y, color, unicode.sub(stroka, i, i), drawWithSymbol) * 2 + lettersInterval end return x end function bigLetters.getTextSize(text) local width, height = 0, 0 local symbol, symbolWidth, symbolHeight for i = 1, unicode.len(text) do symbol = unicode.sub(text, i, i) if symbol == " " then symbolWidth = spaceWidth symbolHeight = 5 elseif not letters[symbol] then symbolHeight = #letters[unknownSymbol] symbolWidth = #letters[unknownSymbol][1] else symbolHeight = #letters[symbol] symbolWidth = #letters[symbol][1] end width = width + symbolWidth * 2 + lettersInterval height = math.max(height, symbolHeight) end return (width - lettersInterval), height end return bigLetters
gpl-3.0
ikekonglp/DiscoParser
torch/tdnn.lua
1
2515
require 'nn' require 'cunn' require 'nngraph' require 'sys' tdnn = {} function tdnn.config(cmd) cmd:option('-vocabSize', 0, 'size of vocabulary') -- Used defaults from Yoon's paper. cmd:option('-embedSize', 300, 'size of embedding vec') cmd:option('-hiddenSize', 100, 'size of hidden layers') cmd:option('-kernelSizeA', 3, 'size of conv kernel') cmd:option('-kernelSizeB', 4, 'size of conv kernel') cmd:option('-kernelSizeC', 5, 'size of conv kernel') cmd:option('-L2s', 3, 'renorm value') end function tdnn.build(config, init_embed) -- Name parameters. local V = config.vocabSize local D = config.embedSize local L = 3 local H = config.hiddenSize local K = {config.kernelSizeA, config.kernelSizeB, config.kernelSizeC} local M = config.maxPoolSize local O = config.labels local input = nn.Identity()() -- Start by embedding and if given, use the passed in (w2v) weights. local embed = nn.LookupTable(V, D) if init_embed then print(init_embed:size()) embed.weight:copy(init_embed) end local inlayer = embed(input) -- Now do L (3) convolutions with different kernels. -- Each consists of a temporal conv and a max-over-time. local pen = {} for i = 1, L do local temporal = nn.TemporalConvolution(D, H, K[i])(inlayer) local nonlin = nn.ReLU()(temporal) table.insert(pen, nn.Max(3)(nn.Transpose({2,3})(nonlin))) end -- Concat the input layers add dropout, throw into softmax-. local penultimate = nn.JoinTable(2)(pen) return nn.gModule({input}, {penultimate}) end function tdnn.build_pairwise(config, init_embed) -- Name parameters. local V = config.vocabSize local D = config.embedSize local H = config.hiddenSize local input = nn.Identity()() local embed = nn.LookupTable(2*V, D) if init_embed then embed.weight:narrow(1,1,V):copy(init_embed) embed.weight:narrow(1,V,V):copy(init_embed) end local inlayer = nn.Transpose({2, 4})(nn.View(30, 30, 2*D)(embed(input))) local temporal = nn.SpatialConvolution(2*D, H, 2, 2)(inlayer) local nonlin = temporal local pen = nn.ReLU()(nn.Max(3)(nn.Max(4)(nonlin))) local penultimate = pen return nn.gModule({input}, {penultimate}) end function tdnn.rescale(linear, config) local w = linear.weight local n = linear.weight:view(w:size(1)*w:size(2)):norm() if (n > config.L2s) then w:mul(config.L2s):div(n) end end return tdnn
gpl-2.0
MeGaReborn/megareborn
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
arventwei/WioEngine
Tools/jamplus/src/luaplus/Src/Modules/socket/test/httptest.lua
19
11480
-- needs Alias from /home/c/diego/tec/luasocket/test to -- "/luasocket-test" and "/luasocket-test/" -- needs ScriptAlias from /home/c/diego/tec/luasocket/test/cgi -- to "/luasocket-test-cgi" and "/luasocket-test-cgi/" -- needs "AllowOverride AuthConfig" on /home/c/diego/tec/luasocket/test/auth local socket = require("socket") local http = require("socket.http") local url = require("socket.url") local mime = require("mime") local ltn12 = require("ltn12") -- override protection to make sure we see all errors -- socket.protect = function(s) return s end dofile("testsupport.lua") local host, proxy, request, response, index_file local ignore, expect, index, prefix, cgiprefix, index_crlf http.TIMEOUT = 10 local t = socket.gettime() --host = host or "diego.student.princeton.edu" --host = host or "diego.student.princeton.edu" host = host or "localhost" proxy = proxy or "http://localhost:3128" prefix = prefix or "/luasocket-test" cgiprefix = cgiprefix or "/luasocket-test-cgi" index_file = "index.html" -- read index with CRLF convention index = readfile(index_file) local check_result = function(response, expect, ignore) for i,v in pairs(response) do if not ignore[i] then if v ~= expect[i] then local f = io.open("err", "w") f:write(tostring(v), "\n\n versus\n\n", tostring(expect[i])) f:close() fail(i .. " differs!") end end end for i,v in pairs(expect) do if not ignore[i] then if v ~= response[i] then local f = io.open("err", "w") f:write(tostring(response[i]), "\n\n versus\n\n", tostring(v)) v = string.sub(type(v) == "string" and v or "", 1, 70) f:close() fail(i .. " differs!") end end end print("ok") end local check_request = function(request, expect, ignore) local t if not request.sink then request.sink, t = ltn12.sink.table() end request.source = request.source or (request.body and ltn12.source.string(request.body)) local response = {} response.code, response.headers, response.status = socket.skip(1, http.request(request)) if t and #t > 0 then response.body = table.concat(t) end check_result(response, expect, ignore) end ------------------------------------------------------------------------ io.write("testing request uri correctness: ") local forth = cgiprefix .. "/request-uri?" .. "this+is+the+query+string" local back, c, h = http.request("http://" .. host .. forth) if not back then fail(c) end back = url.parse(back) if similar(back.query, "this+is+the+query+string") then print("ok") else fail(back.query) end ------------------------------------------------------------------------ io.write("testing query string correctness: ") forth = "this+is+the+query+string" back = http.request("http://" .. host .. cgiprefix .. "/query-string?" .. forth) if similar(back, forth) then print("ok") else fail("failed!") end ------------------------------------------------------------------------ io.write("testing document retrieval: ") request = { url = "http://" .. host .. prefix .. "/index.html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing redirect loop: ") request = { url = "http://" .. host .. cgiprefix .. "/redirect-loop" } expect = { code = 302 } ignore = { status = 1, headers = 1, body = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing invalid url: ") local r, e = http.request{url = host .. prefix} assert(r == nil and e == "invalid host ''") r, re = http.request(host .. prefix) assert(r == nil and e == re, tostring(r) ..", " .. tostring(re) .. " vs " .. tostring(e)) print("ok") io.write("testing invalid empty port: ") request = { url = "http://" .. host .. ":" .. prefix .. "/index.html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing post method: ") -- wanted to test chunked post, but apache doesn't support it... request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", body = index, -- remove content-length header to send chunked body headers = { ["content-length"] = string.len(index) } } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ --[[ io.write("testing proxy with post method: ") request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", body = index, headers = { ["content-length"] = string.len(index) }, proxy= proxy } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ]] ------------------------------------------------------------------------ io.write("testing simple post function: ") back = http.request("http://" .. host .. cgiprefix .. "/cat", index) assert(back == index) print("ok") ------------------------------------------------------------------------ io.write("testing ltn12.(sink|source).file: ") request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", source = ltn12.source.file(io.open(index_file, "rb")), sink = ltn12.sink.file(io.open(index_file .. "-back", "wb")), headers = { ["content-length"] = string.len(index) } } expect = { code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) back = readfile(index_file .. "-back") assert(back == index) os.remove(index_file .. "-back") ------------------------------------------------------------------------ io.write("testing ltn12.(sink|source).chain and mime.(encode|decode): ") local function b64length(len) local a = math.ceil(len/3)*4 local l = math.ceil(a/76) return a + l*2 end local source = ltn12.source.chain( ltn12.source.file(io.open(index_file, "rb")), ltn12.filter.chain( mime.encode("base64"), mime.wrap("base64") ) ) local sink = ltn12.sink.chain( mime.decode("base64"), ltn12.sink.file(io.open(index_file .. "-back", "wb")) ) request = { url = "http://" .. host .. cgiprefix .. "/cat", method = "POST", source = source, sink = sink, headers = { ["content-length"] = b64length(string.len(index)) } } expect = { code = 200 } ignore = { body_cb = 1, status = 1, headers = 1 } check_request(request, expect, ignore) back = readfile(index_file .. "-back") assert(back == index) os.remove(index_file .. "-back") ------------------------------------------------------------------------ io.write("testing http redirection: ") request = { url = "http://" .. host .. prefix } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ --[[ io.write("testing proxy with redirection: ") request = { url = "http://" .. host .. prefix, proxy = proxy } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ]] ------------------------------------------------------------------------ io.write("testing automatic auth failure: ") request = { url = "http://really:wrong@" .. host .. prefix .. "/auth/index.html" } expect = { code = 401 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing http redirection failure: ") request = { url = "http://" .. host .. prefix, redirect = false } expect = { code = 301 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing document not found: ") request = { url = "http://" .. host .. "/wrongdocument.html" } expect = { code = 404 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing auth failure: ") request = { url = "http://" .. host .. prefix .. "/auth/index.html" } expect = { code = 401 } ignore = { body = 1, status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing manual basic auth: ") request = { url = "http://" .. host .. prefix .. "/auth/index.html", headers = { authorization = "Basic " .. (mime.b64("luasocket:password")) } } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing automatic basic auth: ") request = { url = "http://luasocket:password@" .. host .. prefix .. "/auth/index.html" } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing auth info overriding: ") request = { url = "http://really:wrong@" .. host .. prefix .. "/auth/index.html", user = "luasocket", password = "password" } expect = { code = 200, body = index } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ io.write("testing cgi output retrieval (probably chunked...): ") request = { url = "http://" .. host .. cgiprefix .. "/cat-index-html" } expect = { body = index, code = 200 } ignore = { status = 1, headers = 1 } check_request(request, expect, ignore) ------------------------------------------------------------------------ local body io.write("testing simple request function: ") body = http.request("http://" .. host .. prefix .. "/index.html") assert(body == index) print("ok") ------------------------------------------------------------------------ io.write("testing HEAD method: ") local r, c, h = http.request { method = "HEAD", url = "http://www.tecgraf.puc-rio.br/~diego/" } assert(r and h and (c == 200), c) print("ok") ------------------------------------------------------------------------ io.write("testing host not found: ") local c, e = socket.connect("example.invalid", 80) local r, re = http.request{url = "http://example.invalid/does/not/exist"} assert(r == nil and e == re, tostring(r) .. " " .. tostring(re)) r, re = http.request("http://example.invalid/does/not/exist") assert(r == nil and e == re) print("ok") ------------------------------------------------------------------------ print("passed all tests") os.remove("err") print(string.format("done in %.2fs", socket.gettime() - t))
mit
parhamhp/supersp
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
dicebox/minetest-france
mods/unified_inventory/register.lua
3
19785
local S = unified_inventory.gettext local F = unified_inventory.fgettext minetest.register_privilege("creative", { description = S("Can use the creative inventory"), give_to_singleplayer = false, }) minetest.register_privilege("ui_full", { description = S("Forces Unified Inventory to be displayed in Full mode if Lite mode is configured globally"), give_to_singleplayer = false, }) local trash = minetest.create_detached_inventory("trash", { --allow_put = function(inv, listname, index, stack, player) -- if unified_inventory.is_creative(player:get_player_name()) then -- return stack:get_count() -- else -- return 0 -- end --end, on_put = function(inv, listname, index, stack, player) inv:set_stack(listname, index, nil) local player_name = player:get_player_name() minetest.sound_play("trash", {to_player=player_name, gain = 1.0}) end, }) trash:set_size("main", 1) unified_inventory.register_button("craft", { type = "image", image = "ui_craft_icon.png", tooltip = S("Crafting Grid") }) unified_inventory.register_button("craftguide", { type = "image", image = "ui_craftguide_icon.png", tooltip = S("Crafting Guide") }) unified_inventory.register_button("home_gui_set", { type = "image", image = "ui_sethome_icon.png", tooltip = S("Set home position"), hide_lite=true, action = function(player) local player_name = player:get_player_name() if minetest.check_player_privs(player_name, {home=true}) then unified_inventory.set_home(player, player:getpos()) local home = unified_inventory.home_pos[player_name] if home ~= nil then minetest.sound_play("dingdong", {to_player=player_name, gain = 1.0}) minetest.chat_send_player(player_name, S("Home position set to: %s"):format(minetest.pos_to_string(home))) end else minetest.chat_send_player(player_name, S("You don't have the \"home\" privilege!")) unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name]) end end, condition = function(player) return minetest.check_player_privs(player:get_player_name(), {home=true}) end, }) unified_inventory.register_button("home_gui_go", { type = "image", image = "ui_gohome_icon.png", tooltip = S("Go home"), hide_lite=true, action = function(player) local player_name = player:get_player_name() if minetest.check_player_privs(player_name, {home=true}) then minetest.sound_play("teleport", {to_player=player:get_player_name(), gain = 1.0}) unified_inventory.go_home(player) else minetest.chat_send_player(player_name, S("You don't have the \"home\" privilege!")) unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name]) end end, condition = function(player) return minetest.check_player_privs(player:get_player_name(), {home=true}) end, }) unified_inventory.register_button("misc_set_day", { type = "image", image = "ui_sun_icon.png", tooltip = S("Set time to day"), hide_lite=true, action = function(player) local player_name = player:get_player_name() if minetest.check_player_privs(player_name, {settime=true}) then minetest.sound_play("birds", {to_player=player_name, gain = 1.0}) minetest.set_timeofday((6000 % 24000) / 24000) minetest.chat_send_player(player_name, S("Time of day set to 6am")) else minetest.chat_send_player(player_name, S("You don't have the settime privilege!")) unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name]) end end, condition = function(player) return minetest.check_player_privs(player:get_player_name(), {settime=true}) end, }) unified_inventory.register_button("misc_set_night", { type = "image", image = "ui_moon_icon.png", tooltip = S("Set time to night"), hide_lite=true, action = function(player) local player_name = player:get_player_name() if minetest.check_player_privs(player_name, {settime=true}) then minetest.sound_play("owl", {to_player=player_name, gain = 1.0}) minetest.set_timeofday((21000 % 24000) / 24000) minetest.chat_send_player(player_name, S("Time of day set to 9pm")) else minetest.chat_send_player(player_name, S("You don't have the settime privilege!")) unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name]) end end, condition = function(player) return minetest.check_player_privs(player:get_player_name(), {settime=true}) end, }) unified_inventory.register_button("clear_inv", { type = "image", image = "ui_trash_icon.png", tooltip = S("Clear inventory"), action = function(player) local player_name = player:get_player_name() if not unified_inventory.is_creative(player_name) then minetest.chat_send_player(player_name, S("This button has been disabled outside" .." of creative mode to prevent" .." accidental inventory trashing." .."\nUse the trash slot instead.")) unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name]) return end player:get_inventory():set_list("main", {}) minetest.chat_send_player(player_name, S('Inventory cleared!')) minetest.sound_play("trash_all", {to_player=player_name, gain = 1.0}) end, condition = function(player) return unified_inventory.is_creative(player:get_player_name()) end, }) unified_inventory.register_page("craft", { get_formspec = function(player, perplayer_formspec) local formspecy = perplayer_formspec.formspec_y local formheadery = perplayer_formspec.form_header_y local player_name = player:get_player_name() local formspec = "background[2,"..formspecy..";6,3;ui_crafting_form.png]" formspec = formspec.."background[0,"..(formspecy + 3.5)..";8,4;ui_main_inventory.png]" formspec = formspec.."label[0,"..formheadery..";" ..F("Crafting").."]" formspec = formspec.."listcolors[#00000000;#00000000]" formspec = formspec.."list[current_player;craftpreview;6,"..formspecy..";1,1;]" formspec = formspec.."list[current_player;craft;2,"..formspecy..";3,3;]" formspec = formspec.."label[7,"..(formspecy + 1.5)..";" .. F("Trash:") .. "]" formspec = formspec.."list[detached:trash;main;7,"..(formspecy + 2)..";1,1;]" formspec = formspec.."listring[current_name;craft]" formspec = formspec.."listring[current_player;main]" if unified_inventory.is_creative(player_name) then formspec = formspec.."label[0,"..(formspecy + 1.5)..";" .. F("Refill:") .. "]" formspec = formspec.."list[detached:"..minetest.formspec_escape(player_name).."refill;main;0,"..(formspecy +2)..";1,1;]" end return {formspec=formspec} end, }) -- stack_image_button(): generate a form button displaying a stack of items -- -- The specified item may be a group. In that case, the group will be -- represented by some item in the group, along with a flag indicating -- that it's a group. If the group contains only one item, it will be -- treated as if that item had been specified directly. local function stack_image_button(x, y, w, h, buttonname_prefix, item) local name = item:get_name() local count = item:get_count() local show_is_group = false local displayitem = name.." "..count local selectitem = name if name:sub(1, 6) == "group:" then local group_name = name:sub(7) local group_item = unified_inventory.get_group_item(group_name) show_is_group = not group_item.sole displayitem = group_item.item or "unknown" selectitem = group_item.sole and displayitem or name end local label = show_is_group and "G" or "" local buttonname = minetest.formspec_escape(buttonname_prefix..unified_inventory.mangle_for_formspec(selectitem)) local button = string.format("item_image_button[%f,%f;%f,%f;%s;%s;%s]", x, y, w, h, minetest.formspec_escape(displayitem), buttonname, label) if show_is_group then local groupstring, andcount = unified_inventory.extract_groupnames(name) local grouptip if andcount == 1 then grouptip = string.format(S("Any item belonging to the %s group"), groupstring) elseif andcount > 1 then grouptip = string.format(S("Any item belonging to the groups %s"), groupstring) end grouptip = minetest.formspec_escape(grouptip) if andcount >= 1 then button = button .. string.format("tooltip[%s;%s]", buttonname, grouptip) end end return button end local recipe_text = { recipe = "Recipe %d of %d", usage = "Usage %d of %d", } local no_recipe_text = { recipe = "No recipes", usage = "No usages", } local role_text = { recipe = "Result", usage = "Ingredient", } local next_alt_text = { recipe = "Show next recipe", usage = "Show next usage", } local prev_alt_text = { recipe = "Show previous recipe", usage = "Show previous usage", } local other_dir = { recipe = "usage", usage = "recipe", } unified_inventory.register_page("craftguide", { get_formspec = function(player, perplayer_formspec) local formspecy = perplayer_formspec.formspec_y local formheadery = perplayer_formspec.form_header_y local craftresultx = perplayer_formspec.craft_result_x local craftresulty = perplayer_formspec.craft_result_y local player_name = player:get_player_name() local player_privs = minetest.get_player_privs(player_name) local formspec = "" formspec = formspec.."background[0,"..(formspecy + 3.5)..";8,4;ui_main_inventory.png]" formspec = formspec.."label[0,"..formheadery..";" .. F("Crafting Guide") .. "]" formspec = formspec.."listcolors[#00000000;#00000000]" local item_name = unified_inventory.current_item[player_name] if not item_name then return {formspec=formspec} end local item_name_shown if minetest.registered_items[item_name] and minetest.registered_items[item_name].description then item_name_shown = string.format(S("%s (%s)"), minetest.registered_items[item_name].description, item_name) else item_name_shown = item_name end local dir = unified_inventory.current_craft_direction[player_name] local rdir if dir == "recipe" then rdir = "usage" end if dir == "usage" then rdir = "recipe" end local crafts = unified_inventory.crafts_for[dir][item_name] local alternate = unified_inventory.alternate[player_name] local alternates, craft if crafts ~= nil and #crafts > 0 then alternates = #crafts craft = crafts[alternate] end formspec = formspec.."background[0.5,"..(formspecy + 0.2)..";8,3;ui_craftguide_form.png]" formspec = formspec.."textarea["..craftresultx..","..craftresulty ..";10,1;;"..minetest.formspec_escape(F(role_text[dir])..": "..item_name_shown)..";]" formspec = formspec..stack_image_button(0, formspecy, 1.1, 1.1, "item_button_" .. rdir .. "_", ItemStack(item_name)) if not craft then formspec = formspec.."label[5.5,"..(formspecy + 2.35)..";" ..minetest.formspec_escape(F(no_recipe_text[dir])).."]" local no_pos = dir == "recipe" and 4.5 or 6.5 local item_pos = dir == "recipe" and 6.5 or 4.5 formspec = formspec.."image["..no_pos..","..formspecy..";1.1,1.1;ui_no.png]" formspec = formspec..stack_image_button(item_pos, formspecy, 1.1, 1.1, "item_button_" ..other_dir[dir].."_", ItemStack(item_name)) if player_privs.give == true or player_privs.creative == true or minetest.setting_getbool("creative_mode") == true then formspec = formspec.."label[0,"..(formspecy + 2.10)..";" .. F("Give me:") .. "]" .."button[0, "..(formspecy + 2.7)..";0.6,0.5;craftguide_giveme_1;1]" .."button[0.6,"..(formspecy + 2.7)..";0.7,0.5;craftguide_giveme_10;10]" .."button[1.3,"..(formspecy + 2.7)..";0.8,0.5;craftguide_giveme_99;99]" end return {formspec = formspec} end local craft_type = unified_inventory.registered_craft_types[craft.type] or unified_inventory.craft_type_defaults(craft.type, {}) if craft_type.icon then formspec = formspec..string.format(" image[%f,%f;%f,%f;%s]",5.7,(formspecy + 0.05),0.5,0.5,craft_type.icon) end formspec = formspec.."label[5.5,"..(formspecy + 1)..";" .. minetest.formspec_escape(craft_type.description).."]" formspec = formspec..stack_image_button(6.5, formspecy, 1.1, 1.1, "item_button_usage_", ItemStack(craft.output)) local display_size = craft_type.dynamic_display_size and craft_type.dynamic_display_size(craft) or { width = craft_type.width, height = craft_type.height } local craft_width = craft_type.get_shaped_craft_width and craft_type.get_shaped_craft_width(craft) or display_size.width -- This keeps recipes aligned to the right, -- so that they're close to the arrow. local xoffset = 5.5 -- Offset factor for crafting grids with side length > 4 local of = (3/math.max(3, math.max(display_size.width, display_size.height))) local od = 0 -- Minimum grid size at which size optimazation measures kick in local mini_craft_size = 6 if display_size.width >= mini_craft_size then od = math.max(1, display_size.width - 2) xoffset = xoffset - 0.1 end -- Size modifier factor local sf = math.min(1, of * (1.05 + 0.05*od)) -- Button size local bsize_h = 1.1 * sf local bsize_w = bsize_h if display_size.width >= mini_craft_size then bsize_w = 1.175 * sf end if (bsize_h > 0.35 and display_size.width) then for y = 1, display_size.height do for x = 1, display_size.width do local item if craft and x <= craft_width then item = craft.items[(y-1) * craft_width + x] end -- Flipped x, used to build formspec buttons from right to left local fx = display_size.width - (x-1) -- x offset, y offset local xof = (fx-1) * of + of local yof = (y-1) * of + 1 if item then formspec = formspec..stack_image_button( xoffset - xof, formspecy - 1 + yof, bsize_w, bsize_h, "item_button_recipe_", ItemStack(item)) else -- Fake buttons just to make grid formspec = formspec.."image_button[" ..tostring(xoffset - xof)..","..tostring(formspecy - 1 + yof) ..";"..bsize_w..","..bsize_h..";ui_blank_image.png;;]" end end end else -- Error formspec = formspec.."label[" ..tostring(2)..","..tostring(formspecy) ..";"..minetest.formspec_escape(S("This recipe is too\nlarge to be displayed.")).."]" end if craft_type.uses_crafting_grid and display_size.width <= 3 then formspec = formspec.."label[0,"..(formspecy + 0.9)..";" .. F("To craft grid:") .. "]" .."button[0, "..(formspecy + 1.5)..";0.6,0.5;craftguide_craft_1;1]" .."button[0.6,"..(formspecy + 1.5)..";0.7,0.5;craftguide_craft_10;10]" .."button[1.3,"..(formspecy + 1.5)..";0.8,0.5;craftguide_craft_max;" .. F("All") .. "]" end if player_privs.give == true or player_privs.creative == true or minetest.setting_getbool("creative_mode") == true then formspec = formspec.."label[0,"..(formspecy + 2.1)..";" .. F("Give me:") .. "]" .."button[0, "..(formspecy + 2.7)..";0.6,0.5;craftguide_giveme_1;1]" .."button[0.6,"..(formspecy + 2.7)..";0.7,0.5;craftguide_giveme_10;10]" .."button[1.3,"..(formspecy + 2.7)..";0.8,0.5;craftguide_giveme_99;99]" end if alternates and alternates > 1 then formspec = formspec.."label[5.5,"..(formspecy + 1.6)..";" ..string.format(F(recipe_text[dir]), alternate, alternates).."]" .."image_button[5.5,"..(formspecy + 2)..";1,1;ui_left_icon.png;alternate_prev;]" .."image_button[6.5,"..(formspecy + 2)..";1,1;ui_right_icon.png;alternate;]" .."tooltip[alternate_prev;"..F(prev_alt_text[dir]).."]" .."tooltip[alternate;"..F(next_alt_text[dir]).."]" end return {formspec = formspec} end, }) local function craftguide_giveme(player, formname, fields) local amount for k, v in pairs(fields) do amount = k:match("craftguide_giveme_(.*)") if amount then break end end if not amount then return end amount = tonumber(amount) if amount == 0 then return end local player_name = player:get_player_name() local output = unified_inventory.current_item[player_name] if (not output) or (output == "") then return end local player_inv = player:get_inventory() player_inv:add_item("main", {name = output, count = amount}) end -- tells if an item can be moved and returns an index if so local function item_fits(player_inv, craft_item, needed_item) local need_group = string.sub(needed_item, 1, 6) == "group:" if need_group then need_group = string.sub(needed_item, 7) end if craft_item and not craft_item:is_empty() then local ciname = craft_item:get_name() -- abort if the item there isn't usable if ciname ~= needed_item and not need_group then return end -- abort if no item fits onto it if craft_item:get_count() >= craft_item:get_definition().stack_max then return end -- use the item there if it's in the right group and a group item is needed if need_group then if minetest.get_item_group(ciname, need_group) == 0 then return end needed_item = ciname need_group = false end end if need_group then -- search an item of the specific group for i,item in pairs(player_inv:get_list("main")) do if not item:is_empty() and minetest.get_item_group(item:get_name(), need_group) > 0 then return i end end -- no index found return end -- search an item with a the name needed_item for i,item in pairs(player_inv:get_list("main")) do if not item:is_empty() and item:get_name() == needed_item then return i end end -- no index found end -- modifies the player inventory and returns the changed craft_item if possible local function move_item(player_inv, craft_item, needed_item) local stackid = item_fits(player_inv, craft_item, needed_item) if not stackid then return end local wanted_stack = player_inv:get_stack("main", stackid) local taken_item = wanted_stack:take_item() player_inv:set_stack("main", stackid, wanted_stack) if not craft_item or craft_item:is_empty() then return taken_item end craft_item:add_item(taken_item) return craft_item end local function craftguide_craft(player, formname, fields) local amount for k, v in pairs(fields) do amount = k:match("craftguide_craft_(.*)") if amount then break end end if not amount then return end local player_name = player:get_player_name() local output = unified_inventory.current_item[player_name] if (not output) or (output == "") then return end local player_inv = player:get_inventory() local crafts = unified_inventory.crafts_for[unified_inventory.current_craft_direction[player_name]][output] if (not crafts) or (#crafts == 0) then return end local alternate = unified_inventory.alternate[player_name] local craft = crafts[alternate] if craft.width > 3 then return end local needed = craft.items local craft_list = player_inv:get_list("craft") local width = craft.width if width == 0 then -- Shapeless recipe width = 3 end amount = tonumber(amount) or 99 --[[ if amount == "max" then amount = 99 -- Arbitrary; need better way to do this. else amount = tonumber(amount) end--]] for iter = 1, amount do local index = 1 for y = 1, 3 do for x = 1, width do local needed_item = needed[index] if needed_item then local craft_index = ((y - 1) * 3) + x local craft_item = craft_list[craft_index] local newitem = move_item(player_inv, craft_item, needed_item) if newitem then craft_list[craft_index] = newitem end end index = index + 1 end end end player_inv:set_list("craft", craft_list) unified_inventory.set_inventory_formspec(player, "craft") end minetest.register_on_player_receive_fields(function(player, formname, fields) for k, v in pairs(fields) do if k:match("craftguide_craft_") then craftguide_craft(player, formname, fields) return end if k:match("craftguide_giveme_") then craftguide_giveme(player, formname, fields) return end end end)
gpl-3.0
skylitedcpp/skylitedcpp
data/luascripts/quiet_login.lua
7
3439
--// quiet_login.lua -- stop spamming logfiles with MOTDs if not dcpp._chat_ready then math.randomseed( os.time() ) dcpp._chat_ready = {} end dcpp._chat_ready.func = function(hub, user, msg, me_msg) if string.find(msg, dcpp._chat_ready[hub]._cookie) then dcpp._chat_ready[hub]._ready = 1 DC():PrintDebug("Enabled mainchat for "..hub:getHubName()) return 1 end end dcpp:setListener("pm", "quiet_login", dcpp._chat_ready.func) dcpp:setListener("adcPm", "quiet_login", dcpp._chat_ready.func) dcpp:setListener( "userInf", "quiet_login", function( hub, user, flags ) if hub:getOwnSid() == user:getSid() and not dcpp._chat_ready[hub]._ready then DC():SendHubMessage( hub:getId(), string.format("DMSG %s %s %s PM%s\n", hub:getOwnSid(), hub:getOwnSid(), dcpp._chat_ready[hub]._cookie, hub:getOwnSid())) end end ) dcpp:setListener( "userMyInfo", "quiet_login", function( hub, user, message ) if hub:getOwnNick() == user:getNick() then -- Some Ptokax hubs seem not to reflect PMs or $SR's back. -- For them, detect 2nd myinfo. However: this only works -- If someone is an operator, because otherwise there's -- no update post-$OpList. dcpp._chat_ready[hub]._myInfoCount = dcpp._chat_ready[hub]._myInfoCount + 1 if dcpp._chat_ready[hub]._myInfoCount == 2 then DC():PrintDebug("Enabled mainchat for "..hub:getHubName()) dcpp._chat_ready[hub]._ready = 1 else user:sendPrivMsgFmt(dcpp._chat_ready[hub]._cookie, 1) end end end ) chatHandler = function( hub, user, text ) if not dcpp._chat_ready[hub]._ready then -- Other half of Ptokax workaround: the second post-$OpList chat -- message is always a non-MOTD message (the first might be, but -- only if the hub has disabled the MOTD). Risks delaying a chat -- message, but allows non-op users to squelch Ptokax MOTDs. if hub.gotOpList and hub:gotOpList() then cc = dcpp._chat_ready[hub]._postOpListChatCount dcpp._chat_ready[hub]._postOpListChatCount = cc + 1 if cc == 1 then dcpp._chat_ready[hub]._ready = 1 -- Don't block this message. return nil end end dcpp._chat_ready[hub]._text = dcpp._chat_ready[hub]._text .. text .. "\n" return 1 end end dcpp:setListener( "chat", "quiet_login", chatHandler) dcpp:setListener( "adcChat", "quiet_login", chatHandler) dcpp:setListener( "unknownchat", "quiet_login", function( hub, text ) if not dcpp._chat_ready[hub]._ready then dcpp._chat_ready[hub]._text = dcpp._chat_ready[hub]._text .. text .. "\n" return 1 end end ) dcpp:setListener( "connected", "quiet_login", function( hub ) rand = function() return math.random(1000000000,2100000000) end cookie = string.format("%d%d%d", rand(), rand(), rand()) dcpp._chat_ready[hub] = { _ready = nil, _text = "", _cookie = cookie, _myInfoCount = 0, _postOpListChatCount = 0 } end ) -- However, if login failed, best know why. dcpp:setListener( "disconnected", "quiet_login", function( hub ) -- If disconnected prematurely, show archived messages. -- They probably include error messages. if not dcpp._chat_ready[hub]._ready then DC():PrintDebug(dcpp._chat_ready[hub]._text) end dcpp._chat_ready[hub] = nil end ) DC():PrintDebug( " ** Loaded quiet_login.lua **" )
gpl-3.0
4w/xtend
xtend_default/init.lua
1
7019
--- Global table definitions. -- -- All functions, variables, and tables are held in a single global table -- prefixed `_xtend` for uniqueness. _xtend = { mods = {} } -- Initiate an xTend based mod. -- -- For loading and parsing the configuration, and setting other stuff, all -- xTend based mods need to initiate themselves by running this function first. -- -- @return void _xtend.init = function () local name = minetest.get_current_modname() local path = minetest.get_modpath(name) local config_file = io.open(path..DIR_DELIM..'settingtypes.txt', 'rb') local depends_file = io.open(path..DIR_DELIM..'depends.txt', 'rb') _xtend.mods[name] = { defaults = {}, depends = {}, modpath = path } if config_file ~= nil then local lines = {} for line in config_file:lines() do if line:match("^([a-zA-Z])") then local option = line:gsub(' .+', '') local value = line:gsub('^[^ ]+ %b() %a+ ', '') if value == line then value = '' end _xtend.mods[name].defaults[option] = value end end config_file:close() end if depends_file ~= nil then local lines = {} for line in depends_file:lines() do table.insert(_xtend.mods[name].depends, line) end depends_file:close() end end _xtend.init() -- init self -- Clean up after mod processing -- -- When not cleaning up after a mod unnecessary things from that mod could stay -- in the global _xtend table. For the sake of cleanlyness and resources do -- not pollute the global namespace or it’s tables. -- -- @param make_api An optional table of mod table entries that shall be -- converted to an API-like global table named after the mod. -- -- @return void _xtend.clean = function (make_api) local modname = minetest.get_current_modname() if make_api then local mod_table = table.copy(_xtend.mods[modname]) local api = {} for _,entry in pairs(make_api) do api[entry] = mod_table[entry] end rawset(_G, modname, api) -- https://www.lua.org/pil/14.2.html _xtend.log('Created API with members: '..table.concat(make_api, ', ')) end _xtend.mods[modname] = nil _xtend.log('Cleaned up') end --- Get a configuration or default value. -- -- Because Minetest does not provide a valid and sane way to get a value from -- the configuration or – if not present – get a given default value instead, -- this function exists. It searches the configuration for a value and if the -- value does not exist it returns the default value defined in this modpack’s -- `settingtypes.txt` file instead. -- -- @param value The descriptor of the value in question without the -- mod’s prefix. The prefix is added automatically and -- the given value plus prefix will be searched in the -- configuration. -- @param custom_modname Instead of using the calling mod’s name when searching -- for the configuration option use this modname instead. -- @return string The configuration value or the default value _xtend.get_option = function (parameter, custom_modname) local modname = custom_modname or minetest.get_current_modname() local setting = minetest.settings:get(modname..'_'..parameter) local default = '' if modname == 'xtend_default' then default = _xtend.default_settings[modname..'_'..parameter] else default = _xtend.mods[modname].defaults[modname..'_'..parameter] end return setting or default end --- Colorize the given text -- -- Colors the given text in the set color and resets the color to the set reset -- color and returns the result if colorization is enabled. If not enabled this -- function simply returns the given text without any changes. -- -- Attention mod authors: Use with care! Do not overdo it! :) -- -- @param text The text that has to be colorized if enabled -- @return string The colored (or not colored) text _xtend.colorize = function (text) local modname = 'xtend_default' if _xtend.get_option('enable_colorization', modname) == 'true' then local color = '#'.._xtend.get_option('colorization_color', modname) local reset = '#'.._xtend.get_option('reset_color', modname) local color_escape = minetest.get_color_escape_sequence(color) local reset_escape = minetest.get_color_escape_sequence(reset) return color_escape..text..reset_escape else return text end end --- Return a translated string. -- -- Since there currently is no valid convenient way to translate mods (nor -- is gettext used to translate mod strings) this function only returns -- the processed given string. -- -- With release of Minetest 0.5.0 client-side translations will be introduced -- and then the function will be altered to actually translate the string. -- -- As of now only the positional arguments are replaced. This is fully -- compatible with the previous syntax of this function. All mods using it -- should be slowly migrated from gsub() to the new syntax. -- -- @param string The string that is to be translated. Variables @n (where n -- is a number between 1-9) can be used and will be replaced -- with the positional varargs. -- @param ... Up to 9 positional varargs. Those arguments are used for -- replacing @n in the `string` value. -- @return result The translated string -- -- @link https://www.lua.org/pil/5.2.html -- @link http://lua-users.org/wiki/VarargTheSecondClassCitizen -- @link https://stackoverflow.com/questions/7183998 _xtend.translate = function (s, ...) local args = { ... } if #args > 0 then for n,v in pairs(args) do s = s:gsub('@'..n, v) end end return s end -- Output a debug message. -- -- Checks if debugging messages are enabled and if so reads and parses the -- given debug message format and prints a debug message wherever the function -- is called. -- -- @param information The information to be shown -- @return void _xtend.log = function (information, loglevel) local current_mod = minetest.get_current_modname() if loglevel == nil then loglevel = _xtend.get_option('loglevel', 'xtend_default') end local string = _xtend.get_option('log_format', 'xtend_default'):gsub('+.', { ['+i'] = information, ['+m'] = current_mod, ['+M'] = string.upper(current_mod), ['+n'] = '\n', ['+t'] = os.date('%H:%M:%S') }) minetest.log(loglevel, string) end -- Clean self -- -- Keep the default settings table `defaults` as API `xtend_default.defaults` -- because the `xtend_default_*` configuration options might be used indirectly -- by other mods through the functions provided via the `_xtend` table. _xtend.default_settings = table.copy(_xtend.mods.xtend_default.defaults) _xtend.clean()
gpl-3.0
nielsutrecht/computercraft
hydraapi.lua
1
4253
-- Returns a table with the sides and peripheral types function getPeripheralList() local sides = peripheral.getNames() local pTable = {} for k,side in pairs(sides) do pTable[side] = peripheral.getType(side) end return pTable end -- finds the first peripheral of type 'peripheralType' and wraps it function getPeripheral(peripheralType) local pTable = getPeripheralList() for side, pType in pairs(pTable) do if(peripheralType == pType) then return peripheral.wrap(side) end end return nil end -- finds all peripherals of type 'peripheralType' and wraps them function getAllPeripherals(peripheralType) local pTable = getPeripheralList() local wrappedTable = {} for side, pType in pairs(pTable) do if(peripheralType == pType) then wrappedTable[side] = peripheral.wrap(side) end end return wrappedTable end -- finds the first modem and wraps it function getModem(wireless) local modem = getAllPeripherals("modem") for k, m in pairs(modem) do if(m.isWireless() == wireless) then return m end end end -- finds the first monitor and wraps it function getMonitor() return getPeripheral("monitor") end -- finds the first crafting terminal and wraps it function getCraftingTerminal() return getPeripheral("me_crafting_terminal") end -- finds the first ME bridge and wraps it function getMeBridge() return getPeripheral("meBridge") end -- finds all redstone energy cells and wraps them function getAllEnergyCells() return getAllPeripherals("redstone_energy_cell") end -- finds all alvearies and wraps them function getAllAlvearies() return getAllPeripherals("alveary") end -- finds all BigReactor reactors and wraps them function getAllBigReactors() return getAllPeripherals("BigReactors-Reactor") end -- finds all BigReactor turbines and wraps them function getAllBigReactorTurbines() return getAllPeripherals("BigReactors-Turbine") end -- String split function, splits pString on pPattern function split(pString, pPattern) local Table = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pPattern local last_end = 1 local s, e, cap = pString:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(Table,cap) end last_end = e+1 s, e, cap = pString:find(fpat, last_end) end if last_end <= #pString then cap = pString:sub(last_end) table.insert(Table, cap) end return Table end -- Debug function: prints a table function printTable(t) if(t == nil) then print("**nil**") return end for k,v in pairs(t) do print(tostring(k) .. "=" .. tostring(v)) end end function round(number) return math.floor(number * 10) / 10 end function formatLargeNumber(amount) local postfix if(amount >= 1000000000) then amount = math.floor(amount / 100000000) / 10 postFix = "G" elseif(amount >= 1000000) then amount = math.floor(amount / 100000) / 10 postFix = "M" elseif(amount >= 1000) then amount = math.floor(amount / 100) / 10 postFix = "k" else postFix = "" end return tostring(round(amount)) .. postFix end function formatEnergy(amount) return formatLargeNumber(amount) .. "RF" end function formatPercent(fraction) percent = math.floor(fraction * 1000) / 10 return string.format("%3.1f", percent) .. "%" end function saveConfig(config, filename) local handle = fs.open(filename, "w") handle.write(textutils.serialize(config)) handle.close() end function loadConfig(filename) local config local handle = fs.open(filename, "r") if(handle ~= nil) then config = textutils.unserialize(handle.readAll()) handle.close() end return config end function padLeft(str, len) str = '' .. str local reps = len - #str if (reps < 0) then reps = 0 end return string.rep(' ', reps) .. str end -- Debug function: prints all connected peripherals function printPeripherals() printTable(getPeripheralList()) end
mit
jbking/python-stdnet
stdnet/backends/redisb/lua/columnts/reduce.lua
2
1442
local command = ARGV[1] local start = ARGV[2] local stop = ARGV[3] local points = math.max(ARGV[4] + 0, 2) local method = ARGV[5] -- One of 'mean', 'geometric', 'ma' local alpha = ARGV[6] + 0 -- paramether for moving avaerage reduction local num_fields = ARGV[7] local fields = tabletools.slice(ARGV, 8, -1) local ts = columnts:new(KEYS[1]) local time,values = unpack(ts:range(command, start, stop, fields)) local N = # times if N < points then return {times,values} else local space = math.floor(N/points) -- spacing for reduction while N/space > points do space = space + 1 end local rtime, reduced = {}, {} for field,value do local index, stop, fvalues = 1, 0, {} table.insert(reduced,field) table.insert(reduced,fvalues) while stop <= N do start = stop + 1 stop = N - (points-index)*space rtime[index] = time[stop] if method == 'mean' then fvalues[index] = reduce_mean(value,start,stop) elseif method == 'geometric' then fvalues[index] = reduce_geo(value,start,stop) elseif method == 'ma' then fvalues[index] = reduce_ma(value,start,stop,alpha) else fvalues[index] = value[stop] end index = index + 1 end end return {rtime, reduced} end
bsd-3-clause
pouria346/self2
bot/bot.lua
1
7300
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") require("./bot/permissions") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) -- 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, true, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() _gbans = load_gbans() -- 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 true 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 print('\27[36mNot valid: Telegram message\27[39m') return false 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 function save_gbans( ) serialize_to_file(_gbans, './data/gbans.lua') print ('saved gban into ./data/gbans.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('\27[93mAllowed user:\27[39m ' .. user) end return config end function load_gbans( ) local f = io.open('./data/gbans.lua', "r") -- If gbans.lua doesn't exist if not f then print ("Created new gbans file: data/gbans.lua") create_gbans() else f:close() end local gbans = loadfile ("./data/gbans.lua")() return gbans 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 = { "eng", "ctrl", "plugins", "poker", "version", "addplug", "help", "love", "share", "spammer", "joy", "xxx", "group", "getplug", "chat" }, sudo_users = {227841514}, admin_users = {}, disabled_channels = {} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function create_gbans( ) -- A simple config with basic plugins and ourselves as privileged user gbans = { gbans_users = {} } serialize_to_file(gbans, './data/gbans.lua') print ('saved gbans into ./data/gbans.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) --vardump (chat) 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('\27[92mLoading plugin '.. v..'\27[39m') 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 -- 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 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
cshore/luci
applications/luci-app-wshaper/luasrc/model/cbi/wshaper.lua
56
1848
-- Copyright 2011 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") m = Map("wshaper", translate("Wondershaper"), translate("Wondershaper shapes traffic to ensure low latencies for interactive traffic even when your " .. "internet connection is highly saturated.")) s = m:section(NamedSection, "settings", "wshaper", translate("Wondershaper settings")) s.anonymous = true network = s:option(ListValue, "network", translate("Interface")) luci.tools.webadmin.cbi_add_networks(network) uplink = s:option(Value, "uplink", translate("Uplink"), translate("Upstream bandwidth in kbit/s")) uplink.optional = false uplink.datatype = "uinteger" uplink.default = "240" uplink = s:option(Value, "downlink", translate("Downlink"), translate("Downstream bandwidth in kbit/s")) uplink.optional = false uplink.datatype = "uinteger" uplink.default = "200" nopriohostsrc = s:option(DynamicList, "nopriohostsrc", translate("Low priority hosts (Source)"), translate("Host or Network in CIDR notation.")) nopriohostsrc.optional = true nopriohostsrc.datatype = ipaddr nopriohostsrc.placeholder = "10.0.0.1/32" nopriohostdst = s:option(DynamicList, "nopriohostdst", translate("Low priority hosts (Destination)"), translate("Host or Network in CIDR notation.")) nopriohostdst.optional = true nopriohostdst.datatype = ipaddr nopriohostdst.placeholder = "10.0.0.1/32" noprioportsrc = s:option(DynamicList, "noprioportsrc", translate("Low priority source ports")) noprioportsrc.optional = true noprioportsrc.datatype = "range(0,65535)" noprioportsrc.placeholder = "21" noprioportdst = s:option(DynamicList, "noprioportdst", translate("Low priority destination ports")) noprioportdst.optional = true noprioportdst.datatype = "range(0,65535)" noprioportdst.placeholder = "21" return m
apache-2.0
adamel/sysdig
userspace/sysdig/chisels/spectrogram.lua
12
4048
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/>. --]] -- Chisel description description = "This console visualization shows the frequency of system call latencies. The Y axis unit is time. By default, a new line is created twice a second, but that can be changed by specifying a different refresh time argument. The X axis shows a range of latencies. Each latency value has a color that can be black (no calls), green (tens of calls/s), yellow (hundreds of calls/s) or red (Thousands of calls/s). In other words, red areas mean that there are many system calls taking the specified time to return. Use this chisel in conjunction with filters to visualize latencies for certain processes, types of I/O activity, file systems, etc." short_description = "Visualize OS latency in real time." category = "CPU Usage" -- Chisel argument list args = { { name = "refresh_time", description = "Chart refresh time in milliseconds", argtype = "int", optional = true }, } require "common" terminal = require "ansiterminal" terminal.enable_color(true) refresh_time = 500000000 refresh_per_sec = 1000000000 / refresh_time frequencies = {} colpalette = {22, 28, 64, 34, 2, 76, 46, 118, 154, 191, 227, 226, 11, 220, 209, 208, 202, 197, 9, 1} -- Argument initialization Callback function on_set_arg(name, val) if name == "refresh_time" then refresh_time = parse_numeric_input(val, name) * 1000000 refresh_per_sec = 1000000000 / refresh_time return true end return false end -- Initialization callback function on_init() is_tty = sysdig.is_tty() if not is_tty then print("This chisel only works on ANSI terminals. Aborting.") return false end tinfo = sysdig.get_terminal_info() w = tinfo.width h = tinfo.height chisel.set_filter("evt.dir=<") flatency = chisel.request_field("evt.latency") terminal.hidecursor() return true end -- Final chisel initialization function on_capture_start() chisel.set_interval_ns(refresh_time) return true end -- Event parsing callback function on_event() local latency = evt.field(flatency) if latency == 0 then return true end local llatency = math.log10(latency) if(llatency > 11) then llatency = 11 end local norm_llatency = math.floor(llatency * w / 11) + 1 if frequencies[norm_llatency] == nil then frequencies[norm_llatency] = 1 else frequencies[norm_llatency] = frequencies[norm_llatency] + 1 end return true end function mkcol(n) local col = math.floor(math.log10(n * refresh_per_sec + 1) / math.log10(1.6)) if col < 1 then col = 1 end if col > #colpalette then col = #colpalette end return colpalette[col] end -- Periodic timeout callback function on_interval(ts_s, ts_ns, delta) terminal.moveup(1) for x = 1, w do local fr = frequencies[x] if fr == nil or fr == 0 then terminal.setbgcol(0) else terminal.setbgcol(mkcol(fr)) end io.write(" ") end io.write(terminal.reset .. "\n") local x = 0 while true do if x >= w then break end local curtime = math.floor(x * 11 / w) local prevtime = math.floor((x - 1) * 11 / w) if curtime ~= prevtime then io.write("|") local tstr = format_time_interval(math.pow(10, curtime)) io.write(tstr) x = x + #tstr + 1 else io.write(" ") x = x + 1 end end io.write("\n") frequencies = {} return true end -- Called by the engine at the end of the capture (Ctrl-C) function on_capture_end(ts_s, ts_ns, delta) if is_tty then print(terminal.reset) terminal.showcursor() end return true end
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/modules/admin-full/luasrc/model/cbi/admin_network/wireless.lua
4
4146
--[[ 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: wireless.lua 5448 2009-10-31 15:54:11Z jow $ ]]-- require("luci.sys") require("luci.tools.webadmin") local wireless = luci.model.uci.cursor_state():get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end m = SimpleForm("wireless", translate("Wifi")) s = m:section(Table, ifaces, translate("Networks")) function s.extedit(self, section) local device = self.map:get(section, "device") or "" return luci.dispatcher.build_url(unpack(luci.dispatcher.context.requested.path)) .. "/" .. device end link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) s2 = m:section(SimpleSection, translate("Create Network")) create = s2:option(ListValue, "create", translate("Device")) create:value("", translate("-- Please choose --")) for k, v in pairs(wireless) do if v[".type"] == "wifi-device" then create:value(k) end end function create.write(self, section, value) local uci = luci.model.uci.cursor() uci:load("wireless") uci:section("wireless", "wifi-iface", nil, {device=value}) uci:save("wireless") luci.http.redirect(luci.dispatcher.build_url(unpack(luci.dispatcher.context.requested.path)) .. "/" .. value) end function create.cbid(self, section) return "priv.cbid.create" end return m
gpl-2.0
David1Socha/number-nibbler
hump/signal.lua
27
2769
--[[ Copyright (c) 2012-2013 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 Registry = {} Registry.__index = function(self, key) return Registry[key] or (function() local t = {} rawset(self, key, t) return t end)() end function Registry:register(s, f) self[s][f] = f return f end function Registry:emit(s, ...) for f in pairs(self[s]) do f(...) end end function Registry:remove(s, ...) local f = {...} for i = 1,select('#', ...) do self[s][f[i]] = nil end end function Registry:clear(...) local s = {...} for i = 1,select('#', ...) do self[s[i]] = {} end end function Registry:emit_pattern(p, ...) for s in pairs(self) do if s:match(p) then self:emit(s, ...) end end end function Registry:remove_pattern(p, ...) for s in pairs(self) do if s:match(p) then self:remove(s, ...) end end end function Registry:clear_pattern(p) for s in pairs(self) do if s:match(p) then self[s] = {} end end end -- the module local function new() local registry = setmetatable({}, Registry) return setmetatable({ new = new, register = function(...) return registry:register(...) end, emit = function(...) registry:emit(...) end, remove = function(...) registry:remove(...) end, clear = function(...) registry:clear(...) end, emit_pattern = function(...) registry:emit_pattern(...) end, remove_pattern = function(...) registry:remove_pattern(...) end, clear_pattern = function(...) registry:clear_pattern(...) end, }, {__call = new}) end return new()
mit
cochrane/OpenTomb
scripts/strings/italian/generic.lua
7
3453
-- OPENTOMB GENERIC STRINGS - ENGLISH LANGUAGE -- by Lwmte, Jan 2015 -- Italian Translation by: Nickotte. -------------------------------------------------------------------------------- -- This set of strings is used globally in all engine versions for various -- menu entries, notify pop-ups, inventory entries etc. -------------------------------------------------------------------------------- -- Game menu entries strings[000] = "Nuova Partita"; strings[001] = "Selezione Gioco"; strings[002] = "Selezione Livello"; strings[003] = "Casa di Lara"; strings[004] = "Salva Partita"; strings[005] = "Carica partita"; strings[006] = "Opzioni"; strings[007] = "Esci"; strings[008] = "Ricomincia Livello"; strings[009] = "Esci dai Titoli"; -- * -- Dialog components strings[010] = "Si"; strings[011] = "No"; strings[012] = "Applica"; strings[013] = "Annulla"; strings[014] = "Indietro"; strings[015] = "Avanti"; strings[016] = "OK"; strings[017] = "Annulla"; -- Interface headers strings[018] = "INVENTARIO"; strings[019] = "OGGETTI"; strings[020] = "PAUSA"; strings[021] = "OPZIONI"; strings[022] = "STATISTICHE"; -- Dialogs strings[023] = "Uscire dalla Partita?"; strings[024] = "Seleziona Partita da Caricare"; strings[025] = "Seleziona Partita da Salvare"; strings[026] = "Seleziona Oggetto da Combinare"; -- Inventory actions strings[027] = "Equipaggia"; strings[028] = "Seleziona Munizioni"; strings[029] = "Seleziona Modalità di Fuoco"; strings[030] = "Usa"; strings[031] = "Combina"; strings[032] = "Separa"; strings[033] = "Esamina"; strings[034] = "Lascia"; -- Interface hints strings[035] = " - Accetta"; strings[036] = " - Annulla"; strings[037] = "Tieni premuto il tasto sinistro del mouse e trascina per ruotare l'inventario."; strings[038] = "Usa la rotella del mouse per cambiare il menu dell'inventario."; strings[039] = "Tieni premuto il tasto destro del mouse e trascina per esaminare l'oggetto."; -- Statistics bar strings[040] = "Luogo: %s"; strings[041] = "Segreti: %d / %d"; strings[042] = "Distanza: %d km"; strings[043] = "Munizioni usate: %d"; strings[044] = "Uccisioni: %d"; strings[045] = "Medikit usati: %d"; -- * -- Notify pop-up tips - FIND A WAY TO USE THEM! strings[046] = "Premi il tasto CAPRIOLA mentre sei accucciato in TR3-5 per eseguire una capriola accucciata."; strings[047] = "In OpenTomb, Lara scivola sui pendii nella loro esatta direzione."; strings[048] = "Lo sapevi che almeno dieci diversi programmatori hanno lavorato su OpenTomb?"; -- ;) strings[049] = "Lo sapevi che la Core Design non ha mai rilasciato alcun codice sorgente di Tomb Raider?"; -- Whatever... :] -- String masks strings[090] = "%s (%d)" -- Inventory item header strings[091] = "%dx %s" -- Ammo header strings[092] = "%02d:%02d:%02d" -- Timer strings[093] = "%d days, %02d:%02d" -- Time passed -- Game names - to use with Select Game menu... strings[100] = "Tomb Raider I"; strings[101] = "Tomb Raider I Gold: Unfinished Business"; strings[200] = "Tomb Raider II"; strings[201] = "Tomb Raider II Gold: The Golden Mask"; strings[300] = "Tomb Raider III"; strings[301] = "Tomb Raider III Gold: The Lost Artifact"; strings[400] = "Tomb Raider IV: The Last Revelation"; strings[401] = "Tomb Raider IV Bonus: The Times Level"; strings[500] = "Tomb Raider V: Chronicles"; strings[600] = "Custom Levels"; -- *: a techincally wrong translation, but kept for historical/nostalgia reasons ;)
lgpl-3.0
loringmoore/The-Forgotten-Server
data/migrations/8.lua
57
3350
function onUpdateDatabase() print("> Updating database to version 9 (global inbox)") db.query("CREATE TABLE IF NOT EXISTS `player_inboxitems` (`player_id` int(11) NOT NULL, `sid` int(11) NOT NULL, `pid` int(11) NOT NULL DEFAULT '0', `itemtype` smallint(6) NOT NULL, `count` smallint(5) NOT NULL DEFAULT '0', `attributes` blob NOT NULL, UNIQUE KEY `player_id_2` (`player_id`,`sid`), KEY `player_id` (`player_id`), FOREIGN KEY (`player_id`) REFERENCES `players`(`id`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=latin1") -- Delete "market" item db.query("DELETE FROM `player_depotitems` WHERE `itemtype` = 14405") -- Move up items in depot chests local resultId = db.storeQuery("SELECT `player_id`, `pid`, (SELECT `dp2`.`sid` FROM `player_depotitems` AS `dp2` WHERE `dp2`.`player_id` = `dp1`.`player_id` AND `dp2`.`pid` = `dp1`.`sid` AND `itemtype` = 2594) AS `sid` FROM `player_depotitems` AS `dp1` WHERE `itemtype` = 2589") if resultId ~= false then repeat db.query("UPDATE `player_depotitems` SET `pid` = " .. result.getDataInt(resultId, "pid") .. " WHERE `player_id` = " .. result.getDataInt(resultId, "player_id") .. " AND `pid` = " .. result.getDataInt(resultId, "sid")) until not result.next(resultId) result.free(resultId) end -- Delete the depot lockers db.query("DELETE FROM `player_depotitems` WHERE `itemtype` = 2589") -- Delete the depot chests db.query("DELETE FROM `player_depotitems` WHERE `itemtype` = 2594") resultId = db.storeQuery("SELECT DISTINCT `player_id` FROM `player_depotitems` WHERE `itemtype` = 14404") if resultId ~= false then repeat local playerId = result.getDataInt(resultId, "player_id") local runningId = 100 local stmt = "INSERT INTO `player_inboxitems` (`player_id`, `sid`, `pid`, `itemtype`, `count`, `attributes`) VALUES " local resultId2 = db.storeQuery("SELECT `sid` FROM `player_depotitems` WHERE `player_id` = " .. playerId .. " AND `itemtype` = 14404") if resultId2 ~= false then repeat local sids = {} sids[#sids + 1] = result.getDataInt(resultId2, "sid") while #sids > 0 do local sid = sids[#sids] sids[#sids] = nil local resultId3 = db.storeQuery("SELECT * FROM `player_depotitems` WHERE `player_id` = " .. playerId .. " AND `pid` = " .. sid) if resultId3 ~= false then repeat local attr, attrSize = result.getDataStream(resultId3, "attributes") runningId = runningId + 1 stmt = stmt .. "(" .. playerId .. "," .. runningId .. ",0," .. result.getDataInt(resultId3, "itemtype") .. "," .. result.getDataInt(resultId3, "count") .. "," .. db.escapeBlob(attr, attrSize) .. ")," sids[#sids + 1] = result.getDataInt(resultId3, "sid") db.query("DELETE FROM `player_depotitems` WHERE `player_id` = " .. result.getDataInt(resultId, "player_id") .. " AND `sid` = " .. result.getDataInt(resultId3, "sid")) until not result.next(resultId3) result.free(resultId3) end end until not result.next(resultId2) result.free(resultId2) end local stmtLen = string.len(stmt) if stmtLen > 102 then stmt = string.sub(stmt, 1, stmtLen - 1) db.query(stmt) end until not result.next(resultId) result.free(resultId) end -- Delete the inboxes db.query("DELETE FROM `player_depotitems` WHERE `itemtype` = 14404") return true end
gpl-2.0
iamliqiang/prosody-modules
mod_swedishchef/mod_swedishchef.lua
32
1690
-- Copyright (C) 2009 Florian Zeitz -- Copyright (C) 2009 Matthew Wild -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local trigger_string = module:get_option_string("swedishchef_trigger"); trigger_string = (trigger_string and trigger_string .. " ") or ""; local chef = { { th = "t" }, { ow = "o"}, {["([^%w])o"] = "%1oo", O = "Oo"}, {au = "oo", u = "oo", U = "Oo"}, {["([^o])o([^o])"] = "%1u%2"}, {ir = "ur", an = "un", An = "Un", Au = "Oo"}, {e = "i", E = "I"}, { i = function () return select(math.random(2), "i", "ee"); end }, {a = "e", A = "E"}, {["e([^%w])"] = "e-a%1"}, {f = "ff"}, {v = "f", V = "F"}, {w = "v", W = "V"} }; function swedish(english) local eng, url = english:match("(.*)(http://.*)$"); if eng then english = eng; end for _,v in ipairs(chef) do for k,v in pairs(v) do english = english:gsub(k,v); end end english = english:gsub("the", "zee"); english = english:gsub("The", "Zee"); english = english:gsub("tion", "shun"); english = english:gsub("[.!?]$", "%1\nBork Bork Bork!"); return tostring(english..((url and url) or "")); end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; end end if not body then return; end body = body:get_text(); if body and (body:find(trigger_string, 1, true) == 1) then module:log("debug", body:find(trigger_string, 1, true)); stanza[bodyindex][1] = swedish(body:gsub("^" .. trigger_string, "", 1)); end end module:hook("message/bare", check_message);
mit
m-creations/openwrt
feeds/luci/modules/luci-base/luasrc/tools/webadmin.lua
59
2301
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.tools.webadmin", package.seeall) local util = require "luci.util" local uci = require "luci.model.uci" local ip = require "luci.ip" function byte_format(byte) local suff = {"B", "KB", "MB", "GB", "TB"} for i=1, 5 do if byte > 1024 and i < 5 then byte = byte / 1024 else return string.format("%.2f %s", byte, suff[i]) end end end function date_format(secs) local suff = {"min", "h", "d"} local mins = 0 local hour = 0 local days = 0 secs = math.floor(secs) if secs > 60 then mins = math.floor(secs / 60) secs = secs % 60 end if mins > 60 then hour = math.floor(mins / 60) mins = mins % 60 end if hour > 24 then days = math.floor(hour / 24) hour = hour % 24 end if days > 0 then return string.format("%.0fd %02.0fh %02.0fmin %02.0fs", days, hour, mins, secs) else return string.format("%02.0fh %02.0fmin %02.0fs", hour, mins, secs) end end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function cbi_add_knownips(field) local _, n for _, n in ipairs(ip.neighbors({ family = 4 })) do if n.dest then field:value(n.dest:string()) end end end function firewall_find_zone(name) local find luci.model.uci.cursor():foreach("firewall", "zone", function (section) if section.name == name then find = section[".name"] end end ) return find end function iface_get_network(iface) local link = ip.link(tostring(iface)) if link.master then iface = link.master end local cur = uci.cursor() local dump = util.ubus("network.interface", "dump", { }) if dump then local _, net for _, net in ipairs(dump.interface) do if net.l3_device == iface or net.device == iface then -- cross check with uci to filter out @name style aliases local uciname = cur:get("network", net.interface, "ifname") if not uciname or uciname:sub(1, 1) ~= "@" then return net.interface end end end end end
gpl-2.0
lcheylus/haka
modules/protocol/tcp/tcp_connection.lua
3
16655
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local class = require("class") local check = require("check") local raw = require("protocol/raw") local ipv4 = require("protocol/ipv4") local tcp = require("protocol/tcp") local module = {} local log = haka.log_section("tcp") local tcp_connection_dissector = haka.dissector.new{ type = haka.helper.FlowDissector, name = 'tcp_connection' } tcp_connection_dissector.cnx_table = ipv4.cnx_table() tcp_connection_dissector:register_event('new_connection') tcp_connection_dissector:register_event('receive_packet') tcp_connection_dissector:register_streamed_event('receive_data') tcp_connection_dissector:register_event('end_connection') local function tcp_get_key(pkt) return pkt.ip.src, pkt.ip.dst, pkt.srcport, pkt.dstport end function tcp_connection_dissector:receive(pkt) local connection, direction, dropped = tcp_connection_dissector.cnx_table:get(tcp_get_key(pkt)) if not connection then if pkt.flags.syn and not pkt.flags.ack then connection = tcp_connection_dissector.cnx_table:create(tcp_get_key(pkt)) connection.data = haka.context.newscope() local self = tcp_connection_dissector:new(connection, pkt) local ret, err = xpcall(function () haka.context:exec(connection.data, function () self:trigger('new_connection', pkt) end) end, debug.format_error) if err then log.error("%s", err) pkt:drop() self:error() haka.abort() end if not pkt:can_continue() then self:drop() haka.abort() end if not self.stream then pkt:drop() haka.abort() end connection.data:createnamespace('tcp_connection', self) else if not dropped then haka.alert{ severity = 'low', description = "no connection found for tcp packet", sources = { haka.alert.address(pkt.ip.src), haka.alert.service(string.format("tcp/%d", pkt.srcport)) }, targets = { haka.alert.address(pkt.ip.dst), haka.alert.service(string.format("tcp/%d", pkt.dstport)) } } end return pkt:drop() end end local dissector = connection.data:namespace('tcp_connection') local ret, err = xpcall(function () haka.context:exec(connection.data, function () return dissector:emit(pkt, direction) end) if dissector._restart then return tcp_connection_dissector:receive(pkt) end end, debug.format_error) if not ret then if err then log.error("%s", err) dissector:error() end end end tcp_connection_dissector.state_machine = haka.state_machine.new("tcp", function () state_type{ events = { 'input', 'output', 'reset' }, update = function (self, state_machine, direction, pkt) if pkt.flags.rst then state_machine.owner:_sendpkt(pkt, direction) state_machine:trigger('reset', pkt) return end if direction == state_machine.owner.input then state_machine:trigger('input', pkt) else assert(direction == state_machine.owner.output) state_machine:trigger('output', pkt) end end } reset = state() syn = state() syn_sent = state() syn_received = state() established = state() fin_wait_1 = state() fin_wait_2 = state() closing = state() timed_wait = state() local function unexpected_packet(self, pkt) log.error("unexpected tcp packet") pkt:drop() end local function invalid_handshake(type) return function (self, pkt) log.error("invalid tcp %s handshake", type) pkt:drop() end end local function send(dir) return function(self, pkt) self.stream[self[dir]]:init(pkt.seq+1) pkt:send() end end any:on{ events = { events.fail, events.reset }, jump = reset, } any:on{ events = { events.input, events.output }, execute = unexpected_packet, jump = fail, } any:on{ event = events.finish, execute = function (self) self:trigger('end_connection') self:_close() end, } reset:on{ event = events.enter, execute = function (self) self:trigger('end_connection') self:clearstream() self.connection:drop() end, } reset:on{ event = events.timeout(60), jump = finish, } reset:on{ event = events.finish, execute = function (self) self:_close() end, } syn:on{ event = events.init, execute = function (self) self.input = 'up' self.output = 'down' end, } syn:on{ event = events.input, when = function (self, pkt) return pkt.flags.syn end, execute = send('input'), jump = syn_sent, } syn:on{ event = events.input, execute = invalid_handshake('establishement'), jump = fail, } syn_sent:on{ event = events.output, when = function (self, pkt) return pkt.flags.syn and pkt.flags.ack end, execute = send('output'), jump = syn_received, } syn_sent:on{ event = events.input, when = function (self, pkt) return pkt.flags.syn end, execute = function (self, pkt) pkt:send() end, } syn_sent:on{ events = { events.output, events.input }, execute = invalid_handshake('establishement'), jump = fail, } local function push(dir, finish) return function (self, pkt) self:push(pkt, self[dir], finish) end end syn_received:on{ event = events.input, when = function (self, pkt) return pkt.flags.ack end, execute = push('input'), jump = established, } syn_received:on{ event = events.input, when = function (self, pkt) return pkt.flags.fin end, execute = push('input'), jump = fin_wait_1, } syn_received:on{ event = events.output, when = function (self, pkt) return pkt.flags.syn and pkt.flags.ack end, execute = push('output'), } syn_received:on{ events = { events.input, events.output }, execute = invalid_handshake('establishement'), jump = fail, } established:on{ event = events.enter, execute = function (self, pkt) self._established = true end } established:on{ event = events.input, when = function (self, pkt) return pkt.flags.fin end, execute = push('input', true), jump = fin_wait_1, } established:on{ event = events.input, execute = push('input'), } established:on{ event = events.output, when = function (self, pkt) return pkt.flags.fin end, execute = function (self, pkt) self:push(pkt, self.output, true) self.input, self.output = self.output, self.input end, jump = fin_wait_1, } established:on{ event = events.output, execute = push('output'), } local function dofinish(self, pkt) self:finish(self.output) self:_sendpkt(pkt, self.output) end local function sendpkt(dir) return function (self, pkt) self:_sendpkt(pkt, self[dir]) end end fin_wait_1:on{ event = events.output, when = function (self, pkt) return pkt.flags.fin and pkt.flags.ack end, execute = dofinish, jump = closing, } fin_wait_1:on{ event = events.output, when = function (self, pkt) return pkt.flags.fin end, execute = dofinish, jump = timed_wait, } fin_wait_1:on{ event = events.output, when = function (self, pkt) return pkt.flags.ack end, execute = push('output', true), jump = fin_wait_2, } fin_wait_1:on{ event = events.output, execute = invalid_handshake('termination'), jump = fail, } fin_wait_1:on{ event = events.input, when = function (self, pkt) return pkt.flags.fin and pkt.flags.ack end, execute = sendpkt('input'), jump = closing, } fin_wait_1:on{ event = events.input, execute = sendpkt('input'), } fin_wait_2:on{ event = events.output, when = function (self, pkt) return pkt.flags.fin end, execute = sendpkt('output'), jump = timed_wait, } fin_wait_2:on{ event = events.output, when = function (self, pkt) return pkt.flags.ack end, execute = sendpkt('output'), } fin_wait_2:on{ event = events.input, when = function (self, pkt) return pkt.flags.ack end, execute = sendpkt('input'), } fin_wait_2:on{ events = { events.output, events.input }, execute = invalid_handshake('termination'), jump = fail, } closing:on{ event = events.input, when = function (self, pkt) return pkt.flags.ack end, execute = sendpkt('input'), jump = timed_wait, } closing:on{ event = events.input, when = function (self, pkt) return not pkt.flags.fin end, execute = invalid_handshake('termination'), jump = fail, } closing:on{ event = events.input, execute = sendpkt('input'), } closing:on{ event = events.output, when = function (self, pkt) return not pkt.flags.ack end, execute = invalid_handshake('termination'), jump = fail, } closing:on{ event = events.output, execute = sendpkt('output'), } timed_wait:on{ event = events.enter, execute = function (self) self:trigger('end_connection') end, } timed_wait:on{ event = events.input, when = function (self, pkt) return pkt.flags.syn end, execute = function (self, pkt) self:restart() end, jump = finish, } timed_wait:on{ events = { events.input, events.output }, when = function (self, pkt) return not pkt.flags.ack end, execute = invalid_handshake('termination'), jump = fail, } timed_wait:on{ event = events.input, execute = sendpkt('input'), } timed_wait:on{ event = events.output, execute = sendpkt('output'), } timed_wait:on{ event = events.timeout(60), jump = finish, } timed_wait:on{ event = events.finish, execute = function (self) self:_close() end, } initial(syn) end) tcp_connection_dissector.auto_state_machine = false function tcp_connection_dissector.method:__init(connection, pkt) class.super(tcp_connection_dissector).__init(self) self.stream = {} self._restart = false self.srcip = pkt.ip.src self.dstip = pkt.ip.dst self.srcport = pkt.srcport self.dstport = pkt.dstport self.connection = connection self.stream['up'] = tcp.tcp_stream() self.stream['down'] = tcp.tcp_stream() self.state = tcp_connection_dissector.state_machine:instanciate(self) end function tcp_connection_dissector.method:clearstream() if self.stream then self.stream.up:clear() self.stream.down:clear() self.stream = nil end end function tcp_connection_dissector.method:restart() self._restart = true end function tcp_connection_dissector.method:emit(pkt, direction) self.connection:update_stat(direction, pkt.ip.len) self:trigger('receive_packet', pkt, direction) self.state:update(direction, pkt) end function tcp_connection_dissector.method:_close() self:clearstream() if self.connection then self.connection:close() self.connection = nil end self.state = nil end function tcp_connection_dissector.method:_trigger_receive(direction, stream, current) self:trigger('receive_data', stream.stream, current, direction) local next_dissector = self:next_dissector() if next_dissector then return next_dissector:receive(stream.stream, current, direction) else return self:send(direction) end end function tcp_connection_dissector.method:push(pkt, direction, finish) local stream = self.stream[direction] local current = stream:push(pkt) if finish then stream.stream:finish() end self:_trigger_receive(direction, stream, current) end function tcp_connection_dissector.method:finish(direction) local stream = self.stream[direction] stream.stream:finish() self:_trigger_receive(direction, stream, nil) end function tcp_connection_dissector.method:can_continue() return self.stream ~= nil end function tcp_connection_dissector.method:_sendpkt(pkt, direction) self:send(direction) self.stream[direction]:seq(pkt) self.stream[haka.dissector.opposite_direction(direction)]:ack(pkt) pkt:send() end function tcp_connection_dissector.method:_send(direction) if self.stream then local stream = self.stream[direction] local other_stream = self.stream[haka.dissector.opposite_direction(direction)] local pkt = stream:pop() while pkt do other_stream:ack(pkt) pkt:send() pkt = stream:pop() end end end function tcp_connection_dissector.method:send(direction) if not direction then self:_send('up') self:_send('down') else self:_send(direction) end end function tcp_connection_dissector.method:error() self:_close() end function tcp_connection_dissector.method:drop() check.assert(self.state, "connection already dropped") self.state:trigger('reset') end function tcp_connection_dissector.method:_forgereset(direction) local tcprst = raw.create() tcprst = ipv4.create(tcprst) if direction == 'up' then tcprst.src = self.srcip tcprst.dst = self.dstip else tcprst.src = self.dstip tcprst.dst = self.srcip end tcprst.ttl = 64 tcprst = tcp.create(tcprst) if direction == 'up' then tcprst.srcport = self.srcport tcprst.dstport = self.dstport else tcprst.srcport = self.dstport tcprst.dstport = self.srcport end tcprst.seq = self.stream[direction].lastseq tcprst.flags.rst = true return tcprst end function tcp_connection_dissector.method:reset() check.assert(self._established, "cannot reset a non-established connection") local rst rst = self:_forgereset('down') rst:send() rst = self:_forgereset('up') rst:send() self:drop() end function tcp_connection_dissector.method:halfreset() check.assert(self._established, "cannot reset a non-established connection") local rst rst = self:_forgereset('down') rst:send() self:drop() end tcp.select_next_dissector(tcp_connection_dissector) module.events = tcp_connection_dissector.events -- -- Helpers -- module.helper = {} module.helper.TcpFlowDissector = class.class('TcpFlowDissector', haka.helper.FlowDissector) function module.helper.TcpFlowDissector.dissect(cls, flow) flow:select_next_dissector(cls:new(flow)) end function module.helper.TcpFlowDissector.install_tcp_rule(cls, port) haka.rule{ name = string.format("install %s dissector", cls.name), hook = tcp_connection_dissector.events.new_connection, eval = function (flow, pkt) if pkt.dstport == port then log.debug("selecting %s dissector on flow", cls.name) flow:select_next_dissector(cls:new(flow)) end end } end module.helper.TcpFlowDissector.property.connection = { get = function (self) self.connection = self.flow.connection return self.connection end } function module.helper.TcpFlowDissector.method:__init(flow) check.assert(class.isa(flow, tcp_connection_dissector), "invalid flow parameter") class.super(module.helper.TcpFlowDissector).__init(self) self.flow = flow end function module.helper.TcpFlowDissector.method:can_continue() return self.flow ~= nil end function module.helper.TcpFlowDissector.method:drop() self.flow:drop() self.flow = nil end function module.helper.TcpFlowDissector.method:reset() self.flow:reset() self.flow = nil end function module.helper.TcpFlowDissector.method:receive(stream, current, direction) return haka.dissector.pcall(self, function () self.flow:streamed(stream, self.receive_streamed, self, current, direction) if self.flow then self.flow:send(direction) end end) end function module.helper.TcpFlowDissector.method:receive_streamed(iter, direction) assert(self.state, "no state machine defined") while iter:wait() do self.state:update(iter, direction) self:continue() end end -- -- Console utilities -- module.console = {} function module.console.list_connections(show_dropped) local ret = {} for _, cnx in ipairs(tcp_connection_dissector.cnx_table:all(show_dropped)) do if cnx.data then local tcp_data = cnx.data:namespace('tcp_connection') table.insert(ret, { _thread = haka.current_thread(), _id = tcp_data.connection.id, id = string.format("%d-%d", haka.current_thread(), tcp_data.connection.id), srcip = tcp_data.srcip, srcport = tcp_data.srcport, dstip = tcp_data.dstip, dstport = tcp_data.dstport, state = tcp_data.state.current, in_pkts = tcp_data.connection.in_pkts, in_bytes = tcp_data.connection.in_bytes, out_pkts = tcp_data.connection.out_pkts, out_bytes = tcp_data.connection.out_bytes }) end end return ret end function module.console.drop_connection(id) local tcp_conn = tcp_connection_dissector.cnx_table:get_byid(id) if not tcp_conn then error("unknown tcp connection") end if tcp_conn.data then local tcp_data = tcp_conn.data:namespace('tcp_connection') tcp_data:drop() end end function module.console.reset_connection(id) local tcp_conn = tcp_connection_dissector.cnx_table:get_byid(id) if not tcp_conn then error("unknown tcp connection") end if tcp_conn.data then local tcp_data = tcp_conn.data:namespace('tcp_connection') tcp_data:reset() end end return module
mpl-2.0
sealgair/Jolly-Xanthar
menu/splash.lua
1
1834
class = require 'lib/30log/30log' require "controller" require "direction" require "save" require "utils" Splash = class("Splash") function canContinue() return #Ship.shipNames() > 0 end function Splash:init(fsm) self.fsm = fsm self.background = love.graphics.newImage('assets/Splash.png') self.items = { 'continue', 'new', 'controls', 'galaxy', 'planets', 'quit', } self.opts = { new = "Name Your Ship", } if canContinue() then self.activeItem = 1 else self.activeItem = 2 end Controller:register(self, 1) self.controlDirection = Direction(0, 0) end function Splash:update(dt) end function Splash:setDirection(direction) if direction ~= self.controlDirection then self.controlDirection = direction self.activeItem = wrapping(self.activeItem + self.controlDirection.y, # self.items) if self.activeItem == 1 and not canContinue() then -- advance one more self.activeItem = wrapping(self.activeItem + self.controlDirection.y, # self.items) end end end function Splash:controlStop(action) if action == 'a' or action == 'start' then local item = self.items[self.activeItem] local opt = self.opts[item] self.fsm:advance(item, opt) end end function Splash:draw() love.graphics.draw(self.background, 0, 0) graphicsContext({color=Colors.white, font=Fonts.large}, function() for i, item in ipairs(self.items) do if self.activeItem == i then love.graphics.setColor(Colors.red) else if item == "continue" and not canContinue() then love.graphics.setColor(Colors.menuGray) else love.graphics.setColor(Colors.white) end end i = i - 1 local y = 48 + (i * 16) love.graphics.printf(item:upper(), 160, y, 80, "center") end end) end
gpl-3.0
cochrane/OpenTomb
scripts/level/tr4/KARNAK1.lua
2
2776
-- OPENTOMB LEVEL SCRIPT -- FOR TOMB RAIDER 4, KARNAK1 print("Level script loaded (KARNAK1.lua)"); -- STATIC COLLISION FLAGS ------------------------------------------------------ -------------------------------------------------------------------------------- -- PLANT statics (as listed in OBJECTS.H from TRLE) static_tbl[0] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Tree static_tbl[11] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Gate static_tbl[12] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX, hide = 1}; -- Gate: dummy static 1! static_tbl[13] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX, hide = 1}; -- Gate: dummy static 2! static_tbl[14] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Plate static_tbl[15] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Vase static_tbl[16] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX, hide = 1}; -- Cube: dummy static 3! static_tbl[17] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pedestal -- ROCK statics static_tbl[20] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pillar static_tbl[21] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Pillar (half) static_tbl[22] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Border stones static_tbl[23] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Horn static_tbl[24] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Hanging statue 1 static_tbl[25] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Hanging statue 2 static_tbl[26] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pillar 2 static_tbl[29] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Wall pillar -- ARCHITECTURE statics static_tbl[30] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Obelisk, lower part static_tbl[31] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Obelisk, higher part static_tbl[37] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pillar 3 static_tbl[38] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Arch static_tbl[39] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Grated gate (closed) -- SHATTER statics -- Note: all SHATTER statics can be destroyed by SHATTER event (either on hit or something else) static_tbl[50] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Vase 2
lgpl-3.0
sajjad94/ASD_KARBALA
plugins/en-me.lua
6
1496
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ ME BOT : شنو اني ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function run(msg, matches) if matches[1] == 'me' then if is_sudo(msg) then send_document(get_receiver(msg), "./files/me/sudo.webp", ok_cb, false) return "You sudo 😻🙊" elseif is_support(msg) then send_document(get_receiver(msg), "./files/me/support.webp", ok_cb, false) return "You admin 🌚💭" elseif is_owner(msg) then send_document(get_receiver(msg), "./files/me/owner.webp", ok_cb, false) return "You owner 🌺😍" elseif is_momod(msg) then send_document(get_receiver(msg), "./files/me/moderator.webp", ok_cb, false) return "You admin 👍🏻☺️" else send_document(get_receiver(msg), "./files/me/member.webp", ok_cb, false) return "You member 😒💔" end end end return { patterns = { "^(me)$", "^(me)$" }, run = run } end
gpl-2.0
emptyrivers/WeakAuras2
WeakAurasOptions/SubRegionOptions/SubText.lua
1
16141
if not WeakAuras.IsCorrectVersion() then return end local AddonName, OptionsPrivate = ... local SharedMedia = LibStub("LibSharedMedia-3.0") local L = WeakAuras.L local screenWidth, screenHeight = math.ceil(GetScreenWidth() / 20) * 20, math.ceil(GetScreenHeight() / 20) * 20 local self_point_types = { BOTTOMLEFT = L["Bottom Left"], BOTTOM = L["Bottom"], BOTTOMRIGHT = L["Bottom Right"], RIGHT = L["Right"], TOPRIGHT = L["Top Right"], TOP = L["Top"], TOPLEFT = L["Top Left"], LEFT = L["Left"], CENTER = L["Center"], AUTO = L["Automatic"] } local function createOptions(parentData, data, index, subIndex) -- The toggles for font flags is intentionally not keyed on the id -- So that all auras share the state of that toggle local hiddenFontExtra = function() return OptionsPrivate.IsCollapsed("subtext", "subtext", "fontflags" .. index, true) end local indentWidth = 0.15 local options = { __title = L["Text %s"]:format(subIndex), __order = 1, __up = function() if (OptionsPrivate.Private.ApplyToDataOrChildData(parentData, OptionsPrivate.MoveSubRegionUp, index, "subtext")) then WeakAuras.ClearAndUpdateOptions(parentData.id) end end, __down = function() if (OptionsPrivate.Private.ApplyToDataOrChildData(parentData, OptionsPrivate.MoveSubRegionDown, index, "subtext")) then WeakAuras.ClearAndUpdateOptions(parentData.id) end end, __duplicate = function() if (OptionsPrivate.Private.ApplyToDataOrChildData(parentData, OptionsPrivate.DuplicateSubRegion, index, "subtext")) then WeakAuras.ClearAndUpdateOptions(parentData.id) end end, __delete = function() if (OptionsPrivate.Private.ApplyToDataOrChildData(parentData, WeakAuras.DeleteSubRegion, index, "subtext")) then WeakAuras.ClearAndUpdateOptions(parentData.id) end end, text_visible = { type = "toggle", width = WeakAuras.halfWidth, order = 9, name = L["Show Text"], }, text_color = { type = "color", width = WeakAuras.halfWidth, name = L["Color"], hasAlpha = true, order = 10, }, text_text = { type = "input", width = WeakAuras.normalWidth, desc = function() return L["Dynamic text tooltip"] .. OptionsPrivate.Private.GetAdditionalProperties(parentData) end, name = L["Display Text"], order = 11, set = function(info, v) data.text_text = OptionsPrivate.Private.ReplaceLocalizedRaidMarkers(v) WeakAuras.Add(parentData) WeakAuras.ClearAndUpdateOptions(parentData.id) end }, text_font = { type = "select", width = WeakAuras.normalWidth, dialogControl = "LSM30_Font", name = L["Font"], order = 13, values = AceGUIWidgetLSMlists.font, }, text_fontSize = { type = "range", width = WeakAuras.normalWidth, name = L["Size"], order = 14, min = 6, softMax = 72, step = 1, }, text_fontFlagsDescription = { type = "execute", control = "WeakAurasExpandSmall", name = function() local textFlags = OptionsPrivate.Private.font_flags[data.text_fontType] local color = format("%02x%02x%02x%02x", data.text_shadowColor[4] * 255, data.text_shadowColor[1] * 255, data.text_shadowColor[2] * 255, data.text_shadowColor[3]*255) local textJustify = "" if data.text_justify == "CENTER" then -- CENTER is default elseif data.text_justify == "LEFT" then textJustify = " " .. L["and aligned left"] elseif data.text_justify == "RIGHT" then textJustify = " " .. L["and aligned right"] end local textRotate = "" if data.rotateText == "LEFT" then textRotate = " " .. L["and rotated left"] elseif data.rotateText == "RIGHT" then textRotate = " " .. L["and rotated right"] end local textWidth = "" if data.text_automaticWidth == "Fixed" then local wordWarp = "" if data.text_wordWrap == "WordWrap" then wordWarp = L["wrapping"] else wordWarp = L["eliding"] end textWidth = " "..L["and with width |cFFFF0000%s|r and %s"]:format(data.text_fixedWidth, wordWarp) end local secondline = L["|cFFffcc00Font Flags:|r |cFFFF0000%s|r and shadow |c%sColor|r with offset |cFFFF0000%s/%s|r%s%s%s"]:format(textFlags, color, data.text_shadowXOffset, data.text_shadowYOffset, textRotate, textJustify, textWidth) return secondline end, width = WeakAuras.doubleWidth, order = 44, func = function(info, button) local collapsed = OptionsPrivate.IsCollapsed("subtext", "subtext", "fontflags" .. index, true) OptionsPrivate.SetCollapsed("subtext", "subtext", "fontflags" .. index, not collapsed) end, image = function() local collapsed = OptionsPrivate.IsCollapsed("subtext", "subtext", "fontflags" .. index, true) return collapsed and "collapsed" or "expanded" end, imageWidth = 15, imageHeight = 15, arg = { expanderName = "subtext" .. index .. "#" .. subIndex } }, text_font_space = { type = "description", name = "", order = 45, hidden = hiddenFontExtra, width = indentWidth }, text_fontType = { type = "select", width = WeakAuras.normalWidth - indentWidth, name = L["Outline"], order = 46, values = OptionsPrivate.Private.font_flags, hidden = hiddenFontExtra }, text_shadowColor = { type = "color", hasAlpha = true, width = WeakAuras.normalWidth, name = L["Shadow Color"], order = 47, hidden = hiddenFontExtra }, text_font_space3 = { type = "description", name = "", order = 47.5, hidden = hiddenFontExtra, width = indentWidth }, text_shadowXOffset = { type = "range", width = WeakAuras.normalWidth - indentWidth, name = L["Shadow X Offset"], softMin = -15, softMax = 15, bigStep = 1, order = 48, hidden = hiddenFontExtra }, text_shadowYOffset = { type = "range", width = WeakAuras.normalWidth, name = L["Shadow Y Offset"], softMin = -15, softMax = 15, bigStep = 1, order = 49, hidden = hiddenFontExtra }, text_font_space4 = { type = "description", name = "", order = 49.5, hidden = hiddenFontExtra, width = indentWidth }, rotateText = { type = "select", width = WeakAuras.normalWidth - indentWidth, name = L["Rotate Text"], values = OptionsPrivate.Private.text_rotate_types, order = 50, hidden = hiddenFontExtra }, text_justify = { type = "select", width = WeakAuras.normalWidth, name = L["Alignment"], values = OptionsPrivate.Private.justify_types, order = 50.5, hidden = hiddenFontExtra }, text_font_space5 = { type = "description", name = "", order = 51, hidden = hiddenFontExtra, width = indentWidth }, text_automaticWidth = { type = "select", width = WeakAuras.normalWidth - indentWidth, name = L["Width"], order = 51.5, values = OptionsPrivate.Private.text_automatic_width, hidden = hiddenFontExtra }, text_font_space6 = { type = "description", name = "", order = 52, hidden = hiddenFontExtra, width = WeakAuras.normalWidth }, text_font_space7 = { type = "description", name = "", order = 52.5, width = indentWidth, hidden = function() return hiddenFontExtra() or data.text_automaticWidth ~= "Fixed" end }, text_fixedWidth = { name = L["Width"], width = WeakAuras.normalWidth - indentWidth, order = 53, type = "range", min = 1, softMax = 200, bigStep = 1, hidden = function() return hiddenFontExtra() or data.text_automaticWidth ~= "Fixed" end }, text_wordWrap = { type = "select", width = WeakAuras.normalWidth, name = L["Overflow"], order = 54, values = OptionsPrivate.Private.text_word_wrap, hidden = function() return hiddenFontExtra() or data.text_automaticWidth ~= "Fixed" end }, text_anchor = { type = "description", name = "", order = 55, hidden = hiddenFontExtra, control = "WeakAurasExpandAnchor", arg = { expanderName = "subtext" .. index .. "#" .. subIndex } } } -- Note: Anchor Options need to be generalized once there are multiple sub regions -- While every sub region will have anchor options, the initial -- design I had for anchor options proved to be not general enough for -- what SubText needed. So, I removed it, and postponed making it work for unknown future -- sub regions local anchors if parentData.controlledChildren then anchors = {} for index, childId in ipairs(parentData.controlledChildren) do local childData = WeakAuras.GetData(childId) Mixin(anchors, OptionsPrivate.Private.GetAnchorsForData(childData, "point")) end else anchors = OptionsPrivate.Private.GetAnchorsForData(parentData, "point") end -- Anchor Options options.text_anchorsDescription = { type = "execute", control = "WeakAurasExpandSmall", name = function() local selfPoint = data.text_selfPoint ~= "AUTO" and self_point_types[data.text_selfPoint] local anchorPoint = anchors[data.text_anchorPoint or "CENTER"] or anchors["CENTER"] local xOffset = data.text_anchorXOffset or 0 local yOffset = data.text_anchorYOffset or 0 if (type(anchorPoint) == "table") then anchorPoint = anchorPoint[1] .. "/" .. anchorPoint[2] end if selfPoint then if xOffset == 0 and yOffset == 0 then return L["|cFFffcc00Anchors:|r Anchored |cFFFF0000%s|r to frame's |cFFFF0000%s|r"]:format(selfPoint, anchorPoint) else return L["|cFFffcc00Anchors:|r Anchored |cFFFF0000%s|r to frame's |cFFFF0000%s|r with offset |cFFFF0000%s/%s|r"]:format(selfPoint, anchorPoint, xOffset, yOffset) end else if xOffset == 0 and yOffset == 0 then return L["|cFFffcc00Anchors:|r Anchored to frame's |cFFFF0000%s|r"]:format(anchorPoint) else return L["|cFFffcc00Anchors:|r Anchored to frame's |cFFFF0000%s|r with offset |cFFFF0000%s/%s|r"]:format(anchorPoint, xOffset, yOffset) end end end, width = WeakAuras.doubleWidth, order = 60, image = function() local collapsed = OptionsPrivate.IsCollapsed("subregion", "text_anchors", tostring(index), true) return collapsed and "collapsed" or "expanded" end, imageWidth = 15, imageHeight = 15, func = function(info, button) local collapsed = OptionsPrivate.IsCollapsed("subregion", "text_anchors", tostring(index), true) OptionsPrivate.SetCollapsed("subregion", "text_anchors", tostring(index), not collapsed) end, arg = { expanderName = "subtext_anchor" .. index .. "#" .. subIndex } } local hiddenFunction = function() return OptionsPrivate.IsCollapsed("subregion", "text_anchors", tostring(index), true) end options.text_anchor_space = { type = "description", name = "", order = 60.15, hidden = hiddenFunction, width = indentWidth } options.text_selfPoint = { type = "select", width = WeakAuras.normalWidth - indentWidth, name = L["Anchor"], order = 60.2, values = self_point_types, hidden = hiddenFunction } options.text_anchorPoint = { type = "select", width = WeakAuras.normalWidth, name = function() return L["To Frame's"] end, order = 60.3, values = anchors, hidden = hiddenFunction, control = "WeakAurasTwoColumnDropdown" } options.text_anchor_space2 = { type = "description", name = "", order = 60.35, hidden = hiddenFunction, width = indentWidth } options.text_anchorXOffset = { type = "range", width = WeakAuras.normalWidth - indentWidth, name = L["X Offset"], order = 60.4, softMin = (-1 * screenWidth), softMax = screenWidth, bigStep = 10, hidden = hiddenFunction } options.text_anchorYOffset = { type = "range", width = WeakAuras.normalWidth, name = L["Y Offset"], order = 60.5, softMin = (-1 * screenHeight), softMax = screenHeight, bigStep = 10, hidden = hiddenFunction } options.text_anchor_anchor = { type = "description", name = "", order = 61, hidden = hiddenFunction, control = "WeakAurasExpandAnchor", arg = { expanderName = "subtext_anchor" .. index .. "#" .. subIndex } } local function hideCustomTextOption() if not parentData.subRegions then return true end for index, subRegion in ipairs(parentData.subRegions) do if subRegion.type == "subtext" and OptionsPrivate.Private.ContainsCustomPlaceHolder(subRegion.text_text) then return false end end return true end local commonTextOptions = { __title = L["Common Text"], __hidden = function() return hideCustomTextOption() end, text_customTextUpdate = { type = "select", width = WeakAuras.doubleWidth, hidden = hideCustomTextOption, name = L["Update Custom Text On..."], values = OptionsPrivate.Private.text_check_types, order = 3, get = function() return parentData.customTextUpdate or "event" end, set = function(info, v) parentData.customTextUpdate = v WeakAuras.Add(parentData) WeakAuras.ClearAndUpdateOptions(parentData.id) end }, } OptionsPrivate.commonOptions.AddCodeOption(commonTextOptions, parentData, L["Custom Function"], "customText", "https://github.com/WeakAuras/WeakAuras2/wiki/Custom-Code-Blocks#custom-text", 4, hideCustomTextOption, {"customText"}, false) -- Add Text Format Options local hidden = function() return OptionsPrivate.IsCollapsed("format_option", "text", "text_text" .. index, true) end local setHidden = function(hidden) OptionsPrivate.SetCollapsed("format_option", "text", "text_text" .. index, hidden) end local order = 12 local function addOption(key, option) option.order = order order = order + 0.01 if option.reloadOptions then option.reloadOptions = nil option.set = function(info, v) data["text_text_format_" .. key] = v WeakAuras.Add(parentData) WeakAuras.ClearAndUpdateOptions(parentData.id, true) end end options["text_text_format_" .. key] = option end if parentData.controlledChildren then for childIndex, childId in pairs(parentData.controlledChildren) do local parentChildData = WeakAuras.GetData(childId) if parentChildData.subRegions then local childData = parentChildData.subRegions[index] if childData then local get = function(key) return childData["text_text_format_" .. key] end local input = childData["text_text"] OptionsPrivate.AddTextFormatOption(input, true, get, addOption, hidden, setHidden, childIndex, #parentData.controlledChildren) end end end else local get = function(key) return data["text_text_format_" .. key] end local input = data["text_text"] OptionsPrivate.AddTextFormatOption(input, true, get, addOption, hidden, setHidden) end addOption("footer", { type = "description", name = "", width = WeakAuras.doubleWidth, hidden = hidden }) return options, commonTextOptions end WeakAuras.RegisterSubRegionOptions("subtext", createOptions, L["Shows one or more lines of text, which can include dynamic information such as progress or stacks"])
gpl-2.0
SkyRzn/esp8266_sht10
init.lua
1
1232
server_ip = "192.168.0.66" server_port = 8266 deep_sleep_time = 600 max_connection_attempts = 20 run_cnt = 0 new_settings = nil battery = dofile("battery.lua") collectgarbage() data = dofile("sht1x_v3.lua") temp = (data[1]) hum = (data[2]) data = nil collectgarbage() print(temp, hum) btemp = dofile("ds18b20_v3.lua") collectgarbage() print("btemp", btemp) dofile("read_settings.lua") collectgarbage() local function sleep() print("sleep") node.dsleep(deep_sleep_time * 1000000) end function receive(conn, data) tmr.stop(0) new_settings = data dofile("write_settings.lua") sleep() end function run() run_cnt = run_cnt + 1 print("run", run_cnt) if wifi.sta.status() ~= 5 then -- not got IP if run_cnt > max_connection_attempts then sleep() end return end tmr.stop(0) collectgarbage() print("send", temp, hum, btemp) local conn = net.createConnection(net.UDP) conn:on("receive", receive) conn:connect(server_port, server_ip) conn:send(temp..","..hum..","..btemp..","..battery..","..deep_sleep_time..","..max_connection_attempts..","..run_cnt) tmr.wdclr() temp = nil hum = nil btemp = nil collectgarbage() tmr.alarm(0, 200, 0, function() conn:close() sleep() end) end tmr.alarm(0, 1000, 1, run)
gpl-2.0
osgcc/ryzom
ryzom/client/data/gamedev/interfaces_v3/taskbar.lua
3
1058
------------------------------------------------------------------------------------------------------------ -- create the game namespace without reseting if already created in an other file. if (game==nil) then game= {}; end ------------------------------------------------------------------------------------------------------------ -- function game:getMilkoTooltipWithKey(prop, tooltip, tooltip_pushed, name, param) local tt; -- Check if button is toggled and choose the good tooltip if (prop ~= '' and tooltip_pushed ~= '') then local db = getDbProp(prop); if (db == 1) then tt = tooltip_pushed; else tt = tooltip; end else tt = tooltip; end -- Get key shortcut local text = i18n.get(tt); local key = runExpr('getKey(\'' .. name .. '\',\'' .. param .. '\',1)'); if (key ~= nil and key ~= '') then key = ' @{2F2F}(' .. key .. ')'; text = concatUCString(text, key); end setContextHelpText(text); end function game:taskbarDisableTooltip(ui) local uiGroup = getUI(ui); disableContextHelpForControl(uiGroup); end
agpl-3.0
mofax/cardpeek
dot_cardpeek_dir/scripts/lib/compatibility-with-0.7.lua
17
1952
local DEPRECATED_FUNCS = {} function DEPRECATED_FOR(fname) local func = debug.getinfo(2, "n") local orig = debug.getinfo(3, "lS") if DEPRECATED_FUNCS[func.name]==nil then log.print(log.WARNING,orig.short_src .. "[" .. orig.currentline .. "]: " .. func.name .. "() is deprecated, please use " .. fname .. "() instead.\n" .. "\tThis warning will only be printed once for " .. func.name .. "().") DEPRECATED_FUNCS[func.name]=true end end function ui.tree_find_all_nodes(origin_ref, alabel, aid) DEPRECATED_FOR("nodes.find") local node local ret = {} if origin_ref==nil then origin_ref = nodes.root() end for node in nodes.find(origin_ref, {label=alabel, id=aid}) do ret[#ret+1]=node; end return ret; end function ui.tree_find_node(origin_ref, alabel, aid) DEPRECATED_FOR("nodes.find_first") if origin_ref==nil then origin_ref = nodes.root() end return nodes.find_first(origin_ref, {label=alabel, id=aid}) end function ui.tree_add_node(parent_ref, ...) DEPRECATED_FOR("nodes.append") local arg={...} if parent_ref==nil then parent_ref = nodes.root() end return nodes.append(parent_ref,{ classname=arg[1], label=arg[2], id=arg[3], size=arg[4] }) end function ui.tree_set_value(node,val) DEPRECATED_FOR("nodes.set_attribute") return node:set_attribute("val",val) end function ui.tree_get_value(node,val) DEPRECATED_FOR("nodes.get_attribute") return node:get_attribute("val",val) end function ui.tree_set_alt_value(node,val) DEPRECATED_FOR("nodes.set_attribute") return node:set_attribute("alt",val) end function ui.tree_get_alt_value(node,val) DEPRECATED_FOR("nodes.get_attribute") return node:get_attribute("alt",val) end function ui.tree_delete_node(node) DEPRECATED_FOR("nodes.remove") return nodes.remove(node) end
gpl-3.0
werpat/MoonGen
rfc2544/utils/ssh-freebsd.lua
9
3443
local conf = require "config" local ssh = require "utils.ffi.ssh" local mod = {} mod.__index = mod local session = nil function mod.addInterfaceIP(interface, ip, pfx) return mod.exec("ifconfig " .. interface .. " inet " .. ip .. "/" .. pfx .. " add") end function mod.delInterfaceIP(interface, ip, pfx) return mod.exec("ifconfig " .. interface .. " inet " .. ip .. " -alias") end -- The Firewall is not supported yet. Kernel must be recompiled first and the mod.addIPFilter and mod.delIPFilter -- cannot be translated in that extent function mod.clearIPFilters() return mod.exec("ipf -Fa") end function mod.addIPFilter(src, sPfx, dst, dPfx) return mod.exec("printf \"block in from " .. src .. "/" .. sPfx .. " to " .. dst .. "/" .. dPfx .. "\nblock out from " .. src .. "/" .. sPfx .. " to " .. dst .. "/" .. dPfx .. "\" | ipf -f -") end function mod.delIPFilter() return -1 end function mod.clearIPRoutes() return mod.exec("route flush") end --FreeBSD does not support interface function mod.addIPRoute(dst, pfx, gateway, interface) if gateway and interface then return mod.exec("route add -net" .. dst .. "/" .. pfx .. gateway) elseif gateway then return mod.exec("route add -net" .. dst .. "/" .. pfx .. gateway) elseif interface then return mod.exec("route add -net" .. dst .. "/" .. pfx .. gateway) else return -1 end end --Same here: FreeBSD does not support interface function mod.delIPRoute() if gateway and interface then return mod.exec("route del " .. dst .. "/" .. pfx .. gateway) elseif gateway then return mod.exec("route del " .. dst .. "/" .. pfx .. gateway) elseif interface then return mod.exec("route del " .. dst .. "/" .. pfx .. gateway) else return -1 end end --I dont know if this works, since netstat displays comments function mod.getIPRouteCount() local ok, res = mod.exec("netstat -rn -4 | wc -l") return ok, tonumber(res) end function mod.exec(cmd) local sess, err = mod.getSession() if not sess or err ~= 0 then return -1, err end cmd_res, rc = ssh.request_exec(sess, cmd) if cmd_res == nil then print(rc) return -1, rc end return rc, cmd_res end --[[ function exec(cmd) local sess, err = getSession() if not sess or err ~= 0 then return err end cmd_res = ssh.request_exec(sess, cmd) return tonumber(ssh.request_exec(sess, "echo $?")), cmd_res end --]] function mod.getSession() if not session then print("ssh: establishing new connection") session = ssh.new() if session == nil then return nil, -1 end ssh.set_option(session, "user", conf.getSSHUser()) ssh.set_option(session, "host", conf.getHost()) ssh.set_option(session, "port", conf.getSSHPort()) -- do not ask for checking host signature ssh.set_option(session, "strict_hostkey", false) ssh.connect(session) local ok = ssh.auth_autopubkey(session) if not ok then ok = ssh.auth_password(session, conf.getSSHPass()) end if not ok then return nil, -1 end -- could get banner to guess system -- (Mikrotik) -- ssh.get_issue_banner(session) session = session end return session, 0 end return mod
mit
iskolbin/luasdl2-bunnymark
bunny.lua
1
2593
local SDL local SDLImage local SDLTtf local window local renderer local bunnyImage local bunnyTexture local bunnyWidth local bunnyHeight local bunnies = {} local running = true local font local textbox local DELTA_TIME = math.floor( 1000 / 60 ) local ticks local dTicks local function addBunny() local w, h = window:getSize() return { x = math.random(w), y = math.random(h), w = bunnyWidth, h = bunnyHeight, ax = 0, ay = .0098, vx = math.random(), vy = 0 } end local function init() SDL = require'SDL' SDLImage = require'SDL.image' SDLTtf = require 'SDL.ttf' SDL.init{ SDL.flags.Video } SDLImage.init { SDLImage.flags.PNG } SDLTtf.init() window = SDL.createWindow{ title = 'Bunnymark', width = 640, height = 480, flags = { SDL.window.Resizable } } renderer = SDL.createRenderer( window, -1 ) renderer:setDrawColor( 0 ) bunnyImage = SDLImage.load( 'bunny.png' ) bunnyTexture = renderer:createTextureFromSurface( bunnyImage ) _, _, bunnyWidth, bunnyHeight = bunnyTexture:query() bunnies[1] = addBunny() font = SDLTtf.open( 'DejaVuSans.ttf', 24 ) ticks = SDL.getTicks() dTicks = 0 end local function update( dt ) local ww, wh = window:getSize() for i = 1, #bunnies do local bunny = bunnies[i] bunny.x = bunny.x + bunny.vx * dt bunny.y = bunny.y + bunny.vy * dt bunny.vx = bunny.vx + bunny.ax * dt bunny.vy = bunny.vy + bunny.ay * dt if (bunny.x >= ww and bunny.vx > 0) or (bunny.x <= 0 and bunny.vx < 0) then bunny.vx = -bunny.vx end if (bunny.y >= wh and bunny.vy > 0) or (bunny.y <= 0 and bunny.vy < 0) then bunny.vy = -bunny.vy end end end local textboxRect = {x = 0, y = 0, w = 100, h = 32} local function draw( ) renderer:clear() for i = 1, #bunnies do renderer:copy( bunnyTexture, nil, bunnies[i] ) end -- local textbox = font:renderUtf8( ' FPS: ' .. math.floor(1000/ dTicks ) .. 'C: ' .. #bunnies , 'solid', 0xffffff ) -- local textboxTexture = renderer:createTextureFromSurface( textbox ) -- renderer:copy( textboxTexture, nil, textboxRect ) print( 'FPS: ', math.floor( 1000/dTicks ), 'C:', #bunnies ) renderer:present() end init() while running do for e in SDL.pollEvent() do if e.type == SDL.event.quit then running = false elseif e.type == SDL.event.MouseButtonDown then local n = #bunnies * 2 for i = #bunnies+1, n do bunnies[i] = addBunny() end print( 'Bunnies count', n ) end end local newTicks = SDL.getTicks() dTicks = newTicks - ticks ticks = newTicks draw() update( dTicks ) if dTicks <= DELTA_TIME then SDL.delay( DELTA_TIME ) end end
mit
cochrane/OpenTomb
scripts/config/control_constants.lua
2
7176
-- OPENTOMB CONTROL CONSTANTS LIST -- by Lwmte, Aug 2013 -------------------------------------------------------------------------------- -- Defines key and action names used with key bindings. -------------------------------------------------------------------------------- KEY_BACKSPACE = 0x08; KEY_TAB = 0x09; KEY_RETURN = 0x0D; KEY_ESCAPE = 0x1B; KEY_SPACE = 0x20; KEY_EXCLAIM = 0x21; KEY_QUOTEDBL = 0x22; KEY_HASH = 0x23; KEY_DOLLAR = 0x24; KEY_PERCENT = 0x25; KEY_AMPERSAND = 0x26; KEY_QUOTE = 0x27; KEY_LEFTPAREN = 0x28; KEY_RIGHTPAREN = 0x29; KEY_ASTERISK = 0x2A; KEY_PLUS = 0x2B; KEY_COMMA = 0x2C; KEY_MINUS = 0x2D; KEY_PERIOD = 0x2E; KEY_SLASH = 0x2F; KEY_0 = 0x30; KEY_1 = 0x31; KEY_2 = 0x32; KEY_3 = 0x33; KEY_4 = 0x34; KEY_5 = 0x35; KEY_6 = 0x36; KEY_7 = 0x37; KEY_8 = 0x38; KEY_9 = 0x39; KEY_COLON = 0x3A; KEY_SEMICOLON = 0x3B; KEY_LESS = 0x3C; KEY_EQUALS = 0x3D; KEY_GREATER = 0x3E; KEY_QUESTION = 0x3F; KEY_AT = 0x40; KEY_LEFTBRACKET = 0x5B; KEY_BACKSLASH = 0x5C; KEY_RIGHTBRACKET = 0x5D; KEY_CARET = 0x5E; KEY_UNDERSCORE = 0x5F; KEY_BACKQUOTE = 0x60; KEY_A = 0x61; KEY_B = 0x62; KEY_C = 0x63; KEY_D = 0x64; KEY_E = 0x65; KEY_F = 0x66; KEY_G = 0x67; KEY_H = 0x68; KEY_I = 0x69; KEY_J = 0x6A; KEY_K = 0x6B; KEY_L = 0x6C; KEY_M = 0x6D; KEY_N = 0x6E; KEY_O = 0x6F; KEY_P = 0x70; KEY_Q = 0x71; KEY_R = 0x72; KEY_S = 0x73; KEY_T = 0x74; KEY_U = 0x75; KEY_V = 0x76; KEY_W = 0x77; KEY_X = 0x78; KEY_Y = 0x79; KEY_Z = 0x7A; KEY_DELETE = 0xB1; KEY_CAPSLOCK = 0x40000039; KEY_F1 = 0x4000003A; KEY_F2 = 0x4000003B; KEY_F3 = 0x4000003C; KEY_F4 = 0x4000003D; KEY_F5 = 0x4000003E; KEY_F6 = 0x4000003F; KEY_F7 = 0x40000040; KEY_F8 = 0x40000041; KEY_F9 = 0x40000042; KEY_F10 = 0x40000043; KEY_F11 = 0x40000044; KEY_F12 = 0x40000045; KEY_PRINTSCREEN = 0x40000046; KEY_SCROLLLOCK = 0x40000047; KEY_PAUSE = 0x40000048; KEY_INSERT = 0x40000049; KEY_HOME = 0x4000004A; KEY_PAGEUP = 0x4000004B; KEY_END = 0x4000004D; KEY_PAGEDOWN = 0x4000004E; KEY_RIGHT = 0x4000004F; KEY_LEFT = 0x40000050; KEY_DOWN = 0x40000051; KEY_UP = 0x40000052; KEY_NUMLOCKCLEAR = 0x40000053; KEY_KP_DIVIDE = 0x40000054; KEY_KP_MULTIPLY = 0x40000055; KEY_KP_MINUS = 0x40000056; KEY_KP_PLUS = 0x40000057; KEY_KP_ENTER = 0x40000058; KEY_KP_1 = 0x40000059; KEY_KP_2 = 0x4000005A; KEY_KP_3 = 0x4000005B; KEY_KP_4 = 0x4000005C; KEY_KP_5 = 0x4000005D; KEY_KP_6 = 0x4000005E; KEY_KP_7 = 0x4000005F; KEY_KP_8 = 0x40000060; KEY_KP_9 = 0x40000061; KEY_KP_0 = 0x40000062; KEY_KP_PERIOD = 0x40000063; KEY_APPLICATION = 0x40000065; KEY_POWER = 0x40000066; KEY_KP_EQUALS = 0x40000067; KEY_F13 = 0x40000068; KEY_F14 = 0x40000069; KEY_F15 = 0x4000006A; KEY_F16 = 0x4000006B; KEY_F17 = 0x4000006C; KEY_F18 = 0x4000006D; KEY_F19 = 0x4000006E; KEY_F20 = 0x4000006F; KEY_F21 = 0x40000070; KEY_F22 = 0x40000071; KEY_F23 = 0x40000072; KEY_F24 = 0x40000073; KEY_EXECUTE = 0x40000074; KEY_HELP = 0x40000075; KEY_MENU = 0x40000076; KEY_SELECT = 0x40000077; KEY_STOP = 0x40000078; KEY_AGAIN = 0x40000079; KEY_UNDO = 0x4000007A; KEY_CUT = 0x4000007B; KEY_COPY = 0x4000007C; KEY_PASTE = 0x4000007D; KEY_FIND = 0x4000007E; KEY_MUTE = 0x4000007F; KEY_VOLUMEUP = 0x40000080; KEY_VOLUMEDOWN = 0x40000081; KEY_KP_COMMA = 0x40000085; KEY_KP_EQUALSAS400 = 0x40000086; KEY_ALTERASE = 0x40000099; KEY_SYSREQ = 0x4000009A; KEY_CANCEL = 0x4000009B; KEY_CLEAR = 0x4000009C; KEY_PRIOR = 0x4000009D; KEY_RETURN2 = 0x4000009E; KEY_SEPARATOR = 0x4000009F; KEY_OUT = 0x400000A0; KEY_OPER = 0x400000A1; KEY_CLEARAGAIN = 0x400000A2; KEY_CRSEL = 0x400000A3; KEY_EXSEL = 0x400000A4; KEY_KP_00 = 0x400000B0; KEY_KP_000 = 0x400000B1; KEY_THOUSANDSSEPARATOR = 0x400000B2; KEY_DECIMALSEPARATOR = 0x400000B3; KEY_CURRENCYUNIT = 0x400000B4; KEY_CURRENCYSUBUNIT = 0x400000B5; KEY_KP_LEFTPAREN = 0x400000B6; KEY_KP_RIGHTPAREN = 0x400000B7; KEY_KP_LEFTBRACE = 0x400000B8; KEY_KP_RIGHTBRACE = 0x400000B9; KEY_KP_TAB = 0x400000BA; KEY_KP_BACKSPACE = 0x400000BB; KEY_KP_A = 0x400000BC; KEY_KP_B = 0x400000BD; KEY_KP_C = 0x400000BE; KEY_KP_D = 0x400000BF; KEY_KP_E = 0x400000C0; KEY_KP_F = 0x400000C1; KEY_KP_XOR = 0x400000C2; KEY_KP_POWER = 0x400000C3; KEY_KP_PERCENT = 0x400000C4; KEY_KP_LESS = 0x400000C5; KEY_KP_GREATER = 0x400000C6; KEY_KP_AMPERSAND = 0x400000C7; KEY_KP_DBLAMPERSAND = 0x400000C8; KEY_KP_VERTICALBAR = 0x400000C9; KEY_KP_DBLVERTICALBAR = 0x400000CA; KEY_KP_COLON = 0x400000CB; KEY_KP_HASH = 0x400000CC; KEY_KP_SPACE = 0x400000CD; KEY_KP_AT = 0x400000CE; KEY_KP_EXCLAM = 0x400000CF; KEY_KP_MEMSTORE = 0x400000D0; KEY_KP_MEMRECALL = 0x400000D1; KEY_KP_MEMCLEAR = 0x400000D2; KEY_KP_MEMADD = 0x400000D3; KEY_KP_MEMSUBTRACT = 0x400000D4; KEY_KP_MEMMULTIPLY = 0x400000D5; KEY_KP_MEMDIVIDE = 0x400000D6; KEY_KP_PLUSMINUS = 0x400000D7; KEY_KP_CLEAR = 0x400000D8; KEY_KP_CLEARENTRY = 0x400000D9; KEY_KP_BINARY = 0x400000DA; KEY_KP_OCTAL = 0x400000DB; KEY_KP_DECIMAL = 0x400000DC; KEY_KP_HEXADECIMAL = 0x400000DD; KEY_LCTRL = 0x400000E0; KEY_LSHIFT = 0x400000E1; KEY_LALT = 0x400000E2; KEY_LGUI = 0x400000E3; KEY_RCTRL = 0x400000E4; KEY_RSHIFT = 0x400000E5; KEY_RALT = 0x400000E6; KEY_RGUI = 0x400000E7; KEY_MODE = 0x40000101; KEY_AUDIONEXT = 0x40000102; KEY_AUDIOPREV = 0x40000103; KEY_AUDIOSTOP = 0x40000104; KEY_AUDIOPLAY = 0x40000105; KEY_AUDIOMUTE = 0x40000106; KEY_MEDIASELECT = 0x40000107; KEY_WWW = 0x40000108; KEY_MAIL = 0x40000109; KEY_CALCULATOR = 0x4000010A; KEY_COMPUTER = 0x4000010B; KEY_AC_SEARCH = 0x4000010C; KEY_AC_HOME = 0x4000010D; KEY_AC_BACK = 0x4000010E; KEY_AC_FORWARD = 0x4000010F; KEY_AC_STOP = 0x40000110; KEY_AC_REFRESH = 0x40000111; KEY_AC_BOOKMARKS = 0x40000112; KEY_BRIGHTNESSDOWN = 0x40000113; KEY_BRIGHTNESSUP = 0x40000114; KEY_DISPLAYSWITCH = 0x40000115; KEY_KBDILLUMTOGGLE = 0x40000116; KEY_KBDILLUMDOWN = 0x40000117; KEY_KBDILLUMUP = 0x40000118; KEY_EJECT = 0x40000119; KEY_SLEEP = 0x4000011A; JOY_1 = 1000; JOY_2 = 1001; JOY_3 = 1002; JOY_4 = 1003; JOY_5 = 1004; JOY_6 = 1005; JOY_7 = 1006; JOY_8 = 1007; JOY_9 = 1008; JOY_10 = 1009; JOY_11 = 1010; JOY_12 = 1011; JOY_13 = 1012; JOY_14 = 1013; JOY_15 = 1014; JOY_16 = 1015; JOY_17 = 1016; JOY_18 = 1017; JOY_19 = 1018; JOY_20 = 1019; JOY_21 = 1020; JOY_22 = 1021; JOY_23 = 1022; JOY_24 = 1023; JOY_25 = 1024; JOY_26 = 1025; JOY_27 = 1026; JOY_28 = 1027; JOY_29 = 1028; JOY_30 = 1029; JOY_31 = 1030; JOY_32 = 1031; JOY_POVUP = 1101; JOY_POVDOWN = 1104; JOY_POVLEFT = 1108; JOY_POVRIGHT = 1102; JOY_TRIGGERLEFT = 1204; -- Only for XBOX360-like controllers - analog triggers. JOY_TRIGGERRIGHT = 1205; act = {}; act.up = 0; act.down = 1; act.left = 2; act.right = 3; act.action = 4; act.jump = 5; act.roll = 6; act.drawweapon = 7; act.look = 8; act.walk = 9; act.sprint = 10; act.crouch = 11; act.stepleft = 12; act.stepright = 13; act.lookup = 14; act.lookdown = 15; act.lookleft = 16; act.lookright = 17; act.nextweapon = 18; act.prevweapon = 19; act.flare = 20; act.bigmedi = 21; act.smallmedi = 22; act.weapon1 = 23; act.weapon2 = 24; act.weapon3 = 25; act.weapon4 = 26; act.weapon5 = 27; act.weapon6 = 28; act.weapon7 = 29; act.weapon8 = 30; act.weapon9 = 31; act.weapon10 = 32; act.binoculars = 33; act.pls = 34; act.pause = 35; act.inventory = 36; act.diary = 37; act.map = 38; act.loadgame = 39; act.savegame = 40; act.console = 41; act.screenshot = 42;
lgpl-3.0
pavel-odintsov/snabbswitch
src/core/link.lua
13
3092
module(...,package.seeall) local debug = _G.developer_debug local shm = require("core.shm") local ffi = require("ffi") local C = ffi.C local packet = require("core.packet") require("core.packet_h") local counter = require("core.counter") require("core.counter_h") require("core.link_h") local band = require("bit").band local size = C.LINK_RING_SIZE -- NB: Huge slow-down if this is not local max = C.LINK_MAX_PACKETS local counternames = {"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop"} function new (name) local r = shm.map("links/"..name, "struct link") for _, c in ipairs(counternames) do r.stats[c] = counter.open("counters/"..name.."/"..c) end return r end function free (r, name) for _, c in ipairs(counternames) do counter.delete("counters/"..name.."/"..c) end shm.unmap(r) shm.unlink("links/"..name) end function receive (r) -- if debug then assert(not empty(r), "receive on empty link") end local p = r.packets[r.read] r.read = band(r.read + 1, size - 1) counter.add(r.stats.rxpackets) counter.add(r.stats.rxbytes, p.length) return p end function front (r) return (r.read ~= r.write) and r.packets[r.read] or nil end function transmit (r, p) -- assert(p) if full(r) then counter.add(r.stats.txdrop) packet.free(p) else r.packets[r.write] = p r.write = band(r.write + 1, size - 1) counter.add(r.stats.txpackets) counter.add(r.stats.txbytes, p.length) r.has_new_data = true end end -- Return true if the ring is empty. function empty (r) return r.read == r.write end -- Return true if the ring is full. function full (r) return band(r.write + 1, size - 1) == r.read end -- Return the number of packets that are ready for read. function nreadable (r) if r.read > r.write then return r.write + size - r.read else return r.write - r.read end end function nwritable (r) return max - nreadable(r) end function stats (r) local stats = {} for _, c in ipairs(counternames) do stats[c] = tonumber(counter.read(r.stats[c])) end return stats end function selftest () print("selftest: link") local r = new("test") local p = packet.allocate() assert(counter.read(r.stats.txpackets) == 0 and empty(r) == true and full(r) == false) assert(nreadable(r) == 0) transmit(r, p) assert(counter.read(r.stats.txpackets) == 1 and empty(r) == false and full(r) == false) for i = 1, max-2 do transmit(r, p) end assert(counter.read(r.stats.txpackets) == max-1 and empty(r) == false and full(r) == false) assert(nreadable(r) == counter.read(r.stats.txpackets)) transmit(r, p) assert(counter.read(r.stats.txpackets) == max and empty(r) == false and full(r) == true) transmit(r, p) assert(counter.read(r.stats.txpackets) == max and counter.read(r.stats.txdrop) == 1) assert(not empty(r) and full(r)) while not empty(r) do receive(r) end assert(counter.read(r.stats.rxpackets) == max) link.free(r, "test") print("selftest OK") end
apache-2.0
loringmoore/The-Forgotten-Server
data/talkactions/scripts/deathlist.lua
12
2178
local function getArticle(str) return str:find("[AaEeIiOoUuYy]") == 1 and "an" or "a" end local function getMonthDayEnding(day) if day == "01" or day == "21" or day == "31" then return "st" elseif day == "02" or day == "22" then return "nd" elseif day == "03" or day == "23" then return "rd" else return "th" end end local function getMonthString(m) return os.date("%B", os.time{year = 1970, month = m, day = 1}) end function onSay(cid, words, param) local resultId = db.storeQuery("SELECT `id`, `name` FROM `players` WHERE `name` = " .. db.escapeString(param)) if resultId ~= false then local targetGUID = result.getDataInt(resultId, "id") local targetName = result.getDataString(resultId, "name") result.free(resultId) local str = "" local breakline = "" local resultId = db.storeQuery("SELECT `time`, `level`, `killed_by`, `is_player` FROM `player_deaths` WHERE `player_id` = " .. targetGUID .. " ORDER BY `time` DESC") if resultId ~= false then repeat if str ~= "" then breakline = "\n" end local date = os.date("*t", result.getDataInt(resultId, "time")) local article = "" local killed_by = result.getDataString(resultId, "killed_by") if result.getDataInt(resultId, "is_player") == 0 then article = getArticle(killed_by) .. " " killed_by = string.lower(killed_by) end if date.day < 10 then date.day = "0" .. date.day end if date.hour < 10 then date.hour = "0" .. date.hour end if date.min < 10 then date.min = "0" .. date.min end if date.sec < 10 then date.sec = "0" .. date.sec end str = str .. breakline .. " " .. date.day .. getMonthDayEnding(date.day) .. " " .. getMonthString(date.month) .. " " .. date.year .. " " .. date.hour .. ":" .. date.min .. ":" .. date.sec .. " Died at Level " .. result.getDataInt(resultId, "level") .. " by " .. article .. killed_by .. "." until not result.next(resultId) result.free(resultId) end if str == "" then str = "No deaths." end doPlayerPopupFYI(cid, "Deathlist for player, " .. targetName .. ".\n\n" .. str) else doPlayerSendCancel(cid, "A player with that name does not exist.") end return false end
gpl-2.0
Murfalo/game-off-2016
xl/Scene.lua
1
1780
local skiplist = require("libs.skiplist") local __NULL__ = function () end local counter = util.counter() local lessThan = function(a,b) if a.z < b.z then return true elseif a.z==b.z and a.id < b.id then return true else return false end end local MakeNode = function (obj) -- the id field is necessary because, otherwise, items on the same plane would cause troubles. obj = obj or {} obj.id = counter() return obj end local SceneMT = Class.create("Scene") function SceneMT:init(estimate) self.zlist = skiplist.new(estimate) self.len = 0 end function SceneMT:draw() for _,item in self.zlist:iter() do item:draw()end end function SceneMT:update(dt) for _,item in self.zlist:iter() do item:update(dt) end end function SceneMT:insert(obj) assert(obj and obj.z and obj.id, "Cannot insert object into depth list") self.zlist:insert(obj) end function SceneMT:remove(obj) assert(obj) self.zlist:delete(obj) end function SceneMT:move(obj, newZ) self:remove(obj) obj.z = newZ self:insert(obj) end function SceneMT:clear() for _,item in self.zlist:ipairs() do self.zlist:delete(item) end end function SceneMT:size() return self.zlist.size end local BasicNodeWrapper = Class.create("BasicNodeWrapper", nil, { __lt = lessThan, __le = lessThan, init = function (self, object, z) if type(object) == "function" then self.draw, self.update = object, __NULL__ else self.object = object end self.z = z MakeNode(self) end, draw = function (self) (self.object.draw or __NULL__)(self.object) end, update = function (self, dt) (self.object.update or __NULL__)(self.object, dt) end, }) return { new = function (...) return SceneMT(...) end, lessThan = lessThan, makeNode = MakeNode, wrapNode = function (...) return BasicNodeWrapper(...) end }
mit
alexd2580/igjam2016
src/lib/push/examples/1/init.lua
1
1344
examples[1] = function () --default example love.graphics.setDefaultFilter("linear", "linear") --default filter local gameWidth, gameHeight = 1080, 720 local windowWidth, windowHeight = love.window.getDesktopDimensions() windowWidth, windowHeight = windowWidth*.5, windowHeight*.5 push:setupScreen(gameWidth, gameHeight, windowWidth, windowHeight, {fullscreen = false, resizable = true}) push:setBorderColor{0, 0, 0} --default value function love.load() love.graphics.setNewFont(32) end function love.update(dt) end function love.draw() push:apply("start") love.graphics.setColor(100, 100, 100) love.graphics.rectangle("fill", 0, 0, gameWidth, gameHeight) local mouseX, mouseY = love.mouse.getPosition() mouseX, mouseY = push:toGame(mouseX, mouseY) --if nil is returned, that means the mouse is outside the game screen love.graphics.setColor(255, 255, 255) love.graphics.circle("fill", gameWidth*.5, gameHeight*.5, 50) love.graphics.setColor(200, 0, 0) if mouseX and mouseY then love.graphics.circle("line", mouseX, mouseY, 10) end love.graphics.print("mouse x : " .. (mouseX or "outside"), gameWidth-300, 32) love.graphics.print("mouse y : " .. (mouseY or "outside"), gameWidth-300, 64) push:apply("end") end end
mit
Oxygem/Oxycore
app/object.lua
1
6475
-- Oxypanel Core -- File: app/object.lua -- Desc: generic object handler (mapped to <module>_<object-type> in db) --Localize local ngx = ngx local database, user, request = luawa.database, luawa.user, luawa.request -- Oxy.object local object = {} -- Oxy setup function object:setup() ngx.ctx.objects = {} end -- New object 'factory' function object:new(type) if not oxy.config.objects[type] then return false end --create new object, set type local object = { type = type, module = oxy.config.objects[type].module, cache = {} } --if custom fields for lists object.fields = oxy.config.objects[type].fields or true --make this factory inherit from this setmetatable(object, { __index = self }) --return the new object class w/ type set return object end -- Fetch an object as lua object (NO permission checks - ie internal) function object:fetch(id, prepare, fields) if ngx.ctx.objects[self.type .. id] then return ngx.ctx.objects[self.type .. id] end fields = fields or 'id, name' --get object from mysql (get all fields - assume need all on fetch) local object, err = database:select( self.module .. '_' .. self.type, fields, { id = id }, { limit = 1 } ) --if we got none back if #object ~= 1 then err = 'No ' .. self.type .. ' found' return false, err end object = object[1] --load the object 'class' according to type local type = require(oxy.config.root .. 'modules/' .. self.module .. '/object/' .. self.type) --set new objects to inherit from type setmetatable(object, { __index = type }) --give object its type object._type = self.type --helper functions local this = self --edit object details in database object._edit = function(self, data) --update database local update, err = database:update( this.module .. '_' .. this.type, data, { id = self.id }, 1 ) return update, err end --delete the object object._delete = function(self) return this:delete(self.id) end --change object owner object._owner = function(self, user, group) local update, err = self._edit(self, { user_id = user, group_id = group }) return update, err end --run any prepare function if prepare and object.prepare then object:prepare() end ngx.ctx.objects[self.type .. id] = object return object end -- Get an object w/ permission check on active user function object:get(id, permission) --permission permission = permission or 'view' --we got permission? if not self:permission(id, permission) then return false, 'You do not have permission to ' .. permission .. ' this ' .. self.type end --fetch! return self:fetch(id, true, '*') end -- Check current user permissions on object (Admin, View, Edit) function object:permission(id, permission) --permission to any if user:checkPermission(permission .. 'Any' .. self.type) then return true end --permission to owned if user:checkPermission(permission .. 'Own' .. self.type) then local tmp_key = self.type .. id .. user:getData().id if ngx.ctx.permissions[tmp_key] ~= nil then return ngx.ctx.permissions[tmp_key] end local test = database:select( self.module .. '_' .. self.type, 'id', { id = id, { user_id = user:getData().id, group_id = user:getData().group } }, 'id ASC', 1 ) if #test == 1 then ngx.ctx.permissions[tmp_key] = true return true else ngx.ctx.permissions[tmp_key] = false end end --default response return false end -- Delete (mysql only) function object:delete(id) --we got permission? if not self:permission(id, 'delete') then return false, 'You do not have permission to delete this ' .. self.type end --delete local delete, err = database:delete( self.module .. '_' .. self.type, { id = id }, 1 ) return delete, err end -- Get all objects (mysql list only) function object:getAll(wheres, options) return self:getList(wheres, options, true) end -- Get all owned objects (mysql list only) function object:getOwned(wheres, options) return self:getList(wheres, options) end -- Get list of objects from mysql (DRY, see above) function object:getList(wheres, options, all) --not logged in? if not user:checkLogin() then return false, 'You need to be logged in' end --type edit/delete permissions local type, edit, delete, ownedit, owndelete = self.type, false, false, false, false wheres = wheres or {} --are we looking for all objects, or just owned if all then --do we have permission to ViewAny<Object> if not user:checkPermission('ViewAny' .. type) then return false, 'You do not have permission view all ' .. type .. 's' end if user:checkPermission('EditAny' .. type) then edit = true end if user:checkPermission('EditOwn' .. type) then ownedit = true end if user:checkPermission('DeleteAny' .. type) then delete = true end if user:checkPermission('DeleteOwn' .. type) then owndelete = true end else --do we have permission to ViewOwn<Object> if not user:checkPermission('ViewOwn' .. type) then return false, 'You do not have permission view owned ' .. type .. 's' end if user:checkPermission('EditOwn' .. type) then edit = true end if user:checkPermission('DeleteOwn' .. type) then delete = true end --make sure we match user or group id table.insert(wheres, { user_id = user:getData().id, group_id = user:getData().group }) end --get objects from mysql (only get fields needed for lists) local objects = database:select( self.module .. '_' .. self.type, self.fields, wheres, options ) --assign edit & delete permissions for k, object in pairs(objects) do object.permissions = { edit = edit, delete = delete } if all and (object.user_id == user:getData().id or object.group_id == user:getData().group) then if not delete then object.permissions.delete = owndelete end if not edit then object.permissions.edit = ownedit end end end return objects end return object
mit
oitofelix/mininim
data/sblast/sblast.lua
2
1257
--[[ sblast.lua -- Sound Blaster audio mode; Copyright (C) 2015, 2016, 2017 Bruno Félix Rezende Ribeiro <oitofelix@gnu.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 3, 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/>. --]] -- header local P = {package_type = "AUDIO MODE", package_name = "SBLAST", package_file = mininim.debugger.src} -- imports local M = mininim local common = require "script/common" local function p (filename) return common.load_sample (P, filename) end local function t (filename) return common.load_stream (P, filename) end -- body setfenv (1, P) function load () M.audio[package_name] = {SUSPENSE = p "audio/suspense.ogg"} return P end -- end return P
gpl-3.0
mamaddeveloper/uzz
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
lcheylus/haka
lib/haka/lua/lua/state_machine.lua
3
6734
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local state = require("state") -- Hide internals local state_machine = haka.state_machine local state_machine_state = haka.state local state_machine_instance = haka.state_machine_instance haka.state_machine = nil haka.state = nil haka.state_machine_instance = nil local class = require('class') local states = {} local log = haka.log_section("states") states.StateMachine = class.class('StateMachine') function states.StateMachine.method:__init(name) self._states = { } self._default = state.ActionCollection:new() self.name = name end function states.StateMachine.method:compile() if not self._state_machine then self._state_machine = state_machine(self.name) self._state_table = {} local initial if not self._initial then error("state machine must have an initial state") end local unused = {} for name, s in pairs(self._states) do unused[name] = s end for name, s in pairs(self._states) do assert(class.isa(s, state.State), "invalid state type") s:setdefaults(self._default) local new_state = state.CompiledState:new(self, s, name) self._state_table[name] = new_state if s == self._initial then initial = new_state unused[name] = nil end -- Mark states as used for _, event in pairs(s._actions) do for _, a in ipairs(event) do if a.jump then unused[a.jump] = nil end end end end if not initial then error("state machine has an unknown initial state") end for name, _ in pairs(unused) do log.warning("state machine %s never jump on state: %s", self.name, name) end self._state_machine.initial = initial._compiled_state self._state_table.initial = initial self._state_table.fail = { _compiled_state = self._state_machine.fail_state } self._state_table.finish = { _compiled_state = self._state_machine.finish_state } self._state_machine:compile() end end function states.StateMachine.method:dump_graph(file) file:write('digraph state_machine {\n') file:write('fail [fillcolor="#ee0000",style="filled"]\n') file:write('finish [fillcolor="#00ee00",style="filled"]\n') file:write(string.format('%s [fillcolor="#00d7ff",style="filled"]\n', self._initial._name)) for name, state in pairs(self._states) do state:_dump_graph(file) end file:write("}\n") end function states.StateMachine.method:instanciate(owner) return states.StateMachineInstance:new(self, owner) end states.StateMachineInstance = class.class('StateMachineInstance') states.StateMachineInstance.property.current = { get = function (self) return self._instance.state end } function states.StateMachineInstance.method:__init(state_machine, owner) assert(state_machine, "state machine description required") assert(owner, "state machine context required") self._state_machine = state_machine self.states = state_machine._state_table self._instance = state_machine._state_machine:instanciate(owner) self._instance:init() self.owner = owner end function states.StateMachineInstance.method:update(...) local current = self.states[self._instance.state] if not current then error("state machine instance has finished") end current._state:update(self, ...) end function states.StateMachineInstance.method:trigger(name, ...) local current = self.states[self._instance.state] if not current then error("state machine instance has finished") end local trans = current[name] if not trans then error(string.format("no event named '%s' on state '%s'", name, current._name)) end local newstate = trans(self.owner, ...) if newstate then self._instance:update(newstate) end end function states.StateMachineInstance.method:finish() self._instance:finish() end local state_machine_int = {} local function state_machine_env(state_machine) state_machine_int.state_type = function (state_class) assert(type(state_class) == 'table', "state type must be either a table or an existing state type") if not class.isaclass(state_class, state.State) then state_class = state.new(state_class) end state_machine._state_type = state_class end state_machine_int.initial = function (state) state_machine._initial = state end state_machine_int.state = function (...) assert(state_machine._state_type, "cannot create state without prior call to state_type()") return state_machine._state_type:new(...) end -- Fake special states state_machine_int.finish = state.State:new("finish") state_machine_int.fail = state.State:new("fail") -- Special default actions collection state_machine_int.any = state_machine._default -- Events proxying state_machine_int.events = {} state_machine_int.events.timeout = function(timeout) return { name = "timeouts", timeout = timeout } end setmetatable(state_machine_int.events, { __index = function (self, name) return { name = name } end, __newindex = function () error("events is a read only table") end }) return { __index = function (self, name) local ret -- Search in the state classes ret = state[name] if ret then return ret end -- Search in the state_machine environment ret = state_machine_int[name] if ret then return ret end -- Search the defined rules ret = state_machine._states[name] if ret then return ret end return nil end, __newindex = function (self, key, value) -- Forbid override to state_machine elements if state_machine_int[key] then error(string.format("'%s' is reserved in the state machine scope", key)) end if class.isa(value, state.State) then -- Add the object in the states value._name = key state_machine._states[key] = value else rawset(self, key, value) end end } end local state_machine = {} state_machine.State = state.State state_machine.BidirectionnalState = state.BidirectionnalState state_machine.new_state_type = state.new function state_machine.new(name, def) assert(type(def) == 'function', "state machine definition must by a function") local sm = states.StateMachine:new(name) -- Add a metatable to the environment only during the definition -- of the grammar. local env = debug.getfenv(def) setmetatable(env, state_machine_env(sm)) def() setmetatable(env, nil) sm:compile() if state_machine.debug then log.warning("dumping '%s' state_machine graph to %s-state-machine.dot", sm.name, sm.name) f = io.open(string.format("%s-state-machine.dot", sm.name), "w+") sm:dump_graph(f) f:close() end return sm end state_machine.debug = false haka.state_machine = state_machine
mpl-2.0
emptyrivers/WeakAuras2
WeakAurasOptions/BuffTrigger.lua
1
33106
if not WeakAuras.IsCorrectVersion() then return end local AddonName, OptionsPrivate = ... local L = WeakAuras.L; local function getAuraMatchesLabel(name) local ids = WeakAuras.spellCache.GetSpellsMatching(name) if(ids) then local descText = ""; local numMatches = 0; for id, _ in pairs(ids) do numMatches = numMatches + 1; end if(numMatches == 1) then return L["1 Match"]; else return L["%i Matches"]:format(numMatches); end else return ""; end end -- the spell id table is sparse, so tremove doesn't work local function spellId_tremove(tbl, pos) for i = pos, 9, 1 do tbl[i] = tbl[i + 1] end end local function getAuraMatchesList(name) local ids = WeakAuras.spellCache.GetSpellsMatching(name) if(ids) then local descText = ""; for id, _ in pairs(ids) do local name, _, icon = GetSpellInfo(id); if(icon) then if(descText == "") then descText = "|T"..icon..":0|t: "..id; else descText = descText.."\n|T"..icon..":0|t: "..id; end end end return descText; else return ""; end end local noop = function() end local function CanShowNameInfo(data) if(data.regionType == "aurabar" or data.regionType == "icon" or data.regionType == "text") then return true; else return false; end end local function CanShowStackInfo(data) if(data.regionType == "aurabar" or data.regionType == "icon" or data.regionType == "text") then return true; else return false; end end local function GetBuffTriggerOptions(data, triggernum) local trigger = data.triggers[triggernum].trigger trigger.names = trigger.names or {} trigger.spellIds = trigger.spellIds or {} local spellCache = WeakAuras.spellCache; local ValidateNumeric = WeakAuras.ValidateNumeric; local aura_options = { deleteNote = { type = "description", order = 8, name = L["Note: The legacy buff trigger is now permanently disabled. It will be removed in the near future."], fontSize = "large" }, convertToBuffTrigger2SpaceBeforeDesc = { type = "description", width = 0.4, order = 8.1, name = "", }, convertToBuffTrigger2Desc = { type = "description", width = WeakAuras.doubleWidth - 0.8, order = 8.2, name = function() if (not OptionsPrivate.Private.CanConvertBuffTrigger2) then return ""; end local _, err = OptionsPrivate.Private.CanConvertBuffTrigger2(trigger); return err or ""; end, }, convertToBuffTrigger2SpaceAfterDesc = { type = "description", width = 0.4, order = 8.3, name = "", }, convertToBuffTrigger2SpaceBefore = { type = "description", width = 0.3, order = 8.4, name = "", }, convertToBuffTrigger2 = { type = "execute", width = WeakAuras.doubleWidth - 0.6, name = L["Convert to New Aura Trigger"], order = 8.5, disabled = function() if (not OptionsPrivate.Private.CanConvertBuffTrigger2) then return true; end if (not OptionsPrivate.Private.CanConvertBuffTrigger2(trigger)) then return true; end return false; end, desc = function() local _, err = OptionsPrivate.Private.CanConvertBuffTrigger2(trigger); return err or "" end, func = function() OptionsPrivate.Private.ConvertBuffTrigger2(trigger); WeakAuras.Add(data); WeakAuras.UpdateDisplayButton(data) WeakAuras.ClearAndUpdateOptions(data.id); end }, convertToBuffTrigger2SpaceAfter = { type = "description", width = 0.3, order = 8.6, name = "", }, fullscan = { type = "toggle", name = L["Use Full Scan (High CPU)"], width = WeakAuras.doubleWidth, order = 9, set = noop }, autoclone = { type = "toggle", name = L["Show all matches (Auto-clone)"], width = WeakAuras.doubleWidth, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, order = 9.5, set = noop }, useName = { type = "toggle", name = L["Aura(s)"], width = WeakAuras.halfWidth, order = 10, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit ~= "multi"); end, disabled = true, get = function() return true end, set = noop }, use_name = { type = "toggle", width = WeakAuras.normalWidth, name = L["Aura Name"], order = 10, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, set = noop }, name_operator = { type = "select", width = WeakAuras.normalWidth, name = L["Operator"], order = 11, disabled = function() return not trigger.use_name end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, values = OptionsPrivate.Private.string_operator_types, set = noop }, name = { type = "input", name = L["Aura Name"], width = WeakAuras.doubleWidth, order = 12, disabled = function() return not trigger.use_name end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, set = noop }, use_tooltip = { type = "toggle", width = WeakAuras.normalWidth, name = L["Tooltip"], order = 13, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, set = noop }, tooltip_operator = { type = "select", width = WeakAuras.normalWidth, name = L["Operator"], order = 14, disabled = function() return not trigger.use_tooltip end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, values = OptionsPrivate.Private.string_operator_types, set = noop }, tooltip = { type = "input", width = WeakAuras.doubleWidth, name = L["Tooltip"], order = 15, disabled = function() return not trigger.use_tooltip end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, set = noop }, use_stealable = { type = "toggle", width = WeakAuras.doubleWidth, name = function(input) local value = trigger.use_stealable; if(value == nil) then return L["Stealable"]; elseif(value == false) then return "|cFFFF0000 "..L["Negator"].." "..L["Stealable"]; else return "|cFF00FF00"..L["Stealable"]; end end, order = 16, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, get = function() local value = trigger.use_stealable; if(value == nil) then return false; elseif(value == false) then return "false"; else return "true"; end end, set = noop }, use_spellId = { type = "toggle", width = WeakAuras.normalWidth, name = L["Spell ID"], order = 17, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, set = noop }, spellId = { type = "input", width = WeakAuras.normalWidth, name = L["Spell ID"], order = 18, disabled = function() return not trigger.use_spellId end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.unit ~= "multi"); end, set = noop }, use_debuffClass = { type = "toggle", width = WeakAuras.normalWidth, name = L["Debuff Type"], order = 19, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, set = noop }, debuffClass = { type = "select", width = WeakAuras.normalWidth, name = L["Debuff Type"], order = 20, disabled = function() return not trigger.use_debuffClass end, hidden = function() return not (trigger.type == "aura" and trigger.fullscan); end, values = OptionsPrivate.Private.debuff_class_types, set = noop }, multiuse_name = { type = "toggle", width = WeakAuras.halfWidth, name = L["Aura Name"], order = 10, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit == "multi"); end, disabled = true, get = function() return true end, set = noop }, multiicon = { type = "execute", width = WeakAuras.halfWidth, name = "", image = function() if (not trigger.name) then return "" end; local icon = spellCache.GetIcon(trigger.name); return icon and tostring(icon) or "", 18, 18 end, order = 11, disabled = function() return not trigger.name and spellCache.GetIcon(trigger.name) end, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit == "multi"); end, set = noop }, multiname = { type = "input", width = WeakAuras.normalWidth, name = L["Aura Name"], desc = L["Enter an aura name, partial aura name, or spell id"], order = 12, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit == "multi"); end, get = function(info) return trigger.spellId and tostring(trigger.spellId) or trigger.name end, set = noop }, name1icon = { type = "execute", width = WeakAuras.halfWidth, name = function() return getAuraMatchesLabel(trigger.names[1]) end, desc = function() return getAuraMatchesList(trigger.names[1]) end, image = function() local icon = spellCache.GetIcon(trigger.names[1]); return icon and tostring(icon) or "", 18, 18 end, order = 11, disabled = function() return not spellCache.GetIcon(trigger.names[1]) end, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit ~= "multi"); end, set = noop }, name1 = { type = "input", width = WeakAuras.normalWidth, name = L["Aura Name"], desc = L["Enter an aura name, partial aura name, or spell id"], order = 12, hidden = function() return not (trigger.type == "aura" and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[1] and tostring(trigger.spellIds[1]) or trigger.names[1] end, set = noop }, name2space = { type = "execute", width = WeakAuras.halfWidth, name = L["or"], image = function() return "", 0, 0 end, order = 13, hidden = function() return not (trigger.type == "aura" and trigger.names[1] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name2icon = { type = "execute", width = WeakAuras.halfWidth, name = function() return getAuraMatchesLabel(trigger.names[2]) end, desc = function() return getAuraMatchesList(trigger.names[2]) end, image = function() local icon = spellCache.GetIcon(trigger.names[2]); return icon and tostring(icon) or "", 18, 18 end, order = 14, disabled = function() return not spellCache.GetIcon(trigger.names[2]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[1] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name2 = { type = "input", width = WeakAuras.normalWidth, order = 15, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[1] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[2] and tostring(trigger.spellIds[2]) or trigger.names[2] end, set = noop }, name3space = { type = "execute", width = WeakAuras.halfWidth, name = "", image = function() return "", 0, 0 end, order = 16, hidden = function() return not (trigger.type == "aura" and trigger.names[2] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name3icon = { type = "execute", width = WeakAuras.halfWidth, name = function() return getAuraMatchesLabel(trigger.names[3]) end, desc = function() return getAuraMatchesList(trigger.names[3]) end, image = function() local icon = spellCache.GetIcon(trigger.names[3]); return icon and tostring(icon) or "", 18, 18 end, order = 17, disabled = function() return not spellCache.GetIcon(trigger.names[3]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[2] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name3 = { type = "input", width = WeakAuras.normalWidth, order = 18, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[2] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[3] and tostring(trigger.spellIds[3]) or trigger.names[3] end, set = noop }, name4space = { type = "execute", width = WeakAuras.halfWidth, name = "", image = function() return "", 0, 0 end, order = 19, hidden = function() return not (trigger.type == "aura" and trigger.names[3] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name4icon = { type = "execute", width = WeakAuras.halfWidth, name = function() return getAuraMatchesLabel(trigger.names[4]) end, desc = function() return getAuraMatchesList(trigger.names[4]) end, image = function() local icon = spellCache.GetIcon(trigger.names[4]); return icon and tostring(icon) or "", 18, 18 end, order = 20, disabled = function() return not spellCache.GetIcon(trigger.names[4]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[3] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name4 = { type = "input", order = 21, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[3] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[4] and tostring(trigger.spellIds[4]) or trigger.names[4] end, set = noop }, name5space = { type = "execute", width = WeakAuras.halfWidth, name = "", image = function() return "", 0, 0 end, order = 22, disabled = function() return not spellCache.GetIcon(trigger.names[5]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[4] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name5icon = { type = "execute", width = WeakAuras.halfWidth, name = function() return getAuraMatchesLabel(trigger.names[5]) end, desc = function() return getAuraMatchesList(trigger.names[5]) end, image = function() local icon = spellCache.GetIcon(trigger.names[5]); return icon and tostring(icon) or "", 18, 18 end, order = 23, hidden = function() return not (trigger.type == "aura" and trigger.names[4] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name5 = { type = "input", width = WeakAuras.normalWidth, order = 24, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[4] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[5] and tostring(trigger.spellIds[5]) or trigger.names[5] end, set = noop }, name6space = { type = "execute", name = "", width = WeakAuras.halfWidth, image = function() return "", 0, 0 end, order = 25, hidden = function() return not (trigger.type == "aura" and trigger.names[5] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name6icon = { type = "execute", name = function() return getAuraMatchesLabel(trigger.names[6]) end, desc = function() return getAuraMatchesList(trigger.names[6]) end, width = WeakAuras.halfWidth, image = function() local icon = spellCache.GetIcon(trigger.names[6]); return icon and tostring(icon) or "", 18, 18 end, order = 26, disabled = function() return not spellCache.GetIcon(trigger.names[6]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[5] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name6 = { type = "input", width = WeakAuras.normalWidth, order = 27, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[5] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[6] and tostring(trigger.spellIds[6]) or trigger.names[6] end, set = noop }, name7space = { type = "execute", name = "", width = WeakAuras.halfWidth, image = function() return "", 0, 0 end, order = 28, hidden = function() return not (trigger.type == "aura" and trigger.names[6] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name7icon = { type = "execute", name = function() return getAuraMatchesLabel(trigger.names[7]) end, desc = function() return getAuraMatchesList(trigger.names[7]) end, width = WeakAuras.halfWidth, image = function() local icon = spellCache.GetIcon(trigger.names[7]); return icon and tostring(icon) or "", 18, 18 end, order = 29, disabled = function() return not spellCache.GetIcon(trigger.names[7]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[6] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name7 = { type = "input", width = WeakAuras.normalWidth, order = 30, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[6] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[7] and tostring(trigger.spellIds[7]) or trigger.names[7] end, set = noop }, name8space = { type = "execute", name = "", width = WeakAuras.halfWidth, image = function() return "", 0, 0 end, order = 31, hidden = function() return not (trigger.type == "aura" and trigger.names[7] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name8icon = { type = "execute", name = function() return getAuraMatchesLabel(trigger.names[8]) end, desc = function() return getAuraMatchesList(trigger.names[8]) end, width = WeakAuras.halfWidth, image = function() local icon = spellCache.GetIcon(trigger.names[8]); return icon and tostring(icon) or "", 18, 18 end, order = 32, disabled = function() return not spellCache.GetIcon(trigger.names[8]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[7] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name8 = { type = "input", width = WeakAuras.normalWidth, order = 33, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[7] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[8] and tostring(trigger.spellIds[8]) or trigger.names[8] end, set = noop }, name9space = { type = "execute", name = "", width = WeakAuras.halfWidth, image = function() return "", 0, 0 end, order = 34, hidden = function() return not (trigger.type == "aura" and trigger.names[8] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name9icon = { type = "execute", name = function() return getAuraMatchesLabel(trigger.names[9]) end, desc = function() return getAuraMatchesList(trigger.names[9]) end, width = WeakAuras.halfWidth, image = function() local icon = spellCache.GetIcon(trigger.names[9]); return icon and tostring(icon) or "", 18, 18 end, order = 35, disabled = function() return not spellCache.GetIcon(trigger.names[9]) end, hidden = function() return not (trigger.type == "aura" and trigger.names[8] and not trigger.fullscan and trigger.unit ~= "multi"); end, }, name9 = { type = "input", width = WeakAuras.normalWidth, order = 36, name = "", hidden = function() return not (trigger.type == "aura" and trigger.names[8] and not trigger.fullscan and trigger.unit ~= "multi"); end, get = function(info) return trigger.spellIds[9] and tostring(trigger.spellIds[9]) or trigger.names[9] end, set = noop }, useUnit = { type = "toggle", width = WeakAuras.normalWidth, name = L["Unit"], order = 40, disabled = true, hidden = function() return not (trigger.type == "aura"); end, get = function() return true end, set = noop }, unit = { type = "select", width = WeakAuras.normalWidth, name = L["Unit"], order = 41, values = function() if(trigger.fullscan) then return OptionsPrivate.Private.actual_unit_types_with_specific; else return OptionsPrivate.Private.unit_types; end end, hidden = function() return not (trigger.type == "aura"); end, get = function() if(trigger.fullscan and (trigger.unit == "group" or trigger.unit == "multi")) then trigger.unit = "player"; end return trigger.unit; end, set = noop }, useSpecificUnit = { type = "toggle", width = WeakAuras.normalWidth, name = L["Specific Unit"], order = 42, disabled = true, hidden = function() return not (trigger.type == "aura" and trigger.unit == "member") end, get = function() return true end, set = noop }, specificUnit = { type = "input", width = WeakAuras.normalWidth, name = L["Specific Unit"], order = 43, desc = L["Can be a Name or a Unit ID (e.g. party1). A name only works on friendly players in your group."], hidden = function() return not (trigger.type == "aura" and trigger.unit == "member") end, set = noop }, useGroup_count = { type = "toggle", width = WeakAuras.normalWidth, name = L["Group Member Count"], disabled = true, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, get = function() return true; end, order = 45, set = noop }, group_countOperator = { type = "select", name = L["Operator"], order = 46, width = WeakAuras.halfWidth, values = OptionsPrivate.Private.operator_types, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, get = function() return trigger.group_countOperator; end, set = noop }, group_count = { type = "input", name = L["Count"], desc = function() local groupType = OptionsPrivate.Private.unit_types[trigger.unit or "group"] or "|cFFFF0000error|r"; return L["Group aura count description"]:format(groupType, groupType, groupType, groupType, groupType, groupType, groupType); end, order = 47, width = WeakAuras.halfWidth, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, get = function() return trigger.group_count; end, set = noop }, useGroupRole = { type = "toggle", width = WeakAuras.normalWidth, name = L["Filter by Group Role"], order = 47.1, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, set = noop }, group_role = { type = "select", width = WeakAuras.normalWidth, name = L["Group Role"], values = OptionsPrivate.Private.role_types, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, disabled = function() return not trigger.useGroupRole; end, get = function() return trigger.group_role; end, order = 47.2, set = noop }, ignoreSelf = { type = "toggle", name = L["Ignore self"], order = 47.3, width = WeakAuras.doubleWidth, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, set = noop }, groupclone = { type = "toggle", name = L["Show all matches (Auto-clone)"], width = WeakAuras.doubleWidth, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, order = 47.4, set = noop }, name_info = { type = "select", width = WeakAuras.normalWidth, name = L["Name Info"], order = 47.5, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group" and not trigger.groupclone); end, disabled = function() return not CanShowNameInfo(data); end, get = function() if(CanShowNameInfo(data)) then return trigger.name_info; else return nil; end end, values = OptionsPrivate.Private.group_aura_name_info_types, set = noop }, stack_info = { type = "select", width = WeakAuras.normalWidth, name = L["Stack Info"], order = 47.6, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group" and not trigger.groupclone); end, disabled = function() return not CanShowStackInfo(data); end, get = function() if(CanShowStackInfo(data)) then return trigger.stack_info; else return nil; end end, values = OptionsPrivate.Private.group_aura_stack_info_types, set = noop }, hideAlone = { type = "toggle", name = L["Hide When Not In Group"], order = 47.7, width = WeakAuras.doubleWidth, hidden = function() return not (trigger.type == "aura" and trigger.unit == "group"); end, set = noop }, useDebuffType = { type = "toggle", width = WeakAuras.normalWidth, name = L["Aura Type"], order = 50, disabled = true, hidden = function() return not (trigger.type == "aura"); end, get = function() return true end, set = noop }, debuffType = { type = "select", width = WeakAuras.normalWidth, name = L["Aura Type"], order = 51, values = OptionsPrivate.Private.debuff_types, hidden = function() return not (trigger.type == "aura"); end, set = noop }, subcount = { type = "toggle", width = WeakAuras.doubleWidth, name = L["Use tooltip \"size\" instead of stacks"], hidden = function() return not (trigger.type == "aura" and trigger.fullscan) end, order = 55, set = noop }, subcountCount = { type = "select", values = OptionsPrivate.Private.tooltip_count, width = WeakAuras.doubleWidth, name = L["Use nth value from tooltip:"], hidden = function() return not (trigger.type == "aura" and trigger.fullscan and trigger.subcount) end, order = 55.5, set = noop }, useRem = { type = "toggle", width = WeakAuras.normalWidth, name = L["Remaining Time"], hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, order = 56, set = noop }, remOperator = { type = "select", name = L["Operator"], order = 57, width = WeakAuras.halfWidth, values = OptionsPrivate.Private.operator_types, disabled = function() return not trigger.useRem; end, hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, get = function() return trigger.useRem and trigger.remOperator or nil end, set = noop }, rem = { type = "input", name = L["Remaining Time"], validate = ValidateNumeric, order = 58, width = WeakAuras.halfWidth, disabled = function() return not trigger.useRem; end, hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, get = function() return trigger.useRem and trigger.rem or nil end, set = noop }, useCount = { type = "toggle", width = WeakAuras.normalWidth, name = L["Stack Count"], hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, order = 60, set = noop }, countOperator = { type = "select", name = L["Operator"], order = 62, width = WeakAuras.halfWidth, values = OptionsPrivate.Private.operator_types, disabled = function() return not trigger.useCount; end, hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, get = function() return trigger.useCount and trigger.countOperator or nil end, set = noop }, count = { type = "input", name = L["Stack Count"], validate = ValidateNumeric, order = 65, width = WeakAuras.halfWidth, disabled = function() return not trigger.useCount; end, hidden = function() return not (trigger.type == "aura" and trigger.unit ~= "multi"); end, get = function() return trigger.useCount and trigger.count or nil end, set = noop }, ownOnly = { type = "toggle", width = WeakAuras.doubleWidth, name = function() local value = trigger.ownOnly; if(value == nil) then return L["Own Only"]; elseif(value == false) then return "|cFFFF0000 "..L["Negator"].." "..L["Own Only"]; else return "|cFF00FF00"..L["Own Only"]; end end, desc = function() local value = trigger.ownOnly; if(value == nil) then return L["Only match auras cast by the player"]; elseif(value == false) then return L["Only match auras cast by people other than the player"]; else return L["Only match auras cast by the player"]; end end, get = function() local value = trigger.ownOnly; if(value == nil) then return false; elseif(value == false) then return "false"; else return "true"; end end, order = 70, hidden = function() return not (trigger.type == "aura"); end, set = noop }, useBuffShowOn = { type = "toggle", width = WeakAuras.normalWidth, name = L["Show On"], order = 71, disabled = true, hidden = function() return not (trigger.type == "aura" and not(trigger.unit ~= "group" and trigger.fullscan and trigger.autoclone) and trigger.unit ~= "multi" and not(trigger.unit == "group" and not trigger.groupclone)); end, get = function() return true end, set = noop }, buffShowOn = { type = "select", width = WeakAuras.normalWidth, name = "", values = OptionsPrivate.Private.bufftrigger_progress_behavior_types, order = 71.1, get = function() return trigger.buffShowOn end, hidden = function() return not (trigger.type == "aura" and not(trigger.unit ~= "group" and trigger.fullscan and trigger.autoclone) and trigger.unit ~= "multi" and not(trigger.unit == "group" and not trigger.groupclone)); end, set = noop }, unitExists = { type = "toggle", width = WeakAuras.normalWidth, name = L["Show If Unit Is Invalid"], order = 72, hidden = function() return not (trigger.type == "aura" and not(trigger.unit ~= "group" and trigger.fullscan and trigger.autoclone) and trigger.unit ~= "multi" and trigger.unit ~= "group" and trigger.unit ~= "player"); end, set = noop }, linespacer = { type = "description", order = 73, width = WeakAuras.doubleWidth, name = "", hidden = function() -- For those that update without restarting return not OptionsPrivate.Private.CanConvertBuffTrigger2 end, }, }; OptionsPrivate.commonOptions.AddCommonTriggerOptions(aura_options, data, triggernum) OptionsPrivate.commonOptions.AddTriggerGetterSetter(aura_options, data, triggernum) OptionsPrivate.AddTriggerMetaFunctions(aura_options, data, triggernum) return { ["trigger." .. triggernum .. ".legacy_aura_options"] = aura_options } end WeakAuras.RegisterTriggerSystemOptions({"aura"}, GetBuffTriggerOptions);
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/libs/lucid-rpc/luasrc/lucid/rpc/server.lua
52
8197
--[[ LuCI - Lua Development Framework Copyright 2009 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$ ]] local ipairs, pairs = ipairs, pairs local tostring, tonumber = tostring, tonumber local pcall, assert, type, unpack = pcall, assert, type, unpack local nixio = require "nixio" local json = require "luci.json" local util = require "luci.util" local table = require "table" local ltn12 = require "luci.ltn12" --- RPC daemom. -- @cstyle instance module "luci.lucid.rpc.server" RQLIMIT = 32 * nixio.const.buffersize VERSION = "1.0" ERRNO_PARSE = -32700 ERRNO_INVALID = -32600 ERRNO_UNKNOWN = -32001 ERRNO_TIMEOUT = -32000 ERRNO_NOTFOUND = -32601 ERRNO_NOACCESS = -32002 ERRNO_INTERNAL = -32603 ERRNO_NOSUPPORT = -32003 ERRMSG = { [ERRNO_PARSE] = "Parse error.", [ERRNO_INVALID] = "Invalid request.", [ERRNO_TIMEOUT] = "Connection timeout.", [ERRNO_UNKNOWN] = "Unknown error.", [ERRNO_NOTFOUND] = "Method not found.", [ERRNO_NOACCESS] = "Access denied.", [ERRNO_INTERNAL] = "Internal error.", [ERRNO_NOSUPPORT] = "Operation not supported." } --- Create an RPC method wrapper. -- @class function -- @param method Lua function -- @param description Method description -- @return Wrapped RPC method Method = util.class() --- Create an extended wrapped RPC method. -- @class function -- @param method Lua function -- @param description Method description -- @return Wrapped RPC method function Method.extended(...) local m = Method(...) m.call = m.xcall return m end function Method.__init__(self, method, description) self.description = description self.method = method end --- Extended call the associated function. -- @param session Session storage -- @param argv Request parameters -- @return function call response function Method.xcall(self, session, argv) return self.method(session, unpack(argv)) end --- Standard call the associated function. -- @param session Session storage -- @param argv Request parameters -- @return function call response function Method.call(self, session, argv) return self.method(unpack(argv)) end --- Process a given request and create a JSON response. -- @param session Session storage -- @param request Requested method -- @param argv Request parameters function Method.process(self, session, request, argv) local stat, result = pcall(self.call, self, session, argv) if stat then return { result=result } else return { error={ code=ERRNO_UNKNOWN, message=ERRMSG[ERRNO_UNKNOWN], data=result } } end end -- Remap IPv6-IPv4-compatibility addresses to IPv4 addresses local function remapipv6(adr) local map = "::ffff:" if adr:sub(1, #map) == map then return adr:sub(#map+1) else return adr end end --- Create an RPC module. -- @class function -- @param description Method description -- @return RPC module Module = util.class() function Module.__init__(self, description) self.description = description self.handler = {} end --- Add a handler. -- @param k key -- @param v handler function Module.add(self, k, v) self.handler[k] = v end --- Add an access restriction. -- @param restriction Restriction specification function Module.restrict(self, restriction) if not self.restrictions then self.restrictions = {restriction} else self.restrictions[#self.restrictions+1] = restriction end end --- Enforce access restrictions. -- @param request Request object -- @return nil or HTTP statuscode, table of headers, response source function Module.checkrestricted(self, session, request, argv) if not self.restrictions then return end for _, r in ipairs(self.restrictions) do local stat = true if stat and r.interface then -- Interface restriction if not session.localif then for _, v in ipairs(session.env.interfaces) do if v.addr == session.localaddr then session.localif = v.name break end end end if r.interface ~= session.localif then stat = false end end if stat and r.user and session.user ~= r.user then -- User restriction stat = false end if stat then return end end return {error={code=ERRNO_NOACCESS, message=ERRMSG[ERRNO_NOACCESS]}} end --- Register a handler, submodule or function. -- @param m entity -- @param descr description -- @return Module (self) function Module.register(self, m, descr) descr = descr or {} for k, v in pairs(m) do if util.instanceof(v, Method) then self.handler[k] = v elseif type(v) == "table" then self.handler[k] = Module() self.handler[k]:register(v, descr[k]) elseif type(v) == "function" then self.handler[k] = Method(v, descr[k]) end end return self end --- Process a request. -- @param session Session storage -- @param request Request object -- @param argv Request parameters -- @return JSON response object function Module.process(self, session, request, argv) local first, last = request:match("^([^.]+).?(.*)$") local stat = self:checkrestricted(session, request, argv) if stat then -- Access Denied return stat end local hndl = first and self.handler[first] if not hndl then return {error={code=ERRNO_NOTFOUND, message=ERRMSG[ERRNO_NOTFOUND]}} end session.chain[#session.chain+1] = self return hndl:process(session, last, argv) end --- Create a server object. -- @class function -- @param root Root module -- @return Server object Server = util.class() function Server.__init__(self, root) self.root = root end --- Get the associated root module. -- @return Root module function Server.get_root(self) return self.root end --- Set a new root module. -- @param root Root module function Server.set_root(self, root) self.root = root end --- Create a JSON reply. -- @param jsonrpc JSON-RPC version -- @param id Message id -- @param res Result -- @param err Error -- @reutrn JSON response source function Server.reply(self, jsonrpc, id, res, err) id = id or json.null -- 1.0 compatibility if jsonrpc ~= "2.0" then jsonrpc = nil res = res or json.null err = err or json.null end return json.Encoder( {id=id, result=res, error=err, jsonrpc=jsonrpc}, BUFSIZE ):source() end --- Handle a new client connection. -- @param client client socket -- @param env superserver environment function Server.process(self, client, env) local decoder local sinkout = client:sink() client:setopt("socket", "sndtimeo", 90) client:setopt("socket", "rcvtimeo", 90) local close = false local session = {server = self, chain = {}, client = client, env = env, localaddr = remapipv6(client:getsockname())} local req, stat, response, result, cb repeat local oldchunk = decoder and decoder.chunk decoder = json.ActiveDecoder(client:blocksource(nil, RQLIMIT)) decoder.chunk = oldchunk result, response, cb = nil, nil, nil -- Read one request stat, req = pcall(decoder.get, decoder) if stat then if type(req) == "table" and type(req.method) == "string" and (not req.params or type(req.params) == "table") then req.params = req.params or {} result, cb = self.root:process(session, req.method, req.params) if type(result) == "table" then if req.id ~= nil then response = self:reply(req.jsonrpc, req.id, result.result, result.error) end close = result.close else if req.id ~= nil then response = self:reply(req.jsonrpc, req.id, nil, {code=ERRNO_INTERNAL, message=ERRMSG[ERRNO_INTERNAL]}) end end else response = self:reply(req.jsonrpc, req.id, nil, {code=ERRNO_INVALID, message=ERRMSG[ERRNO_INVALID]}) end else if nixio.errno() ~= nixio.const.EAGAIN then response = self:reply("2.0", nil, nil, {code=ERRNO_PARSE, message=ERRMSG[ERRNO_PARSE]}) --[[else response = self:reply("2.0", nil, nil, {code=ERRNO_TIMEOUT, message=ERRMSG_TIMEOUT})]] end close = true end if response then ltn12.pump.all(response, sinkout) end if cb then close = cb(client, session, self) or close end until close client:shutdown() client:close() end
gpl-2.0
spacebuild/sbep
lua/entities/livable_module/init.lua
2
22756
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) util.PrecacheSound( "apc_engine_start" ) util.PrecacheSound( "apc_engine_stop" ) util.PrecacheSound( "common/warning.wav" ) include('shared.lua') function ENT:Initialize() self.BaseClass.Initialize(self) self.Active = 0 self.damaged = 0 self:CreateEnvironment(1, 1, 1, 0, 0, 0, 0, 0) self.currentsize = self:BoundingRadius() self.maxsize = self:BoundingRadius() self.maxO2Level = 100 if not (WireAddon == nil) then self.WireDebugName = self.PrintName self.Inputs = Wire_CreateInputs(self, { "On", "Gravity", "Max O2 level" }) self.Outputs = Wire_CreateOutputs(self, { "On", "Oxygen-Level", "Temperature", "Gravity", "Damaged" }) else self.Inputs = { { Name = "On" }, { Name = "Radius" }, { Name = "Gravity" }, { Name = "Max O2 level" } } end CAF.GetAddon("Resource Distribution").RegisterNonStorageDevice(self) end function ENT:TurnOn() if (self.Active == 0) then self:EmitSound( "apc_engine_start" ) self.Active = 1 self:UpdateSize(self.sbenvironment.size, self.currentsize) --We turn the forcefield that contains the environment on if self.environment and not self.environment:IsSpace() then --Fill the environment with air if the surounding environment has o2, replace with CO2 self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + self.environment:Convert(0, -1, math.Round(self.sbenvironment.air.max/18)) end if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end self:SetOOO(1) end end function ENT:TurnOff() if (self.Active == 1) then self:StopSound( "apc_engine_start" ) self:EmitSound( "apc_engine_stop" ) self.Active = 0 if self.environment then --flush all resources into the environment if we are in one (used for the slownes of the SB updating process, we don't want errors do we?) if self.sbenvironment.air.o2 > 0 then local left = self:SupplyResource("oxygen", self.sbenvironment.air.o2) self.environment:Convert(-1, 0, left) end if self.sbenvironment.air.co2 > 0 then local left = self:SupplyResource("carbon dioxide", self.sbenvironment.air.co2) self.environment:Convert(-1, 1, left) end if self.sbenvironment.air.n > 0 then local left = self:SupplyResource("nitrogen", self.sbenvironment.air.n) self.environment:Convert(-1, 2, left) end if self.sbenvironment.air.h > 0 then local left = self:SupplyResource("hydrogen", self.sbenvironment.air.h) self.environment:Convert(-1, 3, left) end end self.sbenvironment.temperature = 0 self:UpdateSize(self.sbenvironment.size, 0) --We turn the forcefield that contains the environment off! if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end self:SetOOO(0) end end function ENT:TriggerInput(iname, value) if (iname == "On") then self:SetActive(value) elseif (iname == "Gravity") then local gravity = value if value <= 0 then gravity = 0 end self.sbenvironment.gravity = gravity elseif (iname == "Max O2 level") then local level = 100 level = math.Clamp(math.Round(value), 0, 100) self.maxO2Level = level end end function ENT:Damage() if (self.damaged == 0) then self.damaged = 1 end if ((self.Active == 1) and (math.random(1, 10) <= 3)) then self:TurnOff() end end function ENT:Repair() self.BaseClass.Repair(self) self:SetColor(255, 255, 255, 255) self.damaged = 0 end function ENT:Destruct() CAF.GetAddon("Spacebuild").RemoveEnvironment(self) CAF.GetAddon("Life Support").LS_Destruct(self, true) end function ENT:OnRemove() CAF.GetAddon("Spacebuild").RemoveEnvironment(self) self.BaseClass.OnRemove(self) self:StopSound("apc_engine_start") end function ENT:PreEntityCopy() local LivableModule = {} LivableModule.Active = self.Active LivableModule.damaged = self.damaged if WireAddon then duplicator.StoreEntityModifier(self,"WireDupeInfo",WireLib.BuildDupeInfo(self.Entity)) end duplicator.StoreEntityModifier(self, "livable_module", LivableModule) end function ENT:PostEntityPaste(ply, ent, createdEnts) if WireAddon then local emods = ent.EntityMods if emods and emods.WireDupeInfo then WireLib.ApplyDupeInfo(ply, ent, emods.WireDupeInfo, function(id) return createdEnts[id] end) end end end function MakeLivableModule( Player, Data ) local ent = ents.Create( Data.Class ) duplicator.DoGeneric( ent, Data ) ent:Spawn() duplicator.DoGenericPhysics( ent, Player, Data ) ent:SetPlayer(Player) ent.damaged = Data.EntityMods.livable_module.damaged if CPPI then ent:CPPISetOwner(Player) end if Data.EntityMods.livable_module.Active == 1 then ent:TurnOn() end return ent end duplicator.RegisterEntityClass( "livable_module", MakeLivableModule, "Data" ) --[[ function ENT:CreateEnvironment(gravity, atmosphere, pressure, temperature, o2, co2, n, h) --Msg("CreateEnvironment: "..tostring(gravity).."\n") --set Gravity if one is given if gravity and type(gravity) == "number" then if gravity < 0 then gravity = 0 end self.sbenvironment.gravity = gravity end --set atmosphere if given if atmosphere and type(atmosphere) == "number" then if atmosphere < 0 then atmosphere = 0 elseif atmosphere > 1 then atmosphere = 1 end self.sbenvironment.atmosphere = atmosphere end --set pressure if given if pressure and type(pressure) == "number" and pressure >= 0 then self.sbenvironment.pressure = pressure else self.sbenvironment.pressure = math.Round(self.sbenvironment.atmosphere * self.sbenvironment.gravity) end --set temperature if given if temperature and type(temperature) == "number" then self.sbenvironment.temperature = temperature end --set o2 if given if o2 and type(o2) == "number" and o2 > 0 then if o2 > 100 then o2 = 100 end self.sbenvironment.air.o2per = o2 self.sbenvironment.air.o2 = math.Round(o2 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) else o2 = 0 self.sbenvironment.air.o2per = 0 self.sbenvironment.air.o2 = 0 end --set co2 if given if co2 and type(co2) == "number" and co2 > 0 then if (100 - o2) < co2 then co2 = 100-o2 end self.sbenvironment.air.co2per = co2 self.sbenvironment.air.co2 = 0 else co2 = 0 self.sbenvironment.air.co2per = 0 self.sbenvironment.air.co2 = 0 end --set n if given if n and type(n) == "number" and n > 0 then if ((100 - o2)-co2) < n then n = (100-o2)-co2 end self.sbenvironment.air.nper = n self.sbenvironment.air.n = 0 else n = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.n = 0 end --set h if given if h and type(h) == "number" then if (((100 - o2)-co2)-n) < h then h = ((100-o2)-co2)-n end self.sbenvironment.air.hper = h self.sbenvironment.air.h = math.Round(h * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) else h = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.h = 0 end if o2 + co2 + n + h < 100 then local tmp = 100 - (o2 + co2 + n + h) self.sbenvironment.air.empty = math.Round(tmp * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.emptyper = tmp elseif o2 + co2 + n + h > 100 then local tmp = (o2 + co2 + n + h) - 100 if co2 > tmp then self.sbenvironment.air.co2 = math.Round((co2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.co2per = co2 + tmp elseif n > tmp then self.sbenvironment.air.n = math.Round((n - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.nper = n + tmp elseif h > tmp then self.sbenvironment.air.h = math.Round((h - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.hper = h + tmp elseif o2 > tmp then self.sbenvironment.air.o2 = math.Round((o2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.o2per = o2 - tmp end end self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self:PrintVars() end -- ]] --[[ function ENT:UpdateSize(oldsize, newsize) if oldsize == newsize then return end if oldsize and newsize and type(oldsize) == "number" and type(newsize) == "number" and oldsize >= 0 and newsize >= 0 then if oldsize == 0 then self.sbenvironment.air.o2 = 0 self.sbenvironment.air.co2 = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.empty = 0 self.sbenvironment.size = newsize elseif newsize == 0 then local tomuch = self.sbenvironment.air.o2 if self.environment then tomuch = self.environment:Convert(-1, 0, tomuch) end tomuch = self.sbenvironment.air.co2 if self.environment then tomuch = self.environment:Convert(-1, 1, tomuch) end tomuch = self.sbenvironment.air.n if self.environment then tomuch = self.environment:Convert(-1, 2, tomuch) end tomuch = self.sbenvironment.air.h if self.environment then tomuch = self.environment:Convert(-1, 3, tomuch) end self.sbenvironment.air.o2 = 0 self.sbenvironment.air.co2 = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.empty = 0 self.sbenvironment.size = 0 else self.sbenvironment.air.o2 = (newsize/oldsize) * self.sbenvironment.air.o2 self.sbenvironment.air.co2 = (newsize/oldsize) * self.sbenvironment.air.co2 self.sbenvironment.air.n = (newsize/oldsize) * self.sbenvironment.air.n self.sbenvironment.air.h = (newsize/oldsize) * self.sbenvironment.air.h self.sbenvironment.air.empty = (newsize/oldsize) * self.sbenvironment.air.empty self.sbenvironment.size = newsize end self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) if self.sbenvironment.air.o2 > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.o2 - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 0, tomuch) self.sbenvironment.air.o2 = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.co2 > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.co2 - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 1, tomuch) self.sbenvironment.air.co2 = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.n > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.n - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 2, tomuch) self.sbenvironment.air.n = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.h > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.h - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 3, tomuch) self.sbenvironment.air.h = self.sbenvironment.air.max + tomuch end end end end --]] function ENT:Climate_Control() local temperature = 0 local pressure = 0 if self.environment then temperature = self.environment:GetTemperature(self) pressure = self.environment:GetPressure() --Msg("Found environment, updating\n") end --Msg("Temperature: "..tostring(temperature)..", pressure: " ..tostring(pressure).."\n") if self.Active == 1 then --Only do something if the device is on self.energy = self:GetResourceAmount("energy") if self.energy == 0 or self.energy < 3 * math.ceil(self.maxsize/1024) then --Don't have enough power to keep the controler\'s think process running, shut it all down self:TurnOff() return --Msg("Turning of\n") else self.air = self:GetResourceAmount("oxygen") self.coolant = self:GetResourceAmount("water") self.coolant2 = self:GetResourceAmount("nitrogen") self.energy = self:GetResourceAmount("energy") --First let check our air supply and try to stabilize it if we got oxygen left in storage at a rate of 10 oxygen per second if self.sbenvironment.air.o2 < self.sbenvironment.air.max * (self.maxO2Level/100) then --We need some energy to fire the pump! local energyneeded = 5 * math.ceil(self.maxsize/1024) local mul = 1 if self.energy < energyneeded then mul = self.energy/energyneeded self:ConsumeResource("energy", self.energy) else self:ConsumeResource("energy", energyneeded) end local air = math.ceil(1500 * mul) if self.air < air then air = self.air end if self.sbenvironment.air.co2 > 0 then local actual = self:Convert(1, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("carbon dioxide", actual) elseif self.sbenvironment.air.n > 0 then local actual = self:Convert(2, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("nitrogen", actual) elseif self.sbenvironment.air.h > 0 then local actual = self:Convert(3, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("hydrogen", actual) else self:ConsumeResource("oxygen", air) self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + air end elseif self.sbenvironment.air.o2 > self.sbenvironment.air.max then local tmp = self.sbenvironment.air.o2 - self.sbenvironment.air.max self:SupplyResource("oxygen", tmp) end --Now let's check the pressure, if pressure is larger then 1 then we need some more power to keep the climate_controls environment stable. We don\' want any leaks do we? if pressure > 1 then self:ConsumeResource("energy", (pressure-1) * 2 * math.ceil(self.maxsize/1024)) end if temperature < self.sbenvironment.temperature then local dif = self.sbenvironment.temperature - temperature dif = math.ceil(dif/100) --Change temperature depending on the outside temperature, 5° difference does a lot less then 10000° difference self.sbenvironment.temperature = self.sbenvironment.temperature - dif elseif temperature > self.sbenvironment.temperature then local dif = temperature - self.sbenvironment.temperature dif = math.ceil(dif / 100) self.sbenvironment.temperature = self.sbenvironment.temperature + dif end --Msg("Temperature: "..tostring(self.sbenvironment.temperature).."\n") if self.sbenvironment.temperature < 288 then --Msg("Heating up?\n") if self.sbenvironment.temperature + 60 <= 303 then self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 60 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 60 self:ConsumeResource("energy", 60 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 60 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("energy", self.energy) end elseif self.sbenvironment.temperature + 30 <= 303 then self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 30 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 30 self:ConsumeResource("energy", 30 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 30 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("energy", self.energy) end elseif self.sbenvironment.temperature + 15 <= 303 then self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 15 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 15 self:ConsumeResource("energy", 15 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 15 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("energy", self.energy) end else self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 5 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 5 self:ConsumeResource("energy", 5 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 5 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("energy", self.energy) end end elseif self.sbenvironment.temperature > 303 then if self.sbenvironment.temperature - 60 >= 288 then self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024)) if self.coolant2 > 12 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 60 self:ConsumeResource("nitrogen", 12 * math.ceil(self.maxsize/1024)) elseif self.coolant > 60 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 60 self:ConsumeResource("water", 60 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 12 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 60 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("water", self.coolant) end end elseif self.sbenvironment.temperature - 30 >= 288 then self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024)) if self.coolant2 > 6 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 30 self:ConsumeResource("nitrogen", 6 * math.ceil(self.maxsize/1024)) elseif self.coolant > 30 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 30 self:ConsumeResource("water", 30 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 6 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 30 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("water", self.coolant) end end elseif self.sbenvironment.temperature - 15 >= 288 then self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024)) if self.coolant2 > 3 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 15 self:ConsumeResource("nitrogen", 3 * math.ceil(self.maxsize/1024)) elseif self.coolant > 15 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 15 self:ConsumeResource("water", 15 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 3 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 15 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("water", self.coolant) end end else self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024)) if self.coolant2 > 1 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 5 self:ConsumeResource("nitrogen", 1 * math.ceil(self.maxsize/1024)) elseif self.coolant > 5 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 5 self:ConsumeResource("water", 5 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 1 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 5 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("water", self.coolant) end end end end end end if not (WireAddon == nil) then Wire_TriggerOutput(self, "Oxygen-Level", tonumber(self:GetO2Percentage())) Wire_TriggerOutput(self, "Temperature", tonumber(self.sbenvironment.temperature)) Wire_TriggerOutput(self, "Gravity", tonumber(self.sbenvironment.gravity)) Wire_TriggerOutput(self, "Damaged", tonumber(self.damaged)) end end function ENT:Think() self.BaseClass.Think(self) self:Climate_Control() self:NextThink(CurTime() + 1) return true end --[[ function ENT:OnEnvironment(ent) if not ent then return end if ent == self then return end local pos = ent:GetPos() local dist = pos:Distance(self:GetPos()) if dist < self:GetSize() then local min, max = ent:WorldSpaceAABB() if table.HasValue(ents.FindInBox( min, max ), ent) then if not ent.environment then ent.environment = self --self:UpdateGravity(ent) else if ent.environment:GetPriority() < self:GetPriority() then ent.environment = self --self:UpdateGravity(ent) elseif ent.environment:GetPriority() == self:GetPriority() then if ent.environment:GetSize() != 0 then if self:GetSize() <= ent.environment:GetSize() then ent.environment = self --self:UpdateGravity(ent) else if dist < pos:Distance(ent.environment:GetPos()) then ent.environment = self end end else ent.environment = self --self:UpdateGravity(ent) end end end end end end ]]
apache-2.0
deepak78/new-luci
applications/luci-app-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widget.lua
68
1039
-- Copyright 2012 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. local uci = require "luci.model.uci".cursor() local dsp = require "luci.dispatcher" local utl = require "luci.util" local widget = uci:get("freifunk-widgets", arg[1], "template") local title = uci:get("freifunk-widgets", arg[1], "title") or "" m = Map("freifunk-widgets", translate("Widget")) m.redirect = luci.dispatcher.build_url("admin/freifunk/widgets") if not arg[1] or m.uci:get("freifunk-widgets", arg[1]) ~= "widget" then luci.http.redirect(m.redirect) return end wdg = m:section(NamedSection, arg[1], "widget", translate("Widget") .. " " .. title) wdg.anonymous = true wdg.addremove = false local en = wdg:option(Flag, "enabled", translate("Enable")) en.rmempty = false local title = wdg:option(Value, "title", translate("Title")) title.rmempty = true local form = loadfile( utl.libpath() .. "/model/cbi/freifunk/widgets/%s.lua" % widget ) if form then setfenv(form, getfenv(1))(m, wdg) end return m
apache-2.0
machicao2013/redis-source-annotated
deps/lua/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
bsd-3-clause
iamliqiang/prosody-modules
mod_munin/mod_munin.lua
20
3500
module:set_global(); local s_format = string.format; local array = require"util.array"; local it = require"util.iterators"; local mt = require"util.multitable"; local meta = mt.new(); meta.data = module:shared"meta"; local data = mt.new(); data.data = module:shared"data"; local munin_listener = {}; local munin_commands = {}; local node_name = module:get_option_string("munin_node_name", "localhost"); local ignore_stats = module:get_option_set("munin_ignored_stats", { }); local function clean_fieldname(name) return (name:gsub("[^A-Za-z0-9_]", "_"):gsub("^[^A-Za-z_]", "_%1")); end function munin_listener.onconnect(conn) -- require"core.statsmanager".collect(); conn:write("# munin node at "..node_name.."\n"); end function munin_listener.onincoming(conn, line) line = line and line:match("^[^\r\n]+"); if type(line) ~= "string" then return end -- module:log("debug", "incoming: %q", line); local command = line:match"^%w+"; command = munin_commands[command]; if not command then conn:write("# Unknown command.\n"); return; end local ok, err = pcall(command, conn, line); if not ok then module:log("error", "Error running %q: %s", line, err); conn:close(); end end function munin_listener.ondisconnect() end function munin_commands.cap(conn) conn:write("cap\n"); end function munin_commands.list(conn) conn:write(array(it.keys(data.data)):concat(" ") .. "\n"); end function munin_commands.config(conn, line) -- TODO what exactly? local stat = line:match("%s(%S+)"); if not stat then conn:write("# Unknown service\n.\n"); return end for _, _, k, value in meta:iter(stat, "", nil) do conn:write(s_format("%s %s\n", k, value)); end for _, name, k, value in meta:iter(stat, nil, nil) do if name ~= "" and not ignore_stats:contains(name) then conn:write(s_format("%s.%s %s\n", name, k, value)); end end conn:write(".\n"); end function munin_commands.fetch(conn, line) local stat = line:match("%s(%S+)"); if not stat then conn:write("# Unknown service\n.\n"); return end for _, name, value in data:iter(stat, nil) do if not ignore_stats:contains(name) then conn:write(s_format("%s.value %.12f\n", name, value)); end end conn:write(".\n"); end function munin_commands.quit(conn) conn:close(); end module:hook("stats-updated", function (event) local all_stats, this = event.stats_extra; local host, sect, name, typ, key; for stat, value in pairs(event.changed_stats) do if not ignore_stats:contains(stat) then this = all_stats[stat]; -- module:log("debug", "changed_stats[%q] = %s", stat, tostring(value)); host, sect, name, typ = stat:match("^/([^/]+)/([^/]+)/(.+):(%a+)$"); if host == nil then sect, name, typ, host = stat:match("^([^.]+)%.([^:]+):(%a+)$"); elseif host == "*" then host = nil; end key = clean_fieldname(s_format("%s_%s_%s", host or "global", sect, typ)); if not meta:get(key) then if host then meta:set(key, "", "graph_title", s_format("%s %s on %s", sect, typ, host)); else meta:set(key, "", "graph_title", s_format("Global %s %s", sect, typ, host)); end meta:set(key, "", "graph_vlabel", this and this.units or typ); meta:set(key, "", "graph_category", sect); meta:set(key, name, "label", name); elseif not meta:get(key, name, "label") then meta:set(key, name, "label", name); end data:set(key, name, value); end end end); module:provides("net", { listener = munin_listener; default_mode = "*l"; default_port = 4949; });
mit
Murfalo/game-off-2016
xl/Text.lua
1
1193
local Transformable = require "xl.Transformable" local Scene = require "xl.Scene" -- function which creates a default font local MakeFont = function (size) return love.graphics.newFont(size) end local DEFAULT_FONT = MakeFont(12) local WHITE = {255,255,255} local Text = Class.create("Text", Transformable, { __lt = Scene.lessThan, __le = Scene.lessThan, }) function Text:init(msg, x, y, z,camera) self.message = msg self.x = x self.y = y self.z = z self.font = DEFAULT_FONT self.ptsize = 20 self.color = WHITE self.camera = camera or false Transformable.init(self) Scene.makeNode(self) end function Text:setPtsize(size) self.ptsize = size self.font = MakeFont(size) end function Text:setColor( r,g,b,a ) self.color = {r, g , b ,a} end function Text:setPosition( x,y ) self.x = x self.y = y end function Text:draw() love.graphics.setColor(self.color) love.graphics.setFont(self.font) if not self.camera then Game:nocamera(true) end love.graphics.print(self.message, self.x, self.y, self.angle, self.sx, self.sy, self.originx, self.originy) if not self.camera then Game:nocamera(false) end love.graphics.setColor(WHITE) end function Text:update(dt) end return Text
mit
alirezanile/Newsha
plugins/time.lua
94
3004
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run } --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
werpat/MoonGen
rfc2544/utils/ssh.lua
9
3315
local conf = require "config" local ssh = require "utils.ffi.ssh" local mod = {} mod.__index = mod local session = nil function mod.addInterfaceIP(interface, ip, pfx) return mod.exec("ip addr add " .. ip .. "/" .. pfx .. " dev " .. interface) end function mod.delInterfaceIP(interface, ip, pfx) return mod.exec("ip addr del " .. ip .. "/" .. pfx .. " dev " .. interface) end function mod.clearIPFilters() return mod.exec("iptables --flush FORWARD") end function mod.addIPFilter(src, sPfx, dst, dPfx) return mod.exec("iptables -A FORWARD -s " .. src .. "/" .. sPfx .. " -d " .. dst .. "/" .. dPfx .. " -j DROP") end function mod.delIPFilter() return mod.exec("iptables -D FORWARD -s " .. src .. "/" .. sPfx .. " -d " .. dst .. "/" .. dPfx .. " -j DROP") end function mod.clearIPRoutes() return mod.exec("ip route flush table main") end function mod.addIPRoute(dst, pfx, gateway, interface) if gateway and interface then return mod.exec("ip route add " .. dst .. "/" .. pfx .. " via " .. gateway .. " dev " .. interface) elseif gateway then return mod.exec("ip route add " .. dst .. "/" .. pfx .. " via " .. gateway) elseif interface then return mod.exec("ip route add " .. dst .. "/" .. pfx .. " dev " .. interface) else return -1 end end function mod.delIPRoute() if gateway and interface then return mod.exec("ip route del " .. dst .. "/" .. pfx .. " via " .. gateway .. " dev " .. interface) elseif gateway then return mod.exec("ip route del " .. dst .. "/" .. pfx .. " via " .. gateway) elseif interface then return mod.exec("ip route del " .. dst .. "/" .. pfx .. " dev " .. interface) else return -1 end end function mod.getIPRouteCount() local ok, res = mod.exec("ip route show | wc -l") return ok, tonumber(res) end function mod.exec(cmd) local sess, err = mod.getSession() if not sess or err ~= 0 then return -1, err end cmd_res, rc = ssh.request_exec(sess, cmd) if cmd_res == nil then print(rc) return -1, rc end return rc, cmd_res end --[[ function exec(cmd) local sess, err = getSession() if not sess or err ~= 0 then return err end cmd_res = ssh.request_exec(sess, cmd) return tonumber(ssh.request_exec(sess, "echo $?")), cmd_res end --]] function mod.getSession() if not session then print("ssh: establishing new connection") session = ssh.new() if session == nil then return nil, -1 end ssh.set_option(session, "user", conf.getSSHUser()) ssh.set_option(session, "host", conf.getHost()) ssh.set_option(session, "port", conf.getSSHPort()) -- do not ask for checking host signature ssh.set_option(session, "strict_hostkey", false) ssh.connect(session) local ok = ssh.auth_autopubkey(session) if not ok then ok = ssh.auth_password(session, conf.getSSHPass()) end if not ok then return nil, -1 end -- could get banner to guess system -- (Mikrotik) -- ssh.get_issue_banner(session) session = session end return session, 0 end return mod
mit
xinjuncoding/skynet
test/testsocket.lua
80
1078
local skynet = require "skynet" local socket = require "socket" local mode , id = ... local function echo(id) socket.start(id) while true do local str = socket.read(id) if str then socket.write(id, str) else socket.close(id) return end end end if mode == "agent" then id = tonumber(id) skynet.start(function() skynet.fork(function() echo(id) skynet.exit() end) end) else local function accept(id) socket.start(id) socket.write(id, "Hello Skynet\n") skynet.newservice(SERVICE_NAME, "agent", id) -- notice: Some data on this connection(id) may lost before new service start. -- So, be careful when you want to use start / abandon / start . socket.abandon(id) end skynet.start(function() local id = socket.listen("127.0.0.1", 8001) print("Listen socket :", "127.0.0.1", 8001) socket.start(id , function(id, addr) print("connect from " .. addr .. " " .. id) -- you have choices : -- 1. skynet.newservice("testsocket", "agent", id) -- 2. skynet.fork(echo, id) -- 3. accept(id) accept(id) end) end) end
mit
otland/forgottenserver
data/talkactions/scripts/ip_ban.lua
6
1155
local ipBanDays = 7 function onSay(player, words, param) if not player:getGroup():getAccess() then return true end local resultId = db.storeQuery("SELECT `name`, `lastip` FROM `players` WHERE `name` = " .. db.escapeString(param)) if not resultId then return false end local targetName = result.getString(resultId, "name") local targetIp = result.getNumber(resultId, "lastip") result.free(resultId) local targetPlayer = Player(param) if targetPlayer then targetIp = targetPlayer:getIp() targetPlayer:remove() end if targetIp == 0 then return false end resultId = db.storeQuery("SELECT 1 FROM `ip_bans` WHERE `ip` = " .. targetIp) if resultId then player:sendTextMessage(MESSAGE_EVENT_ADVANCE, targetName .. " is already IP banned.") result.free(resultId) return false end local timeNow = os.time() db.query("INSERT INTO `ip_bans` (`ip`, `reason`, `banned_at`, `expires_at`, `banned_by`) VALUES (" .. targetIp .. ", '', " .. timeNow .. ", " .. timeNow + (ipBanDays * 86400) .. ", " .. player:getGuid() .. ")") player:sendTextMessage(MESSAGE_EVENT_ADVANCE, targetName .. " has been IP banned.") return false end
gpl-2.0
cjshmyr/OpenRA
mods/d2k/maps/atreides-02b/atreides02b-AI.lua
4
1137
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } HarkonnenInfantryTypes = { "light_inf" } ActivateAI = function() IdlingUnits[harkonnen] = { } DefendAndRepairBase(harkonnen, HarkonnenBase, 0.75, AttackGroupSize[Difficulty]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local toBuild = function() return HarkonnenInfantryTypes end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 ProduceUnits(harkonnen, HBarracks, delay, toBuild, AttackGroupSize[Difficulty], attackThresholdSize) end
gpl-3.0
sajjad94/ASD_KARBALA
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
3
3275
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: mount.lua 6562 2010-11-27 04:55:38Z jow $ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local has_extroot = fs.access("/lib/preinit/00_extroot.conf") local has_fscheck = fs.access("/lib/functions/fsck.sh") local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/diskapply/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:depends("is_rootfs", "") o = mount:taboption("general", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_extroot then o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"), translate("Configures this mount as overlay storage for block-extroot")) o:depends("fstype", "jffs") o:depends("fstype", "ext2") o:depends("fstype", "ext3") o:depends("fstype", "ext4") end if has_fscheck then o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
gpl-2.0
maanuair/dotfiles_tmp
home/.hammerspoon/init.lua
1
3485
-- Copyright © 2016, 2017, 2018, 2019, 2020, 2021 Emmanuel Roubion -- -- Author: Emmanuel Roubion -- URL: https://github.com/maanuair/dotfiles -- This file is part of Emmanuel's Roubion dot files, released under -- the MIT License as published by the Massachusetts Institute of Technology -- -- These dotfiles are distributed in the hope they wil lbe useful, but -- without any warranty. See the MIT License for more details -- -- You should have received a copy of the MIT License along with this file. -- If not, see https://opensource.org/licenses/mit-license.php -- 8<----- -- Hammerspoon entry point local utils = require('utils') local jira = require('jira') local confluence = require('confluence') local oblique_strategies = require('oblique_strategies') local log = hs.logger.new('init.lua', 'debug') -- Starts fresh hs.console.setConsole() log.i("Fresh Hammerspoon's config loaded !") -- Inits for key bindings... local m1 = {"cmd", "alt", "ctrl"} local m2 = {"cmd", "alt", "ctrl", "shift"} -- m1 Shortcuts hs.hotkey.showHotkeys(m1,"H") hs.hotkey.bind(m1, "A", "Type my address", utils.typeAddress) hs.hotkey.bind(m1, "B", "Browse the highlighted selection", utils.openBrowser) hs.hotkey.bind(m1, "C", "Confluence search the highlighted selection", confluence.search) hs.hotkey.bind(m1, "D", "Define (in Dictionary) the highlighted selection (or ask)", utils.openDict) hs.hotkey.bind(m1, "E", "Type my email", utils.typeEmail) hs.hotkey.bind(m1, "F", "Type my first name", utils.typeFirstName) hs.hotkey.bind(m1, "G", "Google the highlighted selection", utils.googleSelection) hs.hotkey.bind(m1, "I", "Insert current date as YYYY-MM-DD", utils.typeDate) hs.hotkey.bind(m1, "J", "Jira search the highlighted selection", jira.search) hs.hotkey.bind(m1, "L", "Type my lastname", utils.typeLastName) hs.hotkey.bind(m1, "M", "Toggle menubar", utils.toggleMenuBar) hs.hotkey.bind(m1, "N", "New OneNote", utils.newOneNote) hs.hotkey.bind(m1, "T", "Translate with Google the highlighted selection", utils.googleTranslateSelection) hs.hotkey.bind(m1, "O", "Open highlighted Jira issue (or ask)", jira.browseIssue) hs.hotkey.bind(m1, "P", "Type my phone number", utils.typePhoneNumber) hs.hotkey.bind(m1, "Q", "Qwant the highlighted selection", utils.qwantSelection) -- m2 Shortcuts hs.hotkey.bind(m2, "B", "Type a Bug scenario template, in Jira mark-up style", jira.typeBugTemplate) hs.hotkey.bind(m2, "E", "Type my alt. email", utils.typeAltEmail) hs.hotkey.bind(m2, "I", "Insert current timestamp", utils.typeTimestamp) hs.hotkey.bind(m2, "J", "Jira generic URL is typed (highlighted selection appended)", jira.typeBrowseUrl) hs.hotkey.bind(m2, "O", "Oblique Strategy pop-up!", oblique_strategies.showStrategy) hs.hotkey.bind(m2, "S", "Type a Story scenario template, in Jira mark-up style", jira.typeStoryTemplate) -- Timer attempts function remind() hs.notify.new({ title = "Reminder", informativeText = " Remind!\nTTD + PPL + MPC!", }):send() log.df("Sent reminder.") end function remind2() hs.notify.new({ title = "Reminder", informativeText = "Mini break!\n", }):send() log.df("Sent reminder2.") end a = hs.fs.attributes('~/.myTimestamps/hammerspoon.timer') if a == nil then log.df("No timer set.") else hs.hotkey.bind(m1, "R", "Reminder", remind) hs.timer.doEvery(60*15 , remind) hs.hotkey.bind(m2, "R", "Reminder2", remind2) hs.timer.doEvery(60*5+1, remind2) log.df("Reminder timers are set.") remind() remind2() end
mit
vorbi123/larnog
bot/seedbot.lua
24
10036
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" }, sudo_users = {110626080,103649648,111020322,0,tonumber(our_id)},--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
GraphicGame/quick-ejoy2d
examples/test_flash_parser/asset/stand.lua
2
3313
return{ { id = 0, name = "stand9.png", { tex = 1, src = {221, 4, 304, 4, 304, 182, 221, 182, }, screen = {896, 192, 2224, 192, 2224, 3040, 896, 3040, } }, type = "picture", }, { id = 1, name = "stand8.png", { tex = 1, src = {310, 4, 392, 4, 392, 181, 310, 181, }, screen = {912, 192, 2224, 192, 2224, 3024, 912, 3024, } }, type = "picture", }, { id = 2, name = "stand5.png", { tex = 1, src = {807, 4, 882, 4, 882, 179, 807, 179, }, screen = {1024, 224, 2224, 224, 2224, 3024, 1024, 3024, } }, type = "picture", }, { id = 3, name = "stand4.png", { tex = 1, src = {398, 4, 470, 4, 470, 181, 398, 181, }, screen = {1056, 208, 2208, 208, 2208, 3040, 1056, 3040, } }, type = "picture", }, { id = 4, name = "stand7.png", { tex = 1, src = {553, 4, 634, 4, 634, 180, 553, 180, }, screen = {928, 208, 2224, 208, 2224, 3024, 928, 3024, } }, type = "picture", }, { id = 5, name = "stand6.png", { tex = 1, src = {640, 4, 718, 4, 718, 179, 640, 179, }, screen = {976, 224, 2224, 224, 2224, 3024, 976, 3024, } }, type = "picture", }, { id = 6, name = "stand1.png", { tex = 1, src = {4, 4, 129, 4, 129, 186, 4, 186, }, screen = {720, 208, 2720, 208, 2720, 3120, 720, 3120, } }, type = "picture", }, { id = 7, name = "stand3.png", { tex = 1, src = {476, 4, 547, 4, 547, 181, 476, 181, }, screen = {1056, 208, 2192, 208, 2192, 3040, 1056, 3040, } }, type = "picture", }, { id = 8, name = "stand2.png", { tex = 1, src = {135, 4, 215, 4, 215, 184, 135, 184, }, screen = {1008, 144, 2288, 144, 2288, 3024, 1008, 3024, } }, type = "picture", }, { id = 9, name = "stand10.png", { tex = 1, src = {724, 4, 801, 4, 801, 179, 724, 179, }, screen = {992, 224, 2224, 224, 2224, 3024, 992, 3024, } }, type = "picture", }, { id = 10, type = "animation", export = "stand", component = { {id = 6}, {id = 8}, {id = 7}, {id = 3}, {id = 2}, {id = 5}, {id = 4}, {id = 1}, {id = 0}, {id = 9}, }, { {{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 1, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 1, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 2, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 2, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 3, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 3, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 4, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 4, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 5, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 5, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 6, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 6, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 7, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 7, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 8, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 8, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 9, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 9, mat = {1024, 0, 0, 1024, 0, 0}},}, {{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},}, }, }, }
mit
rollokb/tsdemuxer
xupnpd/src/plugins/xupnpd_youtube.lua
4
7798
-- Copyright (C) 2011-2013 Anton Burdinuk -- clark15b@gmail.com -- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd -- 18 - 360p (MP4,h.264/AVC) -- 22 - 720p (MP4,h.264/AVC) hd -- 37 - 1080p (MP4,h.264/AVC) hd -- 82 - 360p (MP4,h.264/AVC) stereo3d -- 83 - 480p (MP4,h.264/AVC) hq stereo3d -- 84 - 720p (MP4,h.264/AVC) hd stereo3d -- 85 - 1080p (MP4,h.264/AVC) hd stereo3d cfg.youtube_fmt=22 cfg.youtube_region='*' cfg.youtube_video_count=100 youtube_api_url='http://gdata.youtube.com/feeds/mobile/' function youtube_find_playlist(user,playlist) if string.sub(playlist,1,3)=='id:' then return string.sub(playlist,4) end local start_index=1 local max_results=50 while(true) do local feed_data=http.download(youtube_api_url..'users/'..user..'/playlists?alt=json&start-index='..start_index..'&max-results='..max_results) if not feed_data then break end local x=json.decode(feed_data) feed_data=nil if not x or not x.feed or not x.feed.entry then break end for i,j in ipairs(x.feed.entry) do if j.title['$t']==playlist then return string.match(j.id['$t'],'.+/([^/]+)$') end end start_index=start_index+max_results end return nil end -- username, favorites/username, playlist/username/playlistname, playlist/username/id:playlistid, channel/channelname, search/searchstring -- channels: top_rated, top_favorites, most_viewed, most_recent, recently_featured function youtube_updatefeed(feed,friendly_name) local rc=false local feed_url=nil local feed_urn=nil local tfeed=split_string(feed,'/') local feed_name='youtube_'..string.lower(string.gsub(feed,"[/ :\'\"]",'_')) if tfeed[1]=='channel' then local region='' if cfg.youtube_region and cfg.youtube_region~='*' then region=cfg.youtube_region..'/' end feed_urn='standardfeeds/'..region..tfeed[2]..'?alt=json' elseif tfeed[1]=='favorites' then feed_urn='users/'..tfeed[2]..'/favorites'..'?alt=json' elseif tfeed[1]=='playlist' then local playlist_id=youtube_find_playlist(tfeed[2],tfeed[3]) if not playlist_id then return false end feed_urn='playlists/'..playlist_id..'?alt=json' elseif tfeed[1]=='search' then feed_urn='videos?vq='..util.urlencode(tfeed[2])..'&alt=json' else feed_urn='users/'..tfeed[1]..'/uploads?orderby=published&alt=json' end local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u' local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u' local dfd=io.open(tmp_m3u_path,'w+') if dfd then dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=youtube\n') local start_index=1 local max_results=50 local count=0 while(count<cfg.youtube_video_count) do local url=youtube_api_url..feed_urn..'&start-index='..start_index..'&max-results='..max_results if cfg.debug>0 then print('YouTube try url '..url) end local feed_data=http.download(url) if not feed_data then break end local x=json.decode(feed_data) feed_data=nil if not x or not x.feed or not x.feed.entry then break end local n=0 for i,j in ipairs(x.feed.entry) do local title=j.title['$t'] local url=nil for ii,jj in ipairs(j.link) do if jj['type']=='text/html' then url=jj.href break end end local logo=nil local thumb=j['media$group']['media$thumbnail'] if thumb and thumb[1] then logo=thumb[1].url end if logo and title and url then dfd:write('#EXTINF:0 logo=',logo,' ,',title,'\n',url,'\n') n=n+1 end end if n<1 then break else count=count+n end start_index=start_index+max_results end dfd:close() if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then if cfg.debug>0 then print('YouTube feed \''..feed_name..'\' updated') end rc=true end else util.unlink(tmp_m3u_path) end end return rc end function youtube_sendurl(youtube_url,range) local url=nil if plugin_sendurl_from_cache(youtube_url,range) then return end url=youtube_get_video_url(youtube_url) if url then if cfg.debug>0 then print('YouTube Real URL: '..url) end plugin_sendurl(youtube_url,url,range) else if cfg.debug>0 then print('YouTube clip is not found') end plugin_sendfile('www/corrupted.mp4') end end function youtube_get_best_fmt(urls,fmt) if fmt>81 and fmt<86 then -- 3d local i=fmt while(i>81) do if urls[i] then return urls[i] end i=i-1 end local t={ [82]=18, [83]=18, [84]=22, [85]=37 } fmt=t[fmt] end local t={ 37,22,18 } local t2={ [18]=true, [22]=true, [37]=true } for i=1,3,1 do local u=urls[ t[i] ] if u and t2[fmt] and t[i]<=fmt then return u end end return urls[18] end function youtube_get_video_url(youtube_url) local url=nil local clip_page=plugin_download(youtube_url) if clip_page then local s=json.decode(string.match(clip_page,'ytplayer.config%s*=%s*({.-});')) clip_page=nil local stream_map=nil -- s.args.adaptive_fmts -- itag 137: 1080p -- itag 136: 720p -- itag 135: 480p -- itag 134: 360p -- itag 133: 240p -- itag 160: 144 -- local player_url=nil if s.assets then player_url=s.assets.js end if player_url and string.sub(player_url,1,2)=='//' then player_url='http:'..player_url end if s.args then stream_map=s.args.url_encoded_fmt_stream_map end local fmt=string.match(youtube_url,'&fmt=(%w+)$') if not fmt then fmt=cfg.youtube_fmt end if stream_map then local urls={} for i in string.gmatch(stream_map,'([^,]+)') do local item={} for j in string.gmatch(i,'([^&]+)') do local name,value=string.match(j,'(%w+)=(.+)') if name then --print(name,util.urldecode(value)) item[name]=util.urldecode(value) end end local sig=item['sig'] or item['s'] local u=item['url'] if sig then u=u..'&signature='..sig end --print(item['itag'],u) urls[tonumber(item['itag'])]=u --print('\n') end url=youtube_get_best_fmt(urls,tonumber(fmt)) end return url else if cfg.debug>0 then print('YouTube clip is not found') end return nil end end plugins['youtube']={} plugins.youtube.name="YouTube" plugins.youtube.desc="<i>username</i>, favorites/<i>username</i>, playlist/<i>username</i>/<i>playlistname</i>, playlist/<i>username</i>/id:<i>playlistid</i>, channel/<i>channelname</i>, search/<i>search_string</i>".. "<br/><b>YouTube channels</b>: top_rated, top_favorites, most_viewed, most_recent, recently_featured" plugins.youtube.sendurl=youtube_sendurl plugins.youtube.updatefeed=youtube_updatefeed plugins.youtube.getvideourl=youtube_get_video_url plugins.youtube.ui_config_vars= { { "select", "youtube_fmt", "int" }, { "select", "youtube_region" }, { "input", "youtube_video_count", "int" } } --youtube_updatefeed('channel/top_rated','')
mit
jp9000/obs-studio
UI/frontend-plugins/frontend-tools/data/scripts/instant-replay.lua
23
5385
obs = obslua source_name = "" hotkey_id = obs.OBS_INVALID_HOTKEY_ID attempts = 0 last_replay = "" ---------------------------------------------------------- function try_play() local replay_buffer = obs.obs_frontend_get_replay_buffer_output() if replay_buffer == nil then obs.remove_current_callback() return end -- Call the procedure of the replay buffer named "get_last_replay" to -- get the last replay created by the replay buffer local cd = obs.calldata_create() local ph = obs.obs_output_get_proc_handler(replay_buffer) obs.proc_handler_call(ph, "get_last_replay", cd) local path = obs.calldata_string(cd, "path") obs.calldata_destroy(cd) obs.obs_output_release(replay_buffer) if path == last_replay then path = nil end -- If the path is valid and the source exists, update it with the -- replay file to play back the replay. Otherwise, stop attempting to -- replay after 10 retries if path == nil then attempts = attempts + 1 if attempts >= 10 then obs.remove_current_callback() end else last_replay = path local source = obs.obs_get_source_by_name(source_name) if source ~= nil then local settings = obs.obs_data_create() source_id = obs.obs_source_get_id(source) if source_id == "ffmpeg_source" then obs.obs_data_set_string(settings, "local_file", path) obs.obs_data_set_bool(settings, "is_local_file", true) -- updating will automatically cause the source to -- refresh if the source is currently active obs.obs_source_update(source, settings) elseif source_id == "vlc_source" then -- "playlist" array = obs.obs_data_array_create() item = obs.obs_data_create() obs.obs_data_set_string(item, "value", path) obs.obs_data_array_push_back(array, item) obs.obs_data_set_array(settings, "playlist", array) -- updating will automatically cause the source to -- refresh if the source is currently active obs.obs_source_update(source, settings) obs.obs_data_release(item) obs.obs_data_array_release(array) end obs.obs_data_release(settings) obs.obs_source_release(source) end obs.remove_current_callback() end end -- The "Instant Replay" hotkey callback function instant_replay(pressed) if not pressed then return end local replay_buffer = obs.obs_frontend_get_replay_buffer_output() if replay_buffer ~= nil then -- Call the procedure of the replay buffer named "get_last_replay" to -- get the last replay created by the replay buffer local ph = obs.obs_output_get_proc_handler(replay_buffer) obs.proc_handler_call(ph, "save", nil) -- Set a 2-second timer to attempt playback every 1 second -- until the replay is available if obs.obs_output_active(replay_buffer) then attempts = 0 obs.timer_add(try_play, 2000) else obs.script_log(obs.LOG_WARNING, "Tried to save an instant replay, but the replay buffer is not active!") end obs.obs_output_release(replay_buffer) else obs.script_log(obs.LOG_WARNING, "Tried to save an instant replay, but found no active replay buffer!") end end ---------------------------------------------------------- -- A function named script_update will be called when settings are changed function script_update(settings) source_name = obs.obs_data_get_string(settings, "source") end -- A function named script_description returns the description shown to -- the user function script_description() return "When the \"Instant Replay\" hotkey is triggered, saves a replay with the replay buffer, and then plays it in a media source as soon as the replay is ready. Requires an active replay buffer.\n\nMade by Jim and Exeldro" end -- A function named script_properties defines the properties that the user -- can change for the entire script module itself function script_properties() props = obs.obs_properties_create() local p = obs.obs_properties_add_list(props, "source", "Media Source", obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING) local sources = obs.obs_enum_sources() if sources ~= nil then for _, source in ipairs(sources) do source_id = obs.obs_source_get_id(source) if source_id == "ffmpeg_source" then local name = obs.obs_source_get_name(source) obs.obs_property_list_add_string(p, name, name) elseif source_id == "vlc_source" then local name = obs.obs_source_get_name(source) obs.obs_property_list_add_string(p, name, name) else -- obs.script_log(obs.LOG_INFO, source_id) end end end obs.source_list_release(sources) return props end -- A function named script_load will be called on startup function script_load(settings) hotkey_id = obs.obs_hotkey_register_frontend("instant_replay.trigger", "Instant Replay", instant_replay) local hotkey_save_array = obs.obs_data_get_array(settings, "instant_replay.trigger") obs.obs_hotkey_load(hotkey_id, hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end -- A function named script_save will be called when the script is saved -- -- NOTE: This function is usually used for saving extra data (such as in this -- case, a hotkey's save data). Settings set via the properties are saved -- automatically. function script_save(settings) local hotkey_save_array = obs.obs_hotkey_save(hotkey_id) obs.obs_data_set_array(settings, "instant_replay.trigger", hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end
gpl-2.0
iamliqiang/prosody-modules
mod_message_logging/mod_message_logging.lua
32
3943
module:set_global(); local jid_bare = require "util.jid".bare; local jid_split = require "util.jid".split; local stat, mkdir = require "lfs".attributes, require "lfs".mkdir; -- Get a filesystem-safe string local function fsencode_char(c) return ("%%%02x"):format(c:byte()); end local function fsencode(s) return (s:gsub("[^%w._-@]", fsencode_char):gsub("^%.", "_")); end local log_base_path = module:get_option("message_logging_dir", prosody.paths.data.."/message_logs"); mkdir(log_base_path); local function get_host_path(host) return log_base_path.."/"..fsencode(host); end local function get_user_path(jid) local username, host = jid_split(jid); local base = get_host_path(host)..os.date("/%Y-%m-%d"); if not stat(base) then mkdir(base); end return base.."/"..fsencode(username)..".msglog"; end local open_files_mt = { __index = function (open_files, jid) local f, err = io.open(get_user_path(jid), "a+"); if not f then module:log("error", "Failed to open message log for writing [%s]: %s", jid, err); end rawset(open_files, jid, f); return f; end }; -- [user@host] = filehandle local open_files = setmetatable({}, open_files_mt); function close_open_files() module:log("debug", "Closing all open files"); for jid, filehandle in pairs(open_files) do filehandle:close(); open_files[jid] = nil; end end module:hook_global("logging-reloaded", close_open_files); local function write_to_log(log_jid, jid, prefix, body) if not body then return; end local f = open_files[log_jid]; if not f then return; end body = body:gsub("\n", "\n "); -- Indent newlines f:write(os.date("%H:%M:%S "), prefix or "", prefix and ": " or "", jid, ": ", body, "\n"); f:flush(); end local function handle_incoming_message(event) local origin, stanza = event.origin, event.stanza; local message_type = stanza.attr.type; if message_type == "error" then return; end local from, to = jid_bare(stanza.attr.from), jid_bare(stanza.attr.to or stanza.attr.from); if message_type == "groupchat" then from = from.." <"..(select(3, jid_split(stanza.attr.from)) or "")..">"; end write_to_log(to, from, "RECV", stanza:get_child_text("body")); end local function handle_outgoing_message(event) local origin, stanza = event.origin, event.stanza; local message_type = stanza.attr.type; if message_type == "error" then return; end local from, to = jid_bare(stanza.attr.from), jid_bare(stanza.attr.to or origin.full_jid); write_to_log(from, to, "SEND", stanza:get_child_text("body")); end local function handle_muc_message(event) local stanza = event.stanza; if stanza.attr.type ~= "groupchat" then return; end local room = event.room or hosts[select(2, jid_split(stanza.attr.to))].modules.muc.rooms[stanza.attr.to]; if not room then return; end local nick = select(3, jid_split(room._jid_nick[stanza.attr.from])); if not nick then return; end write_to_log(room.jid, jid_bare(stanza.attr.from).." <"..nick..">", "MESG", stanza:get_child_text("body")); end function module.add_host(module) local host_base_path = get_host_path(module.host); if not stat(host_base_path) then mkdir(host_base_path); end if hosts[module.host].modules.muc then module:hook("message/bare", handle_muc_message, 1); else module:hook("message/bare", handle_incoming_message, 1); module:hook("message/full", handle_incoming_message, 1); module:hook("pre-message/bare", handle_outgoing_message, 1); module:hook("pre-message/full", handle_outgoing_message, 1); module:hook("pre-message/host", handle_outgoing_message, 1); end end function module.command(arg) local command = table.remove(arg, 1); if command == "path" then print(get_user_path(arg[1])); else io.stderr:write("Unrecognised command: ", command); return 1; end return 0; end function module.save() return { open_files = open_files }; end function module.restore(saved) open_files = setmetatable(saved.open_files or {}, open_files_mt); end
mit
jiankers/Atlas
examples/tutorial-basic.lua
37
1739
--[[ $%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%$ --]] --[[ --]] --- -- read_query() gets the client query before it reaches the server -- -- @param packet the mysql-packet sent by client -- -- the packet contains a command-packet: -- * the first byte the type (e.g. proxy.COM_QUERY) -- * the argument of the command -- -- http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Command_Packet -- -- for a COM_QUERY it is the query itself in plain-text -- function read_query( packet ) print("read hello world") if string.byte(packet) == proxy.COM_QUERY then print("we got a normal query: " .. string.sub(packet, 2)) end print("default_charset is: " .. proxy.connection.client.default_charset) proxy.queries:append(1, packet, { resultset_is_needed = true}) return proxy.PROXY_SEND_QUERY end function read_query_result( inj ) print("hellowrold!!") print("client charset is: " .. proxy.connection.client.default_charset) print("server charset is: " .. proxy.connection.server.default_charset) end
gpl-2.0