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
lcheylus/haka
sample/ruleset/http/security.lua
3
1067
------------------------------------ -- HTTP Attacks ------------------------------------ -- detect malicious web scanners haka.rule { hook = http.events.request, eval = function (http, request) --user-agent patterns of known web scanners local http_useragent = { nikto = '.+%(Nikto%/.+%)%s%(Evasions:.+%)%s%(Test:.+%)', nessus = '^Nessus.*', w3af = '*.%s;w3af.sf.net%)', sqlmap = '^sqlmap%/.*%s%(http:%/%/sqlmap.*%)', fimap = '^fimap%.googlecode%.%com.*', grabber = '^Grabber.*' } if request.headers['User-Agent'] then local user_agent = request.headers['User-Agent'] for scanner, pattern in pairs(http_useragent) do if user_agent:match(pattern) then haka.alert{ description = string.format("'%s' scan detected", scanner), severity = 'high', sources = haka.alert.address(http.flow.srcip), targets = { haka.alert.address(http.flow.dstip), haka.alert.service(string.format("tcp/%d", http.flow.dstport), "http") }, } http:drop() return end end end end }
mpl-2.0
krstal/CrYsTaL
plugins/set.lua
4
1060
local function save_value(msg, name, value) if (not name or not value) then return "Usage: !set var_name value" end local hash = nil if msg.to.type == 'chat' or msg.to.type == 'channel' then hash = 'chat:'..msg.to.id..':variables' end if hash then redis:hset(hash, name, value) return "Saved "..name end end local function run(msg, matches) if not is_momod(msg) then return "For moderators only!" end local name = string.sub(matches[1], 1, 50) local value = string.sub(matches[2], 1, 1000) local name1 = user_print_name(msg.from) savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value ) local text = save_value(msg, name, value) return text end return { patterns = { "^[#!/]save ([^%s]+) (.+)$" }, run = run } --[[ تم التعطيل والتعريب بواسطه @xXxDev_iqxXx _____ _ | ___|_ _ ___ __| | ___ _ __ | |_ / _` |/ _ \/ _` |/ _ \ '__| | _| (_| | __/ (_| | __/ | |_| \__,_|\___|\__,_|\___|_| --]]
gpl-2.0
shwsun/yavc
lua/plugin-list.lua
1
4960
local cmd = vim.cmd cmd("packadd packer.nvim") local present, packer = pcall(require, "packer") if not present then local packer_path = vim.fn.stdpath("data") .. "/site/pack/packer/opt/packer.nvim" print("Cloning packer..") -- remove the dir before cloning vim.fn.delete(packer_path, "rf") vim.fn.system({"git", "clone", "https://github.com/wbthomason/packer.nvim", "--depth", "20", packer_path}) cmd("packadd packer.nvim") present, packer = pcall(require, "packer") if present then print("Packer cloned successfully.") else error("Couldn't clone packer !\nPacker path: " .. packer_path .. "\n" .. packer) end end packer.init({ display = {open_fn = function() return require("packer.util").float({border = "single"}) end, prompt_border = "single"}, git = { clone_timeout = 600 -- Timeout, in seconds, for git clones }, auto_clean = true, compile_on_sync = true -- auto_reload_compiled = true }) require("packer").startup(function(use) use("wbthomason/packer.nvim") -- VIM enhancements use({"tpope/vim-dispatch", opt = true, cmd = {'Dispatch', 'Make', 'Focus', 'Start'}}) use("tpope/vim-fugitive") use("tpope/vim-sleuth") -- Auto configure indentation use("tpope/vim-surround") use("gpanders/editorconfig.nvim") use({'numToStr/Comment.nvim', config = function() require('Comment').setup() end}) -- GUI enhancements use("machakann/vim-highlightedyank") -- highlight yank use("jaxbot/semantic-highlight.vim") -- different color for every variable use("ntpeters/vim-better-whitespace") use("p00f/nvim-ts-rainbow") use("lukas-reineke/indent-blankline.nvim") -- use({'wfxr/minimap.vim', run = ':!cargo install --locked code-minimap'}) use({"tomasiser/vim-code-dark"}) use({'nvim-lualine/lualine.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true}}) use({'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}, config = function() require('gitsigns').setup() end}) -- nvim tools use({'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'}) use("rhysd/committia.vim") -- better git commit layout -- use("kdheepak/lazygit.nvim") use("windwp/nvim-autopairs") use("folke/which-key.nvim") -- use({ 'ibhagwan/fzf-lua', -- requires = { 'kyazdani42/nvim-web-devicons' } -- }) -- use({ 'junegunn/fzf.vim', -- requires = { 'airblade/vim-rooter' }, -- { 'junegunn/fzf', run = './install --bin', } -- }) use {'nvim-telescope/telescope.nvim', requires = {{'nvim-lua/plenary.nvim'}}} -- use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } use {'nvim-telescope/telescope-fzy-native.nvim'} use {'RRethy/nvim-align'} -- LSP support use("neovim/nvim-lspconfig") use("williamboman/nvim-lsp-installer") -- LSP utils use("nvim-lua/lsp_extensions.nvim") -- info and inlay hints use("ray-x/lsp_signature.nvim") -- function signatures use("j-hui/fidget.nvim") -- status use("jose-elias-alvarez/null-ls.nvim") -- enable non-lsp things -- Coq use({"ms-jpq/coq_nvim", branch = "coq", requires = {{"ms-jpq/coq.artifacts", branch = "artifacts"}, {"ms-jpq/coq.thirdparty", branch = "3p"}}}) use("folke/lua-dev.nvim") -- Language support use({"stephpy/vim-yaml", ft = 'yaml', opt = true}) use({"cespare/vim-toml", ft = 'toml', opt = true}) use({"dag/vim-fish", ft = 'fish', opt = true}) use({'nvim-orgmode/orgmode', config = function() require('orgmode').setup {} end}) use({"plasticboy/vim-markdown", ft = 'markdown', opt = true}) use({"mzlogin/vim-markdown-toc", ft = 'markdown', opt = true}) use("alvan/vim-closetag") -- Rust -- use("rust-lang/rust.vim") use("simrat39/rust-tools.nvim") -- C++ and Clang -- use("octol/vim-cpp-enhanced-highlight', {'for': ['cpp'] } -- use("drmikehenry/vim-headerguard', {'for': ['cpp', 'hpp'] } -- use("bfrg/vim-cpp-modern', {'for': ['cpp', 'hpp'] } -- use("arakashic/chromatica.nvim', {'for': ['cpp', 'hpp'] } -- use("rhysd/vim-clang-format', {'for': ['c', 'cpp', 'hpp'] } -- SQL use {"tami5/sql.nvim", rocks = {"sqlite", "luv"}} use "tpope/vim-dadbod" use {"kristijanhusak/vim-dadbod-completion"} use {"kristijanhusak/vim-dadbod-ui"} -- Grammars -- local_use "tree-sitter-lua" -- use { "m-novikov/tree-sitter-sql" } -- use { "DerekStride/tree-sitter-sql" } -- local_use "tree-sitter-sql" -- LaTeX -- https://www.reddit.com/r/neovim/comments/idthcb/vimtex_vs_texlab/ -- use({"lervag/vimtex", ft = {'tex', 'latex'}}) -- use({"rhysd/vim-grammarous", ft = {'tex', 'latex', 'markdown'}}) -- use({"brymer-meneses/grammar-guard.nvim", requires = {"neovim/nvim-lspconfig", "williamboman/nvim-lsp-installer"}}) -- unsure -- use({"folke/trouble.nvim", requires = "kyazdani42/nvim-web-devicons"}) end)
mit
vzaramel/kong
spec/plugins/mashape-analytics/buffer_spec.lua
2
3814
require "kong.tools.ngx_stub" local ALFBuffer = require "kong.plugins.mashape-analytics.buffer" local json = require "cjson" local ALF_STUB = {hello = "world"} local CONF_STUB = { batch_size = 100, delay = 2 } local str = json.encode(ALF_STUB) local STUB_LEN = string.len(str) describe("ALFBuffer", function() local alf_buffer it("should create a new buffer", function() alf_buffer = ALFBuffer.new(CONF_STUB) assert.truthy(alf_buffer) assert.equal(100, alf_buffer.MAX_ENTRIES) assert.equal(2, alf_buffer.AUTO_FLUSH_DELAY) end) describe(":add_alf()", function() it("should be possible to add an ALF to it", function() local buffer = ALFBuffer.new(CONF_STUB) buffer:add_alf(ALF_STUB) assert.equal(1, #buffer.entries) end) it("should compute and update the current buffer size in bytes", function() alf_buffer:add_alf(ALF_STUB) assert.equal(STUB_LEN, alf_buffer.entries_size) -- Add 50 objects for i = 1, 50 do alf_buffer:add_alf(ALF_STUB) end assert.equal(51 * STUB_LEN, alf_buffer.entries_size) end) describe(":get_size()", function() it("should return the hypothetical size of what the payload should be", function() local comma_size = string.len(",") local total_comma_size = 50 * comma_size -- 51 - 1 commas local braces_size = string.len("[]") local entries_size = alf_buffer.entries_size assert.equal(entries_size + total_comma_size + braces_size, alf_buffer:get_size()) end) end) it("should call :flush() when reaching its n entries limit", function() local s = spy.on(alf_buffer, "flush") -- Add 49 more entries for i = 1, 49 do alf_buffer:add_alf(ALF_STUB) end assert.spy(s).was_not.called() -- One more to go over the limit alf_buffer:add_alf(ALF_STUB) assert.spy(s).was.called() finally(function() alf_buffer.flush:revert() end) end) it("should call :flush() when reaching its max size", function() -- How many stubs to reach the limit? local COMMA_LEN = string.len(",") local JSON_ARR_LEN = string.len("[]") local max_n_stubs = math.ceil(ALFBuffer.MAX_BUFFER_SIZE / (STUB_LEN + COMMA_LEN)) -- + the comma after each ALF in the JSON payload -- Create a new buffer local buffer = ALFBuffer.new({batch_size = max_n_stubs + 100, delay = 2}) local s = spy.on(buffer, "flush") -- Add max_n_stubs - 1 entries for i = 1, max_n_stubs - 1 do buffer:add_alf(ALF_STUB) end assert.spy(s).was_not_called() -- We should have `(max_n_stubs - 1) * (STUB_LEN + COMMA_LEN) + JSON_ARR_LEN - COMMA_LEN` because no comma for latest object` -- as our current buffer size. assert.equal((max_n_stubs - 1) * (STUB_LEN + COMMA_LEN) + JSON_ARR_LEN - COMMA_LEN, buffer:get_size()) -- adding one more entry buffer:add_alf(ALF_STUB) assert.spy(s).was.called() end) it("should drop an ALF if it is too big by itself", function() local str = string.rep(".", ALFBuffer.MAX_BUFFER_SIZE) local huge_alf = {foo = str} local buffer = ALFBuffer.new(CONF_STUB) buffer:add_alf(huge_alf) assert.equal(0, buffer.entries_size) assert.equal(0, #buffer.entries) end) describe(":flush()", function() it("should have emptied the current buffer and added a payload to be sent", function() assert.equal(1, #alf_buffer.entries) assert.equal(1, #alf_buffer.sending_queue) assert.equal("table", type(alf_buffer.sending_queue[1])) assert.equal("string", type(alf_buffer.sending_queue[1].payload)) assert.equal(STUB_LEN, alf_buffer.entries_size) end) end) end) end)
apache-2.0
vzaramel/kong
kong/plugins/request-transformer/access.lua
2
4046
local utils = require "kong.tools.utils" local stringy = require "stringy" local Multipart = require "multipart" local _M = {} local CONTENT_LENGTH = "content-length" local FORM_URLENCODED = "application/x-www-form-urlencoded" local MULTIPART_DATA = "multipart/form-data" local CONTENT_TYPE = "content-type" local HOST = "host" local function iterate_and_exec(val, cb) if utils.table_size(val) > 0 then for _, entry in ipairs(val) do local parts = stringy.split(entry, ":") cb(parts[1], utils.table_size(parts) == 2 and parts[2] or nil) end end end local function get_content_type() local header_value = ngx.req.get_headers()[CONTENT_TYPE] if header_value then return stringy.strip(header_value):lower() end end function _M.execute(conf) if conf.add then -- Add headers if conf.add.headers then iterate_and_exec(conf.add.headers, function(name, value) ngx.req.set_header(name, value) if name:lower() == HOST then -- Host header has a special treatment ngx.var.backend_host = value end end) end -- Add Querystring if conf.add.querystring then local querystring = ngx.req.get_uri_args() iterate_and_exec(conf.add.querystring, function(name, value) querystring[name] = value end) ngx.req.set_uri_args(querystring) end if conf.add.form then local content_type = get_content_type() if content_type and stringy.startswith(content_type, FORM_URLENCODED) then -- Call ngx.req.read_body to read the request body first ngx.req.read_body() local parameters = ngx.req.get_post_args() iterate_and_exec(conf.add.form, function(name, value) parameters[name] = value end) local encoded_args = ngx.encode_args(parameters) ngx.req.set_header(CONTENT_LENGTH, string.len(encoded_args)) ngx.req.set_body_data(encoded_args) elseif content_type and stringy.startswith(content_type, MULTIPART_DATA) then -- Call ngx.req.read_body to read the request body first ngx.req.read_body() local body = ngx.req.get_body_data() local parameters = Multipart(body and body or "", content_type) iterate_and_exec(conf.add.form, function(name, value) parameters:set_simple(name, value) end) local new_data = parameters:tostring() ngx.req.set_header(CONTENT_LENGTH, string.len(new_data)) ngx.req.set_body_data(new_data) end end end if conf.remove then -- Remove headers if conf.remove.headers then iterate_and_exec(conf.remove.headers, function(name, value) ngx.req.clear_header(name) end) end if conf.remove.querystring then local querystring = ngx.req.get_uri_args() iterate_and_exec(conf.remove.querystring, function(name) querystring[name] = nil end) ngx.req.set_uri_args(querystring) end if conf.remove.form then local content_type = get_content_type() if content_type and stringy.startswith(content_type, FORM_URLENCODED) then local parameters = ngx.req.get_post_args() iterate_and_exec(conf.remove.form, function(name) parameters[name] = nil end) local encoded_args = ngx.encode_args(parameters) ngx.req.set_header(CONTENT_LENGTH, string.len(encoded_args)) ngx.req.set_body_data(encoded_args) elseif content_type and stringy.startswith(content_type, MULTIPART_DATA) then -- Call ngx.req.read_body to read the request body first ngx.req.read_body() local body = ngx.req.get_body_data() local parameters = Multipart(body and body or "", content_type) iterate_and_exec(conf.remove.form, function(name) parameters:delete(name) end) local new_data = parameters:tostring() ngx.req.set_header(CONTENT_LENGTH, string.len(new_data)) ngx.req.set_body_data(new_data) end end end end return _M
apache-2.0
GraphicGame/quick-ejoy2d
quick/demos/kofanim/src/kofanim.lua
2
1907
local ej = require "ejoy2d" local Stage = require "quick.lua.Stage" local Layer = require "quick.lua.Layer" local Sprite = require "quick.lua.Sprite" local Resources = require "quick.lua.Resources" local Screen = require "quick.lua.Screen" --舞台 local _stage --背景层 local _layerBackground --精灵层 local _layerSprites --- ---初始化舞台 --- local function initStage() --创建舞台,舞台是全局唯一的. _stage = Stage.getStage() --屏幕适配,通过缩放舞台来达到屏幕适配的目的。 _stage.scale = Screen.width / 960 --创建两个层次,一个是背景层,一个是精灵层. _layerBackground = Layer.createLayer() _layerSprites = Layer.createLayer() --将两个层次按照顺序放到舞台上 _stage:addLayer(_layerBackground) _stage:addLayer(_layerSprites) end local _spriteList = {} --精灵列表 local _soulHero --主角:魂! --- ---初始化精灵 --- local function initSprites() --初始化背景 local background = Sprite.createSprite("background", "background") _layerBackground:addSprite(background) --初始化精灵 local robert = Sprite.createSprite("robert", "robert") _layerSprites:addSprite(robert) table.insert(_spriteList, robert) robert.x = 100 robert.y = 460 robert.actionName = "stand" end --- ---初始化游戏 --- local function initGame() initStage() --初始化舞台 initSprites() --初始化精灵 end -- --游戏的框架(用的是ejoy2d的原生设计) -- local game = {} function game.update() --精灵动画 for i = 1, #_spriteList do (_spriteList[i]):nextFrame() end end function game.drawframe() --绘制舞台(含舞台中的所有对象) _stage:clearCanvas(0) _stage:draw() end function game.touch(what, x, y) end function game.message(...) end function game.handle_error(...) end function game.on_resume() end function game.on_pause() end initGame() ej.start(game)
mit
m-creations/openwrt
feeds/luci/modules/luci-mod-admin-mini/luasrc/model/cbi/mini/wifi.lua
48
11450
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } 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") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid 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") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower 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 -- WLAN-Scan-Table -- 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) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end 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 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")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
gpl-2.0
zhaohao/waifu2x
lib/image_loader.lua
32
2887
local gm = require 'graphicsmagick' local ffi = require 'ffi' require 'pl' local image_loader = {} function image_loader.decode_float(blob) local im, alpha = image_loader.decode_byte(blob) if im then im = im:float():div(255) end return im, alpha end function image_loader.encode_png(rgb, alpha) if rgb:type() == "torch.ByteTensor" then error("expect FloatTensor") end if alpha then if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "Sinc"):toTensor("float", "I", "DHW") end local rgba = torch.Tensor(4, rgb:size(2), rgb:size(3)) rgba[1]:copy(rgb[1]) rgba[2]:copy(rgb[2]) rgba[3]:copy(rgb[3]) rgba[4]:copy(alpha) local im = gm.Image():fromTensor(rgba, "RGBA", "DHW") im:format("png") return im:toBlob(9) else local im = gm.Image(rgb, "RGB", "DHW") im:format("png") return im:toBlob(9) end end function image_loader.save_png(filename, rgb, alpha) local blob, len = image_loader.encode_png(rgb, alpha) local fp = io.open(filename, "wb") fp:write(ffi.string(blob, len)) fp:close() return true end function image_loader.decode_byte(blob) local load_image = function() local im = gm.Image() local alpha = nil im:fromBlob(blob, #blob) -- FIXME: How to detect that a image has an alpha channel? if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then -- split alpha channel im = im:toTensor('float', 'RGBA', 'DHW') local sum_alpha = (im[4] - 1):sum() if sum_alpha > 0 or sum_alpha < 0 then alpha = im[4]:reshape(1, im:size(2), im:size(3)) end local new_im = torch.FloatTensor(3, im:size(2), im:size(3)) new_im[1]:copy(im[1]) new_im[2]:copy(im[2]) new_im[3]:copy(im[3]) im = new_im:mul(255):byte() else im = im:toTensor('byte', 'RGB', 'DHW') end return {im, alpha} end local state, ret = pcall(load_image) if state then return ret[1], ret[2] else return nil end end function image_loader.load_float(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_float(buff) end function image_loader.load_byte(file) local fp = io.open(file, "rb") if not fp then error(file .. ": failed to load image") end local buff = fp:read("*a") fp:close() return image_loader.decode_byte(buff) end local function test() require 'image' local img img = image_loader.load_float("./a.jpg") if img then print(img:min()) print(img:max()) image.display(img) end img = image_loader.load_float("./b.png") if img then image.display(img) end end --test() return image_loader
mit
mamaddeveloper/outo
plugins/hearthstone.lua
7
2109
-- Plugin for the Hearthstone database provided by hearthstonejson.com. if not hs_dat then hs_dat = {} local jstr, res = HTTPS.request('http://hearthstonejson.com/json/AllSets.json') if res ~= 200 then print('Error connecting to hearthstonejson.com.') print('hearthstone.lua will not be enabled.') end local jdat = JSON.decode(jstr) for k,v in pairs(jdat) do for key,val in pairs(v) do table.insert(hs_dat, val) end end end local doc = [[ /hearthstone <query> Returns Hearthstone card info. ]] local triggers = { '^/h[earth]*s[tone]*[@'..bot.username..']*' } local format_card = function(card) local ctype = card.type if card.race then ctype = card.race end if card.rarity then ctype = card.rarity .. ' ' .. ctype end if card.playerClass then ctype = ctype .. ' (' .. card.playerClass .. ')' elseif card.faction then ctype = ctype .. ' (' .. card.faction .. ')' end local stats if card.cost then stats = card.cost .. 'c' if card.attack then stats = stats .. ' | ' .. card.attack .. 'a' end if card.health then stats = stats .. ' | ' .. card.health .. 'h' end if card.durability then stats = stats .. ' | ' .. card.durability .. 'd' end elseif card.health then stats = card.health .. 'h' end local info = '' if card.text then info = card.text:gsub('</?.->',''):gsub('%$','') if card.flavor then info = info .. '\n' .. card.flavor end elseif card.flavor then info = card.flavor else info = nil end local s = card.name .. '\n' .. ctype if stats then s = s .. '\n' .. stats end if info then s = s .. '\n' .. info end return s end local action = function(msg) local input = msg.text_lower:input() if not input then sendReply(msg, doc) return end local output = '' for k,v in pairs(hs_dat) do if string.lower(v.name):match(input) then output = output .. format_card(v) .. '\n\n' end end output = output:trim() if output:len() == 0 then sendReply(msg, config.errors.results) return end sendReply(msg, output) end return { action = action, triggers = triggers, doc = doc }
gpl-2.0
Eugene-Ye/fanclub
app/libs/db.lua
1
3052
local sgsub = string.gsub local tinsert = table.insert local type = type local ipairs = ipairs local pairs = pairs local mysql = require("resty.mysql") local cjson = require("cjson") local utils = require("app.libs.utils") local config = require("app.config.config") local DB = {} function DB:new(conf) conf = conf or config.mysql local instance = {} instance.conf = conf setmetatable(instance, { __index = self}) return instance end function DB:exec(sql) local conf = self.conf local db, err = mysql:new() if not db then ngx.say("failed to instantiate mysql: ", err) return end db:set_timeout(conf.timeout) -- 1 sec local ok, err, errno, sqlstate = db:connect(conf.connect_config) if not ok then ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate) return end --ngx.log(ngx.ERR, "connected to mysql, reused_times:", db:get_reused_times(), " sql:", sql) db:query("SET NAMES utf8") local res, err, errno, sqlstate = db:query(sql) if not res then ngx.log(ngx.ERR, "bad result: ", err, ": ", errno, ": ", sqlstate, ".") end local ok, err = db:set_keepalive(conf.pool_config.max_idle_timeout, conf.pool_config.pool_size) if not ok then ngx.say("failed to set keepalive: ", err) end return res, err, errno, sqlstate end function DB:query(sql, params) sql = self:parse_sql(sql, params) return self:exec(sql) end function DB:select(sql, params) return self:query(sql, params) end function DB:insert(sql, params) local res, err, errno, sqlstate = self:query(sql, params) if res and not err then return res.insert_id, err else return res, err end end function DB:update(sql, params) return self:query(sql, params) end function DB:delete(sql, params) local res, err, errno, sqlstate = self:query(sql, params) if res and not err then return res.affected_rows, err else return res, err end end local function split(str, delimiter) if str==nil or str=='' or delimiter==nil then return nil end local result = {} for match in (str..delimiter):gmatch("(.-)"..delimiter) do tinsert(result, match) end return result end local function compose(t, params) if t==nil or params==nil or type(t)~="table" or type(params)~="table" or #t~=#params+1 or #t==0 then return nil else local result = t[1] for i=1, #params do result = result .. params[i].. t[i+1] end return result end end function DB:parse_sql(sql, params) if not params or not utils.table_is_array(params) or #params == 0 then return sql end local new_params = {} for i, v in ipairs(params) do if v and type(v) == "string" then v = ngx.quote_sql_str(v) end tinsert(new_params, v) end local t = split(sql,"?") local sql = compose(t, new_params) return sql end return DB
mit
deepak78/new-luci
build/luadoc/luadoc/init.lua
172
1333
------------------------------------------------------------------------------- -- LuaDoc main function. -- @release $Id: init.lua,v 1.4 2008/02/17 06:42:51 jasonsantos Exp $ ------------------------------------------------------------------------------- local require = require local util = require "luadoc.util" logger = {} module ("luadoc") ------------------------------------------------------------------------------- -- LuaDoc version number. _COPYRIGHT = "Copyright (c) 2003-2007 The Kepler Project" _DESCRIPTION = "Documentation Generator Tool for the Lua language" _VERSION = "LuaDoc 3.0.1" ------------------------------------------------------------------------------- -- Main function -- @see luadoc.doclet.html, luadoc.doclet.formatter, luadoc.doclet.raw -- @see luadoc.taglet.standard function main (files, options) logger = util.loadlogengine(options) -- load config file if options.config ~= nil then -- load specified config file dofile(options.config) else -- load default config file require("luadoc.config") end local taglet = require(options.taglet) local doclet = require(options.doclet) -- analyze input taglet.options = options taglet.logger = logger local doc = taglet.start(files) -- generate output doclet.options = options doclet.logger = logger doclet.start(doc) end
apache-2.0
BytewaveMLP/SteamGroupRewardsFramework
lua/sgrf/config.lua
1
1897
--[[------------------------- GENERAL SETTINGS General configuration options. --------------------------]]-- SGRF.Config = SGRF.Config or {} -- DO NOT TOUCH ME --- Commands to open the Steam group page -- These commands may be used in chat to open the Steam group page for the group designated -- below. The addon will check if a player has joined the group upon re-entering the game, and -- will reward them accordingly. SGRF.Config.Commands = { '!steamgroup', '/steamgroup', '!sg', '/sg', } --- The group ID to check -- This is your group's ID. You can find this on your group's profile edit page, after the "ID:" -- label. SGRF.Config.SteamGroup = 'CHANGE ME' --- Your Steam Web API key -- You can get this at https://steamcommunity.com/dev/apikey. SGRF.Config.SteamAPIKey = 'CHANGE ME' --- Should DEBUG-level log messages be printed? -- You should really only set this to true if asked to by the developers. This will cause a lot of -- console spam. SGRF.Config.LogDebugMessages = false --[[------------------------- REWARDS SETTINGS Add your custom rewards here! -------------------------]]-- SGRF.Rewards = SGRF.Rewards or {} -- DO NOT TOUCH ME -- Add your custom rewards here! -- To grant rewards outside of those available in callbacks, eg PAC3 access or hook-related rewards, -- use the helper function SGRF.IsPlayerInGroup(ply) documented below. -- Alternatively, you may use the PData variable SGRF_InSteamGroup. NOTE, however, that Player:GetPData -- (annoyingly) returns strings, so you will have to check if the returned value equals the STRING 'true' -- if the player is in the group or the STRING 'false' if the player is not in the group. -- TO ADD NEW REWARDS, use the template below. --[===[ SGRF.Rewards.Name = { OneTime = true, Recurring = true, Callback = function(ply) end, } ]===]--
gpl-3.0
ziz/solarus
quests/zsxd/data/maps/map0065.lua
1
7175
-- Temple of Stupidities 1F NE will_remove_water = false function event_map_started(destination_point_name) -- switches of stairs of the central room for i = 1,7 do if not sol.game.savegame_get_boolean(292 + i) then sol.map.stairs_set_enabled("stairs_"..i, false) sol.map.switch_set_activated("stairs_"..i.."_switch", false) else sol.map.switch_set_activated("stairs_"..i.."_switch", true) end end -- room with enemies to fight if sol.game.savegame_get_boolean(301) then sol.map.enemy_remove_group("fight_room") end -- block pushed to remove the water of 2F SW if sol.game.savegame_get_boolean(283) then sol.map.block_set_enabled("remove_water_block", false) else sol.map.block_set_enabled("fake_remove_water_block", false) end -- boss sol.map.door_set_open("boss_door", true) if sol.game.savegame_get_boolean(306) then sol.map.tile_set_enabled("boss_gate", true) end end function event_switch_activated(switch_name) i = string.match(switch_name, "^stairs_\([1-7]\)_switch$") if (i ~= nil) then sol.map.stairs_set_enabled("stairs_"..i, true) sol.main.play_sound("secret") sol.game.savegame_set_boolean(292 + i, true) elseif switch_name == "switch_torch_1_on" then sol.map.tile_set_enabled("torch_1", true) sol.map.switch_set_activated("switch_torch_1_off", false) elseif switch_name == "switch_torch_1_off" then sol.map.tile_set_enabled("torch_1", false) sol.map.switch_set_activated("switch_torch_1_on", false) elseif switch_name == "switch_torch_2_on" then sol.map.tile_set_enabled("torch_2", true) sol.map.switch_set_activated("switch_torch_2_off", false) elseif switch_name == "switch_torch_2_off" then sol.map.tile_set_enabled("torch_2", false) sol.map.switch_set_activated("switch_torch_2_on", false) elseif switch_name == "switch_torch_3_on" then sol.map.tile_set_enabled("torch_3", true) sol.map.switch_set_activated("switch_torch_3_off", false) elseif switch_name == "switch_torch_3_off" then sol.map.tile_set_enabled("torch_3", false) sol.map.switch_set_activated("switch_torch_3_on", false) elseif switch_name == "switch_torch_4_on" then sol.map.tile_set_enabled("torch_4", true) sol.map.switch_set_activated("switch_torch_4_off", false) elseif switch_name == "switch_torch_4_off" then sol.map.tile_set_enabled("torch_4", false) sol.map.switch_set_activated("switch_torch_4_on", false) elseif switch_name == "switch_torch_5_on" then sol.map.tile_set_enabled("torch_5", true) sol.map.switch_set_activated("switch_torch_5_off", false) elseif switch_name == "switch_torch_5_off" then sol.map.tile_set_enabled("torch_5", false) sol.map.switch_set_activated("switch_torch_5_on", false) elseif switch_name == "switch_torch_6_on" then sol.map.tile_set_enabled("torch_6", true) sol.map.switch_set_activated("switch_torch_6_off", false) elseif switch_name == "switch_torch_6_off" then sol.map.tile_set_enabled("torch_6", false) sol.map.switch_set_activated("switch_torch_6_on", false) elseif switch_name == "switch_torch_7_on" then sol.map.tile_set_enabled("torch_7", true) sol.map.switch_set_activated("switch_torch_7_off", false) sol.map.switch_set_activated("switch_torch_7_off_2", false) elseif switch_name == "switch_torch_7_off" or switch_name == "switch_torch_7_off_2" then sol.map.tile_set_enabled("torch_7", false) sol.map.switch_set_activated("switch_torch_7_on", false) elseif switch_name == "switch_torch_8_on" then sol.map.tile_set_enabled("torch_8", true) sol.map.switch_set_activated("switch_torch_8_off", false) elseif switch_name == "switch_torch_8_off" then sol.map.tile_set_enabled("torch_8", false) sol.map.switch_set_activated("switch_torch_8_on", false) elseif switch_name == "switch_torch_9_on" then sol.map.tile_set_enabled("torch_9", true) sol.map.switch_set_activated("switch_torch_9_off", false) elseif switch_name == "switch_torch_9_off" then sol.map.tile_set_enabled("torch_9", false) sol.map.switch_set_activated("switch_torch_9_on", false) elseif switch_name == "switch_torch_10_on" then sol.map.tile_set_enabled("torch_10", true) sol.map.switch_set_activated("switch_torch_10_off", false) elseif switch_name == "switch_torch_10_off" then sol.map.tile_set_enabled("torch_10", false) sol.map.switch_set_activated("switch_torch_10_on", false) elseif switch_name == "switch_torch_11_on" then sol.map.tile_set_enabled("torch_11", true) sol.map.switch_set_activated("switch_torch_11_off", false) elseif switch_name == "switch_torch_11_off" then sol.map.tile_set_enabled("torch_11", false) sol.map.switch_set_activated("switch_torch_11_on", false) end end function event_enemy_dead(enemy_name) if string.match(enemy_name, '^fight_room') and sol.map.enemy_is_group_dead("fight_room") then sol.main.play_sound("secret") sol.map.door_open("fight_room_door") elseif enemy_name == "boss" then sol.map.tile_set_enabled("boss_gate", true) sol.game.savegame_set_boolean(62, true) -- open the door of Link's cave sol.main.play_sound("secret") end end function event_hero_on_sensor(sensor_name) if sensor_name == "remove_water_sensor" and not sol.game.savegame_get_boolean(283) and not will_remove_water then sol.main.timer_start(500, "remove_2f_sw_water", false) will_remove_water = true elseif sensor_name == "start_boss_sensor" then if sol.map.door_is_open("boss_door") and not sol.game.savegame_get_boolean(306) then sol.map.door_close("boss_door") sol.map.hero_freeze() sol.main.timer_start(1000, "start_boss", false) end end end function remove_2f_sw_water() sol.main.play_sound("water_drain_begin") sol.main.play_sound("water_drain") sol.map.dialog_start("dungeon_1.2f_sw_water_removed") sol.game.savegame_set_boolean(283, true) end function start_boss() sol.map.enemy_set_enabled("boss", true) sol.main.play_music("ganon_theme.spc") sol.main.timer_start(1000, "ganon_dialog", false) sol.map.hero_unfreeze() end function ganon_dialog() sol.map.dialog_start("dungeon_1.ganon") end function event_hero_interaction(entity_name) if entity_name == "boss_hint_stone" then sol.main.timer_start(9000, "another_castle", false) sol.main.play_music("victory.spc") sol.map.hero_set_direction(3) sol.map.hero_freeze() end end function another_castle() sol.map.dialog_start("dungeon_1.boss_hint_stone") sol.map.dialog_set_variable("dungeon_1.boss_hint_stone", sol.game.savegame_get_name()) end function event_dialog_finished(first_message_id) if first_message_id == "dungeon_1.boss_hint_stone" then sol.main.timer_start(1000, "victory", false) elseif first_message_id == "dungeon_1.ganon" then sol.main.play_music("ganon_battle.spc") end end function victory() sol.map.hero_start_victory_sequence() sol.main.timer_start(2000, "leave_dungeon", false) end function leave_dungeon() sol.main.play_sound("warp") sol.map.hero_set_map(4, "from_temple_of_stupidities", 1) end
gpl-3.0
hoelzl/Xbt.lua
src/test/test_util.lua
1
4797
--- Tests for the utility functions. -- @copyright 2015, Matthias Hölzl -- @author Matthias Hölzl -- @license MIT, see the file LICENSE.md. local util = require("xbt.util") local lunatest = require("lunatest") local assert_equal = lunatest.assert_equal local assert_not_equal = lunatest.assert_not_equal local assert_error = lunatest.assert_error local assert_false = lunatest.assert_false local assert_not_false = lunatest.assert_not_false local assert_table = lunatest.assert_table local assert_not_table = lunatest.assert_not_table local assert_true = lunatest.assert_true local assert_nil = lunatest.assert_nil local t = {} function t.test_random () for i=1,100 do local r = util.random(20) assert_true(1 <= r) assert_true(r <= 20) end for i=1,100 do local r = util.random(10, 20) assert_true(10 <= r) assert_true(r <= 20) end for i=1,100 do local r = util.random(-10, 20) assert_true(-10 <= r) assert_true(r <= 20) end end function t.test_uuid () -- Only test for the correct pattern. assert_true(string.match( util.uuid(), "%x%x%x%x%x%x%x%x%-%x%x%x%x%-4%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x")) -- Check that freshly generated uuids are distinct assert_not_equal(util.uuid(), util.uuid()) end function t.test_size () assert_equal(util.size({}), 0) assert_equal(util.size({1, 2, 3}), 3) assert_equal(util.size({1, {2}, {1, 2, 3}, 4}), 4) assert_equal(util.size({x = 1, y = "Y"}), 2) end function t.test_equal_1 () assert_true(util.equal(1, 1)) assert_false(util.equal(1, 2)) assert_true(util.equal("foo", "foo")) assert_false(util.equal("foo", "bar")) end function t.test_equal_2 () assert_true(util.equal({}, {}), "Empty tables not equal.") assert_false(util.equal({}, {1}), "Empty table equal to array.") assert_false(util.equal({1}, {}), "Array equal to empty table.") assert_false(util.equal({}, {x = "X"}), "Empty table equal to map.") assert_false(util.equal({x = "X"}, {}), "Map equal to empty table.") end function t.test_equal_3 () assert_true(util.equal({1, 2, 3}, {1, 2, 3})) assert_false(util.equal({1, 2, 3}, {1, 2, 3, 4})) assert_false(util.equal({1, 2}, {1, 2, 3})) assert_false(util.equal({1, 2, 3, 4}, {1, 2})) end function t.test_equal_4 () assert_false(util.equal({1, 2, 3}, {1, 3, 2})) assert_false(util.equal({3, 1, 2}, {1, 2, 3})) assert_false(util.equal({1, 2, 3}, {3, 2, 1})) end function t.test_equal_5 () assert_true(util.equal({x="X", y="Y", z="Z"}, {x="X", y="Y", z="Z"})) assert_false(util.equal({x="X", y="Y", z="Z"}, {x="X", y="Y", z="Z", w="W"})) assert_false(util.equal({x="X", y="Y", z="Z"}, {x="X", y="Y"})) assert_false(util.equal({x="X", y="Y", z="Z", w="W"}, {x="X", y="Y", z="Z"})) assert_false(util.equal({x="X", y="Y"}, {x="X", y="Y", z="Z"})) end function t.test_equal_6 () assert_true(util.equal({{1}, {2}, {3}}, {{1}, {2}, {3}})) assert_false(util.equal({{1}, {2}, {3}}, {{1}, {3}, {2}})) end function t.test_addall_1 () local t1 = {} local res = util.addall(t1, {x = "XX", y = "YY"}) assert_table(res) assert_true(util.equal(res, {x = "XX", y = "YY"})) assert_true(util.equal(t1, {x = "XX", y = "YY"})) end function t.test_addall_2 () local t1 = {a = "AA", b = "BB", x = "XX"} local res = util.addall(t1, {x = "xx", y = "YY"}) assert_table(res) assert_true(util.equal(res, {a = "AA", b = "BB", x = "xx", y = "YY"})) assert_true(util.equal(t1, {a = "AA", b = "BB", x = "xx", y = "YY"})) end function t.test_keys () assert_true(util.equal(util.keys({}), {})) assert_true(util.equal(util.keys({10, 20, 30}), {1, 2, 3})) assert_true(util.equal(util.keys({x="X", y="Y"}), {"x", "y"})) end function t.test_append () assert_true(util.equal(util.append({1,2,3}, {}), {1,2,3})) assert_true(util.equal(util.append({}, {1,2,3}), {1,2,3})) assert_true(util.equal(util.append({1,2,3}, {4,5,6}), {1,2,3,4,5,6})) end function t.test_maybe_add_1 () assert_true(util.equal(util.maybe_add({}, "foo"), {foo={}})) assert_true(util.equal(util.maybe_add({bar="bar"}, "foo"), {foo={}, bar="bar"})) assert_true(util.equal(util.maybe_add({bar="bar"}, "bar"), {bar="bar"})) end function t.test_maybe_add_2 () assert_true(util.equal(util.maybe_add({}, "foo", true), {foo=true})) assert_true(util.equal(util.maybe_add({bar="bar"}, "foo", true), {foo=true, bar="bar"})) assert_true(util.equal(util.maybe_add({bar="bar"}, "bar", true), {bar="bar"})) end function t.test_maybe_add_3 () assert_true(util.equal(util.maybe_add({}, "foo", false), {foo=false})) assert_true(util.equal(util.maybe_add({bar="bar"}, "foo", false), {foo=false, bar="bar"})) assert_true(util.equal(util.maybe_add({bar="bar"}, "bar", false), {bar="bar"})) end return t
mit
mangostaniko/cg15-seganku
external/bullet/bullet-2.82-r2704/Demos/premake4.lua
10
2983
function createDemos( demos, incdirs, linknames) for _, name in ipairs(demos) do project ( "App_" .. name ) kind "ConsoleApp" targetdir ".." includedirs {incdirs} configuration { "Windows" } defines { "GLEW_STATIC"} links { "opengl32" } includedirs{ "../Glut" } libdirs {"../Glut"} files { "../build/bullet.rc" } configuration {"Windows", "x32"} links {"glew32s","glut32"} configuration {"Windows", "x64"} links {"glew64s", "glut64"} configuration {"MacOSX"} --print "hello" linkoptions { "-framework Carbon -framework OpenGL -framework AGL -framework Glut" } configuration {"not Windows", "not MacOSX"} links {"GL","GLU","glut"} configuration{} links { linknames } files { "./" .. name .. "/*.cpp" , "./" .. name .. "/*.h" } end end -- "CharacterDemo", fixme: it includes BspDemo files local localdemos = { "BasicDemo", "Box2dDemo", "BspDemo", "CcdPhysicsDemo", "CollisionDemo", "CollisionInterfaceDemo", "ConcaveConvexcastDemo", "ConcaveDemo", "ConcaveRaycastDemo", "ConstraintDemo", "ContinuousConvexCollision", "ConvexHullDistance", "DynamicControlDemo", "EPAPenDepthDemo", "ForkLiftDemo", "FeatherstoneMultiBodyDemo", "FractureDemo", "GenericJointDemo", "GimpactTestDemo", "GjkConvexCastDemo", "GyroscopicDemo", "InternalEdgeDemo", "MovingConcaveDemo", "MultiMaterialDemo", "RagdollDemo", "Raytracer", "RaytestDemo", "RollingFrictionDemo", "SimplexDemo", "SliderConstraintDemo", "TerrainDemo", "UserCollisionAlgorithm", "VehicleDemo", "VoronoiFractureDemo" } -- the following demos require custom include or link settings createDemos({"HelloWorld"},{"../src"},{"BulletDynamics","BulletCollision","LinearMath"}) createDemos(localdemos,{"../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"ConvexDecompositionDemo"},{"../Extras/HACD","../Extras/ConvexDecomposition","../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath","HACD","ConvexDecomposition"}) createDemos({"SoftDemo"},{"../src","OpenGL"}, {"OpenGLSupport","BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"SerializeDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"BulletXmlImportDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletXmlWorldImporter", "../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletXmlWorldImporter","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) include "OpenGL"
apache-2.0
misterdustinface/Lua-Synergy
Lua-Synergy/src/IO/STD.lua
1
1614
require 'tif' STD = { } local writeTable local writeBoolean local writeValue local writeValueDispatchTable = { ["nil"] = function() io.write("nil") end, boolean = writeBoolean, number = io.write, string = io.write, table = writeTable, } function writeBoolean(x) io.write( tif(x, "true", "false") ) end function writeTable(t) io.write('{') for k,v in pairs(t) do writeValue(v) if k < #t then io.write(', ') end end io.write('}') end function writeValue(x) writeValueDispatchTable[type(x)](x) end STD.write = writeValue STD.flush = io.flush STD.read = io.read STD.readall = function() io.read("*all") end STD.fill = function(char, n) local str = {} for i = 0, n do table.insert(str, char) end return table.concat(str, "") end STD.prompt = function(promptMessage) io.write(promptMessage); io.flush(); return io.read() end STD.writeToFile = function(filename, data) local out = assert(io.open( filename, "a+" )) out:write(data); out:flush() assert(out:close()) end STD.list = function(table, prefix) prefix = prefix or "" for _,v in pairs(table) do io.write(prefix) writeValue(v) io.write('\n') end end STD.HELP = list STD.clear = function(table) local iterationKey = next(table) while iterationKey ~= nil do table[iterationKey] = nil iterationKey = next(table) end return table end STD.copy = function(source, destination) if not source then return nil end if not destination then destination = {} end for key, value in pairs(source) do rawset(destination, key, value) end return destination end
gpl-2.0
KNIGHTTH0R/uzz
plugins/search_youtube.lua
674
1270
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end local function searchYoutubeVideos(text) local url = 'https://www.googleapis.com/youtube/v3/search?' url = url..'part=snippet'..'&maxResults=4'..'&type=video' url = url..'&q='..URL.escape(text) if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local data = httpsRequest(url) if not data then print("HTTP Error") return nil elseif not data.items then return nil end return data.items end local function run(msg, matches) local text = '' local items = searchYoutubeVideos(matches[1]) if not items then return "Error!" end for k,item in pairs(items) do text = text..'http://youtu.be/'..item.id.videoId..' '.. item.snippet.title..'\n\n' end return text end return { description = "Search video on youtube and send it.", usage = "!youtube [term]: Search for a youtube video and send it.", patterns = { "^!youtube (.*)" }, run = run } end
gpl-2.0
paulmarsy/Console
Libraries/nmap/App/nselib/url.lua
5
11906
--- -- URI parsing, composition, and relative URL resolution. -- -- A URL is represented as a table with the following entries: -- * <code>scheme</code> -- * <code>fragment</code> -- * <code>query</code> -- * <code>params</code> -- * <code>authority</code> -- * <code>userinfo</code> -- * <code>path</code> -- * <code>port</code> -- * <code>password</code> -- These correspond to these parts of a URL (some may be <code>nil</code>): -- <code> -- scheme://userinfo@password:authority:port/path;params?query#fragment -- </code> -- -- @author Diego Nehab -- @author Eddie Bell <ejlbell@gmail.com> --[[ URI parsing, composition and relative URL resolution LuaSocket toolkit. Author: Diego Nehab RCS ID: $Id: url.lua,v 1.37 2005/11/22 08:33:29 diego Exp $ parse_query and build_query added For nmap (Eddie Bell <ejlbell@gmail.com>) --]] ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local _G = require "_G" local stdnse = require "stdnse" local string = require "string" local table = require "table" local base = _G _ENV = stdnse.module("url", stdnse.seeall) _VERSION = "URL 1.0" --[[ Internal functions --]] local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end -- these are allowed withing a path segment, along with alphanum -- other characters must be escaped local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } --- -- Protects a path segment, to prevent it from interfering with the -- URL parsing. -- @param s Binary string to be encoded. -- @return Escaped representation of string. local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end --- -- Builds a path from a base path and a relative path -- @param base_path A base path. -- @param relative_path A relative path. -- @return The corresponding absolute path. ----------------------------------------------------------------------------- local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end --[[ External functions --]] --- -- Encodes a string into its escaped hexadecimal representation. -- @param s Binary string to be encoded. -- @return Escaped representation of string. ----------------------------------------------------------------------------- function escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end --- -- Decodes an escaped hexadecimal string. -- @param s Hexadecimal-encoded string. -- @return Decoded string. ----------------------------------------------------------------------------- function unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end --- -- Parses a URL and returns a table with all its parts according to RFC 2396. -- -- The following grammar describes the names given to the URL parts. -- <code> -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- </code> -- -- The leading <code>/</code> in <code>/<path></code> is considered part of -- <code><path></code>. -- @param url URL of request. -- @param default Table with default values for each field. -- @return A table with the following fields, where RFC naming conventions have -- been preserved: -- <code>scheme</code>, <code>authority</code>, <code>userinfo</code>, -- <code>user</code>, <code>password</code>, <code>host</code>, -- <code>port</code>, <code>path</code>, <code>params</code>, -- <code>query</code>, and <code>fragment</code>. ----------------------------------------------------------------------------- function parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme. Lower-case according to RFC 3986 section 3.1. url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = string.lower(s); return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left parsed.path = url local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([0-9]*)$", function(p) if p ~= "" then parsed.port = p end; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end --- -- Rebuilds a parsed URL from its components. -- -- Components are protected if any reserved or disallowed characters are found. -- @param parsed Parsed URL, as returned by parse. -- @return A string with the corresponding URL. ----------------------------------------------------------------------------- function build(parsed) local ppath = parse_path(parsed.path or "") local url = build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end --- -- Builds an absolute URL from a base and a relative URL according to RFC 2396. -- @param base_url A base URL. -- @param relative_url A relative URL. -- @return The corresponding absolute URL. ----------------------------------------------------------------------------- function absolute(base_url, relative_url) local base_parsed; if type(base_url) == "table" then base_parsed = base_url base_url = build(base_parsed) else base_parsed = parse(base_url) end local relative_parsed = parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return build(relative_parsed) end end --- -- Breaks a path into its segments, unescaping the segments. -- @param path A path to break. -- @return A table with one entry per segment. ----------------------------------------------------------------------------- function parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i, v in ipairs(parsed) do parsed[i] = unescape(v) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end --- -- Builds a path component from its segments, escaping protected characters. -- @param parsed Path segments. -- @param unsafe If true, segments are not protected before path is built. -- @return The corresponding path string ----------------------------------------------------------------------------- function build_path(parsed, unsafe) local path = {} if parsed.is_absolute then path[#path+1] = "/" end local n = #parsed if unsafe then for i = 1, n-1 do path[#path+1] = parsed[i] .. "/" end if n > 0 then path[#path+1] = parsed[n] if parsed.is_directory then path[#path+1] = "/" end end else for i = 1, n-1 do path[#path+1] = protect_segment(parsed[i]) .. "/" end if n > 0 then path[#path+1] = protect_segment(parsed[n]) if parsed.is_directory then path[#path+1] = "/" end end end return table.concat(path) end --- -- Breaks a query string into name/value pairs. -- -- This function takes a <code><query></code> of the form -- <code>"name1=value1&name2=value2"</code> -- and returns a table containing the name-value pairs, with the name as the key -- and the value as its associated value. Both the name and the value are -- subject to URL decoding. -- @param query Query string. -- @return A table of name-value pairs following the pattern -- <code>table["name"]</code> = <code>value</code>. ----------------------------------------------------------------------------- function parse_query(query) local parsed = {} local pos = 0 query = string.gsub(query, "&amp;", "&") query = string.gsub(query, "&lt;", "<") query = string.gsub(query, "&gt;", ">") local function ginsert(qstr) local pos = qstr:find("=", 1, true) if pos then parsed[unescape(qstr:sub(1, pos - 1))] = unescape(qstr:sub(pos + 1)) else parsed[unescape(qstr)] = "" end end while true do local first, last = string.find(query, "&", pos) if first then ginsert(string.sub(query, pos, first-1)); pos = last+1 else ginsert(string.sub(query, pos)); break; end end return parsed end --- -- Builds a query string from a table. -- -- This is the inverse of <code>parse_query</code>. Both the parameter name -- and value are subject to URL encoding. -- @param query A dictionary table where <code>table['name']</code> = -- <code>value</code>. -- @return A query string (like <code>"name=value2&name=value2"</code>). ----------------------------------------------------------------------------- function build_query(query) local qstr = {} for i,v in pairs(query) do qstr[#qstr+1] = escape(i) .. '=' .. escape(v) end return table.concat(qstr, '&') end return _ENV;
mit
MmxBoy/test2
bot/sbssxybot.lua
1
6866
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") 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 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, false, 60*5.0) -- See plugins/isup.lua as an example for cron _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 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 -- 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 = { "banhammer", "channels", "greeter", "groupmanager", "help", "id", "invite", "moderation", "plugins", "version"}, sudo_users = {194229913}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } 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) --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("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 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 194229913 now = os.time() math.randomseed(now) started = false
gpl-2.0
Crazy-Duck/junglenational
game/dota_addons/junglenational/scripts/vscripts/libraries/animations.lua
1
16025
ANIMATIONS_VERSION = "1.00" --[[ Lua-controlled Animations Library by BMD Installation -"require" this file inside your code in order to gain access to the StartAnmiation and EndAnimation global. -Additionally, ensure that this file is placed in the vscripts/libraries path and that the vscripts/libraries/modifiers/modifier_animation.lua, modifier_animation_translate.lua, modifier_animation_translate_permanent.lua, and modifier_animation_freeze.lua files exist and are in the correct path Usage -Animations can be started for any unit and are provided as a table of information to the StartAnimation call -Repeated calls to StartAnimation for a single unit will cancel any running animation and begin the new animation -EndAnimation can be called in order to cancel a running animation -Animations are specified by a table which has as potential parameters: -duration: The duration to play the animation. The animation will be cancelled regardless of how far along it is at the end fo the duration. -activity: An activity code which will be used as the base activity for the animation i.e. DOTA_ACT_RUN, DOTA_ACT_ATTACK, etc. -rate: An optional (will be 1.0 if unspecified) animation rate to be used when playing this animation. -translate: An optional translate activity modifier string which can be used to modify the animation sequence. Example: For ACT_DOTA_RUN+haste, this should be "haste" -translate2: A second optional translate activity modifier string which can be used to modify the animation sequence further. Example: For ACT_DOTA_ATTACK+sven_warcry+sven_shield, this should be "sven_warcry" or "sven_shield" while the translate property is the other translate modifier -A permanent activity translate can be applied to a unit by calling AddAnimationTranslate for that unit. This allows for a permanent "injured" or "aggressive" animation stance. -Permanent activity translate modifiers can be removed with RemoveAnimationTranslate. -Animations can be frozen in place at any time by calling FreezeAnimation(unit[, duration]). Leaving the duration off will cause the animation to be frozen until UnfreezeAnimation is called. -Animations can be unfrozen at any time by calling UnfreezeAnimation(unit) Notes -Animations can only play for valid activities/sequences possessed by the model the unit is using. -Sequences requiring 3+ activity modifier translates (i.e "stun+fear+loadout" or similar) are not possible currently in this library. -Calling EndAnimation and attempting to StartAnimation a new animation for the same unit withing ~2 server frames of the animation end will likely fail to play the new animation. Calling StartAnimation directly without ending the previous animation will automatically add in this delay and cancel the previous animation. -The maximum animation rate which can be used is 12.75, and animation rates can only exist at a 0.05 resolution (i.e. 1.0, 1.05, 1.1 and not 1.06) -StartAnimation and EndAnimation functions can also be accessed through GameRules as GameRules.StartAnimation and GameRules.EndAnimation for use in scoped lua files (triggers, vscript ai, etc) -This library requires that the "libraries/timers.lua" be present in your vscripts directory. Examples: --Start a running animation at 2.5 rate for 2.5 seconds StartAnimation(unit, {duration=2.5, activity=ACT_DOTA_RUN, rate=2.5}) --End a running animation EndAnimation(unit) --Start a running + hasted animation at .8 rate for 5 seconds StartAnimation(unit, {duration=5, activity=ACT_DOTA_RUN, rate=0.8, translate="haste"}) --Start a shield-bash animation for sven with variable rate StartAnimation(unit, {duration=1.5, activity=ACT_DOTA_ATTACK, rate=RandomFloat(.5, 1.5), translate="sven_warcry", translate2="sven_shield"}) --Start a permanent injured translate modifier AddAnimationTranslate(unit, "injured") --Remove a permanent activity translate modifier RemoveAnimationTranslate(unit) --Freeze an animation for 4 seconds FreezeAnimation(unit, 4) --Unfreeze an animation UnfreezeAnimation(unit) ]] LinkLuaModifier( "modifier_animation", "libraries/modifiers/modifier_animation.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_translate", "libraries/modifiers/modifier_animation_translate.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_translate_permanent", "libraries/modifiers/modifier_animation_translate_permanent.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_freeze", "libraries/modifiers/modifier_animation_freeze.lua", LUA_MODIFIER_MOTION_NONE ) require('libraries/timers') local _ANIMATION_TRANSLATE_TO_CODE = { abysm= 13, admirals_prow= 307, agedspirit= 3, aggressive= 4, agrressive= 163, am_blink= 182, ancestors_edge= 144, ancestors_pauldron= 145, ancestors_vambrace= 146, ancestral_scepter= 67, ancient_armor= 6, anvil= 7, arcana= 8, armaments_set= 20, axes= 188, backstab= 41, backstroke_gesture= 283, backward= 335, ball_lightning= 231, batter_up= 43, bazooka= 284, belly_flop= 180, berserkers_blood= 35, black= 44, black_hole= 194, bladebiter= 147, blood_chaser= 134, bolt= 233, bot= 47, brain_sap= 185, broodmother_spin= 50, burning_fiend= 148, burrow= 229, burrowed= 51, cat_dancer_gesture= 285, cauldron= 29, charge= 97, charge_attack= 98, chase= 246, chasm= 57, chemical_rage= 2, chicken_gesture= 258, come_get_it= 39, corpse_dress= 104, corpse_dresstop= 103, corpse_scarf= 105, cryAnimationExportNode= 341, crystal_nova= 193, culling_blade= 184, dagger_twirl= 143, dark_wraith= 174, darkness= 213, dc_sb_charge= 107, dc_sb_charge_attack= 108, dc_sb_charge_finish= 109, dc_sb_ultimate= 110, deadwinter_soul= 96, death_protest= 94, demon_drain= 116, desolation= 55, digger= 176, dismember= 218, divine_sorrow= 117, divine_sorrow_loadout= 118, divine_sorrow_loadout_spawn= 119, divine_sorrow_sunstrike= 120, dizzying_punch= 343, dog_of_duty= 342, dogofduty= 340, dominator= 254, dryad_tree= 311, dualwield= 14, duel_kill= 121, earthshock= 235, emp= 259, enchant_totem= 313, ["end"]= 243, eyeoffetizu= 34, f2p_doom= 131, face_me= 286, faces_hakama= 111, faces_mask= 113, faces_wraps= 112, fast= 10, faster= 11, fastest= 12, fear= 125, fiends_grip= 186, fiery_soul= 149, finger= 200, firefly= 190, fish_slap= 123, fishstick= 339, fissure= 195, flying= 36, focusfire= 124, forcestaff_enemy= 122, forcestaff_friendly= 15, forward= 336, fountain= 49, freezing_field= 191, frost_arrow= 37, frostbite= 192, frostiron_raider= 150, frostivus= 54, ftp_dendi_back= 126, gale= 236, get_burned= 288, giddy_up_gesture= 289, glacier= 101, glory= 345, good_day_sir= 40, great_safari= 267, greevil_black_hole= 58, greevil_blade_fury= 59, greevil_bloodlust= 60, greevil_cold_snap= 61, greevil_decrepify= 62, greevil_diabolic_edict= 63, greevil_echo_slam= 64, greevil_fatal_bonds= 65, greevil_ice_wall= 66, greevil_laguna_blade= 68, greevil_leech_seed= 69, greevil_magic_missile= 70, greevil_maledict= 71, greevil_miniboss_black_brain_sap= 72, greevil_miniboss_black_nightmare= 73, greevil_miniboss_blue_cold_feet= 74, greevil_miniboss_blue_ice_vortex= 75, greevil_miniboss_green_living_armor= 76, greevil_miniboss_green_overgrowth= 77, greevil_miniboss_orange_dragon_slave= 78, greevil_miniboss_orange_lightstrike_array= 79, greevil_miniboss_purple_plague_ward= 80, greevil_miniboss_purple_venomous_gale= 81, greevil_miniboss_red_earthshock= 82, greevil_miniboss_red_overpower= 83, greevil_miniboss_white_purification= 84, greevil_miniboss_yellow_ion_shell= 85, greevil_miniboss_yellow_surge= 86, greevil_natures_attendants= 87, greevil_phantom_strike= 88, greevil_poison_nova= 89, greevil_purification= 90, greevil_shadow_strike= 91, greevil_shadow_wave= 92, groove_gesture= 305, ground_pound= 128, guardian_angel= 215, guitar= 290, hang_loose_gesture= 291, happy_dance= 293, harlequin= 129, haste= 45, hook= 220, horn= 292, immortal= 28, impale= 201, impatient_maiden= 100, impetus= 138, injured= 5, ["injured rare"]= 247, injured_aggressive= 130, instagib= 21, iron= 255, iron_surge= 99, item_style_2= 133, jump_gesture= 294, laguna= 202, leap= 206, level_1= 140, level_2= 141, level_3= 142, life_drain= 219, loadout= 0, loda= 173, lodestar= 114, loser= 295, lsa= 203, lucentyr= 158, lute= 296, lyreleis_breeze= 159, mace= 160, mag_power_gesture= 298, magic_ends_here= 297, mana_drain= 204, mana_void= 183, manias_mask= 135, manta= 38, mask_lord= 299, masquerade= 25, meld= 162, melee= 334, miniboss= 164, moon_griffon= 166, moonfall= 165, moth= 53, nihility= 95, obeisance_of_the_keeper= 151, obsidian_helmet= 132, odachi= 32, offhand_basher= 42, omnislash= 198, overpower1= 167, overpower2= 168, overpower3= 169, overpower4= 170, overpower5= 171, overpower6= 172, pegleg= 248, phantom_attack= 16, pinfold= 175, plague_ward= 237, poison_nova= 238, portrait_fogheart= 177, poundnpoint= 300, powershot= 242, punch= 136, purification= 216, pyre= 26, qop_blink= 221, ravage= 225, red_moon= 30, reincarnate= 115, remnant= 232, repel= 217, requiem= 207, roar= 187, robot_gesture= 301, roshan= 181, salvaged_sword= 152, sandking_rubyspire_burrowstrike= 52, sb_bracers= 251, sb_helmet= 250, sb_shoulder= 252, sb_spear= 253, scream= 222, serene_honor= 153, shadow_strike= 223, shadowraze= 208, shake_moneymaker= 179, sharp_blade= 303, shinobi= 27, shinobi_mask= 154, shinobi_tail= 23, shrapnel= 230, silent_ripper= 178, slam= 196, slasher_chest= 262, slasher_mask= 263, slasher_offhand= 261, slasher_weapon= 260, sm_armor= 264, sm_head= 56, sm_shoulder= 265, snipe= 226, snowangel= 17, snowball= 102, sonic_wave= 224, sparrowhawk_bow= 269, sparrowhawk_cape= 270, sparrowhawk_hood= 272, sparrowhawk_quiver= 271, sparrowhawk_shoulder= 273, spin= 199, split_shot= 1, sprint= 275, sprout= 209, staff_swing= 304, stalker_exo= 93, start= 249, stinger= 280, stolen_charge= 227, stolen_firefly= 189, strike= 228, sugarrush= 276, suicide_squad= 18, summon= 210, sven_shield= 256, sven_warcry= 257, swag_gesture= 287, swordonshoulder= 155, taunt_fullbody= 19, taunt_killtaunt= 139, taunt_quickdraw_gesture= 268, taunt_roll_gesture= 302, techies_arcana= 9, telebolt= 306, teleport= 211, thirst= 137, tidebringer= 24, tidehunter_boat= 22, tidehunter_toss_fish= 312, tidehunter_yippy= 347, timelord_head= 309, tinker_rollermaw= 161, torment= 279, totem= 197, transition= 278, trapper= 314, tree= 310, trickortreat= 277, triumphant_timelord= 127, turbulent_teleport= 308, twinblade_attack= 315, twinblade_attack_b= 316, twinblade_attack_c= 317, twinblade_attack_d= 318, twinblade_attack_injured= 319, twinblade_death= 320, twinblade_idle= 321, twinblade_idle_injured= 322, twinblade_idle_rare= 323, twinblade_injured_attack_b= 324, twinblade_jinada= 325, twinblade_jinada_injured= 326, twinblade_shuriken_toss= 327, twinblade_shuriken_toss_injured= 328, twinblade_spawn= 329, twinblade_stun= 330, twinblade_track= 331, twinblade_track_injured= 332, twinblade_victory= 333, twister= 274, unbroken= 106, vendetta= 337, viper_strike= 239, viridi_set= 338, void= 214, vortex= 234, wall= 240, ward= 241, wardstaff= 344, wave= 205, web= 48, whalehook= 156, whats_that= 281, when_nature_attacks= 31, white= 346, windrun= 244, windy= 245, winterblight= 157, witchdoctor_jig= 282, with_item= 46, wolfhound= 266, wraith_spin= 33, wrath= 212, rampant= 348, overload= 349, surge=350, es_prosperity=351, Espada_pistola=352, overload_injured=353, ss_fortune=354, liquid_fire=355, jakiro_icemelt=356, jakiro_roar=357, chakram=358, doppelwalk=359, enrage=360, fast_run=361, overpower=362, overwhelmingodds=363, pregame=364, shadow_dance=365, shukuchi=366, strength=367, twinblade_run=368, twinblade_run_injured=369, windwalk=370, } function StartAnimation(unit, table) local duration = table.duration local activity = table.activity local translate = table.translate local translate2 = table.translate2 local rate = table.rate or 1.0 rate = math.floor(math.max(0,math.min(255/20, rate)) * 20 + .5) local stacks = activity + bit.lshift(rate,11) if translate ~= nil then if _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.") return end stacks = stacks + bit.lshift(_ANIMATION_TRANSLATE_TO_CODE[translate],19) end if translate2 ~= nil and _ANIMATION_TRANSLATE_TO_CODE[translate2] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate2 .. "'. This translate may be misspelled or need to be added to the enum manually.") return end if unit:HasModifier("modifier_animation") or (unit._animationEnd ~= nil and unit._animationEnd + .067 > GameRules:GetGameTime()) then EndAnimation(unit) Timers:CreateTimer(.066, function() if translate2 ~= nil then unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2}) unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2]) end unit._animationEnd = GameRules:GetGameTime() + duration unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation", unit, stacks) end) else if translate2 ~= nil then unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2}) unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2]) end unit._animationEnd = GameRules:GetGameTime() + duration unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation", unit, stacks) end end function FreezeAnimation(unit, duration) if duration then unit:AddNewModifier(unit, nil, "modifier_animation_freeze", {duration=duration}) else unit:AddNewModifier(unit, nil, "modifier_animation_freeze", {}) end end function UnfreezeAnimation(unit) unit:RemoveModifierByName("modifier_animation_freeze") end function EndAnimation(unit) unit._animationEnd = GameRules:GetGameTime() unit:RemoveModifierByName("modifier_animation") unit:RemoveModifierByName("modifier_animation_translate") end function AddAnimationTranslate(unit, translate) if translate == nil or _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.") return end unit:AddNewModifier(unit, nil, "modifier_animation_translate_permanent", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation_translate_permanent", unit, _ANIMATION_TRANSLATE_TO_CODE[translate]) end function RemoveAnimationTranslate(unit) unit:RemoveModifierByName("modifier_animation_translate_permanent") end GameRules.StartAnimation = StartAnimation GameRules.EndAnimation = EndAnimation GameRules.AddAnimationTranslate = AddAnimationTranslate GameRules.RemoveAnimationTranslate = RemoveAnimationTranslate
mit
Samanstar/tele-Manager
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
alinfrat/nefratrobot
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
loringmoore/The-Forgotten-Server
data/npc/lib/npcsystem/keywordhandler.lua
8
5090
-- Advanced NPC System by Jiddo if KeywordHandler == nil then KeywordNode = { keywords = nil, callback = nil, parameters = nil, children = nil, parent = nil } -- Created a new keywordnode with the given keywords, callback function and parameters and without any childNodes. function KeywordNode:new(keys, func, param) local obj = {} obj.keywords = keys obj.callback = func obj.parameters = param obj.children = {} setmetatable(obj, self) self.__index = self return obj end -- Calls the underlying callback function if it is not nil. function KeywordNode:processMessage(cid, message) return (self.callback == nil or self.callback(cid, message, self.keywords, self.parameters, self)) end -- Returns true if message contains all patterns/strings found in keywords. function KeywordNode:checkMessage(message) if self.keywords.callback ~= nil then return self.keywords.callback(self.keywords, message) end for i,v in ipairs(self.keywords) do if type(v) == 'string' then local a, b = string.find(message, v) if a == nil or b == nil then return false end end end return true end -- Returns the parent of this node or nil if no such node exists. function KeywordNode:getParent() return self.parent end -- Returns an array of the callback function parameters assosiated with this node. function KeywordNode:getParameters() return self.parameters end -- Returns an array of the triggering keywords assosiated with this node. function KeywordNode:getKeywords() return self.keywords end -- Adds a childNode to this node. Creates the childNode based on the parameters (k = keywords, c = callback, p = parameters) function KeywordNode:addChildKeyword(keywords, callback, parameters) local new = KeywordNode:new(keywords, callback, parameters) return self:addChildKeywordNode(new) end -- Adds a pre-created childNode to this node. Should be used for example if several nodes should have a common child. function KeywordNode:addChildKeywordNode(childNode) self.children[#self.children + 1] = childNode childNode.parent = self return childNode end KeywordHandler = { root = nil, lastNode = {} } -- Creates a new keywordhandler with an empty rootnode. function KeywordHandler:new() local obj = {} obj.root = KeywordNode:new(nil, nil, nil) setmetatable(obj, self) self.__index = self return obj end -- Resets the lastNode field, and this resetting the current position in the node hierarchy to root. function KeywordHandler:reset(cid) if self.lastNode[cid] then self.lastNode[cid] = nil end end -- Makes sure the correct childNode of lastNode gets a chance to process the message. function KeywordHandler:processMessage(cid, message) local node = self:getLastNode(cid) if node == nil then error('No root node found.') return false end local ret = self:processNodeMessage(node, cid, message) if ret then return true end if node:getParent() then node = node:getParent() -- Search through the parent. local ret = self:processNodeMessage(node, cid, message) if ret then return true end end if node ~= self:getRoot() then node = self:getRoot() -- Search through the root. local ret = self:processNodeMessage(node, cid, message) if ret then return true end end return false end -- Tries to process the given message using the node parameter's children and calls the node's callback function if found. -- Returns the childNode which processed the message or nil if no such node was found. function KeywordHandler:processNodeMessage(node, cid, message) local messageLower = string.lower(message) for i, childNode in pairs(node.children) do if childNode:checkMessage(messageLower) then local oldLast = self.lastNode[cid] self.lastNode[cid] = childNode childNode.parent = node -- Make sure node is the parent of childNode (as one node can be parent to several nodes). if childNode:processMessage(cid, message) then return true end self.lastNode[cid] = oldLast end end return false end -- Returns the root keywordnode function KeywordHandler:getRoot() return self.root end -- Returns the last processed keywordnode or root if no last node is found. function KeywordHandler:getLastNode(cid) return self.lastNode[cid] or self:getRoot() end -- Adds a new keyword to the root keywordnode. Returns the new node. function KeywordHandler:addKeyword(keys, callback, parameters) return self:getRoot():addChildKeyword(keys, callback, parameters) end -- Moves the current position in the keyword hierarchy count steps upwards. Count defalut value = 1. -- This function MIGHT not work properly yet. Use at your own risk. function KeywordHandler:moveUp(count) local steps = count if steps == nil or type(steps) ~= "number" then steps = 1 end for i = 1, steps, 1 do if self.lastNode[cid] == nil then break end self.lastNode[cid] = self.lastNode[cid]:getParent() or self:getRoot() end return self.lastNode[cid] end end
gpl-2.0
m-creations/openwrt
feeds/luci/applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/iwinfo.lua
31
1569
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.iwinfo", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- signal/noise diagram -- local snr = { title = "%H: Signal and noise on %pi", vlabel = "dBm", number_format = "%5.1lf dBm", data = { types = { "signal_noise", "signal_power" }, options = { signal_power = { title = "Signal", overlay = true, color = "0000ff" }, signal_noise = { title = "Noise", overlay = true, color = "ff0000" } } } } -- -- signal quality diagram -- local quality = { title = "%H: Signal quality on %pi", vlabel = "Quality", number_format = "%3.0lf", data = { types = { "signal_quality" }, options = { signal_quality = { title = "Quality", noarea = true, color = "0000ff" } } } } -- -- phy rate diagram -- local bitrate = { title = "%H: Average phy rate on %pi", vlabel = "MBit/s", number_format = "%5.1lf%sBit/s", data = { types = { "bitrate" }, options = { bitrate = { title = "Rate", color = "00ff00" } } } } -- -- associated stations -- local stations = { title = "%H: Associated stations on %pi", vlabel = "Stations", number_format = "%3.0lf", data = { types = { "stations" }, options = { stations = { title = "Stations", color = "0000ff" } } } } return { snr, quality, bitrate, stations } end
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/applications/luci-multiwan/luasrc/model/cbi/multiwan/multiwan.lua
7
5178
require("luci.tools.webadmin") m = Map("multiwan", translate("Multi-WAN"), translate("Multi-WAN allows for the use of multiple uplinks for load balancing and failover.")) s = m:section(NamedSection, "config", "multiwan", "") e = s:option(Flag, "enabled", translate("Enable")) e.rmempty = false function e.write(self, section, value) local cmd = (value == "1") and "enable" or "disable" if value ~= "1" then os.execute("/etc/init.d/multiwan stop") end os.execute("/etc/init.d/multiwan " .. cmd) end function e.cfgvalue(self, section) return (os.execute("/etc/init.d/multiwan enabled") == 0) and "1" or "0" end s = m:section(TypedSection, "interface", translate("WAN Interfaces"), translate("Health Monitor detects and corrects network changes and failed connections.")) s.addremove = true weight = s:option(ListValue, "weight", translate("Load Balancer Distribution")) weight:value("10", "10") weight:value("9", "9") weight:value("8", "8") weight:value("7", "7") weight:value("6", "6") weight:value("5", "5") weight:value("4", "4") weight:value("3", "3") weight:value("2", "2") weight:value("1", "1") weight:value("disable", translate("None")) weight.default = "10" weight.optional = false weight.rmempty = false interval = s:option(ListValue, "health_interval", translate("Health Monitor Interval")) interval:value("disable", translate("Disable")) interval:value("5", "5 sec.") interval:value("10", "10 sec.") interval:value("20", "20 sec.") interval:value("30", "30 sec.") interval:value("60", "60 sec.") interval:value("120", "120 sec.") interval.default = "10" interval.optional = false interval.rmempty = false icmp_hosts = s:option(Value, "icmp_hosts", translate("Health Monitor ICMP Host(s)")) icmp_hosts:value("disable", translate("Disable")) icmp_hosts:value("dns", "DNS Server(s)") icmp_hosts:value("gateway", "WAN Gateway") icmp_hosts.default = "dns" icmp_hosts.optional = false icmp_hosts.rmempty = false timeout = s:option(ListValue, "timeout", translate("Health Monitor ICMP Timeout")) timeout:value("1", "1 sec.") timeout:value("2", "2 sec.") timeout:value("3", "3 sec.") timeout:value("4", "4 sec.") timeout:value("5", "5 sec.") timeout:value("10", "10 sec.") timeout.default = "3" timeout.optional = false timeout.rmempty = false fail = s:option(ListValue, "health_fail_retries", translate("Attempts Before WAN Failover")) fail:value("1", "1") fail:value("3", "3") fail:value("5", "5") fail:value("10", "10") fail:value("15", "15") fail:value("20", "20") fail.default = "3" fail.optional = false fail.rmempty = false recovery = s:option(ListValue, "health_recovery_retries", translate("Attempts Before WAN Recovery")) recovery:value("1", "1") recovery:value("3", "3") recovery:value("5", "5") recovery:value("10", "10") recovery:value("15", "15") recovery:value("20", "20") recovery.default = "5" recovery.optional = false recovery.rmempty = false failover_to = s:option(ListValue, "failover_to", translate("Failover Traffic Destination")) failover_to:value("disable", translate("None")) luci.tools.webadmin.cbi_add_networks(failover_to) failover_to:value("fastbalancer", translate("Load Balancer(Performance)")) failover_to:value("balancer", translate("Load Balancer(Compatibility)")) failover_to.default = "balancer" failover_to.optional = false failover_to.rmempty = false dns = s:option(Value, "dns", translate("DNS Server(s)")) dns:value("auto", translate("Auto")) dns.default = "auto" dns.optional = false dns.rmempty = true s = m:section(TypedSection, "mwanfw", translate("Multi-WAN Traffic Rules"), translate("Configure rules for directing outbound traffic through specified WAN Uplinks.")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true src = s:option(Value, "src", translate("Source Address")) src.rmempty = true src:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(src) dst = s:option(Value, "dst", translate("Destination Address")) dst.rmempty = true dst:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(dst) proto = s:option(Value, "proto", translate("Protocol")) proto:value("", translate("all")) proto:value("tcp", "TCP") proto:value("udp", "UDP") proto:value("icmp", "ICMP") proto.rmempty = true ports = s:option(Value, "ports", translate("Ports")) ports.rmempty = true ports:value("", translate("all", translate("all"))) wanrule = s:option(ListValue, "wanrule", translate("WAN Uplink")) luci.tools.webadmin.cbi_add_networks(wanrule) wanrule:value("fastbalancer", translate("Load Balancer(Performance)")) wanrule:value("balancer", translate("Load Balancer(Compatibility)")) wanrule.default = "fastbalancer" wanrule.optional = false wanrule.rmempty = false s = m:section(NamedSection, "config", "", "") s.addremove = false default_route = s:option(ListValue, "default_route", translate("Default Route")) luci.tools.webadmin.cbi_add_networks(default_route) default_route:value("fastbalancer", translate("Load Balancer(Performance)")) default_route:value("balancer", translate("Load Balancer(Compatibility)")) default_route.default = "balancer" default_route.optional = false default_route.rmempty = false return m
gpl-2.0
RvdE/pdns
pdns/recursordist/contrib/powerdns-example-script.lua
14
3915
pdnslog("pdns-recursor Lua script starting!", pdns.loglevels.Warning) blockset = newDS() blockset:add{"powerdns.org", "xxx"} dropset = newDS(); dropset:add("123.cn") malwareset = newDS() malwareset:add("nl") magic2 = newDN("www.magic2.com") magicMetric = getMetric("magic") -- shows the various ways of blocking, dropping, changing questions -- return false to say you did not take over the question, but we'll still listen to 'variable' -- to selectively disable the cache function preresolve(dq) print("Got question for "..dq.qname:toString().." from "..dq.remoteaddr:toString().." to "..dq.localaddr:toString()) local ednssubnet=dq:getEDNSSubnet() if(ednssubnet) then print("Packet EDNS subnet source: "..ednssubnet:toString()..", "..ednssubnet:getNetwork():toString()) end local a=dq:getEDNSOption(3) if(a) then print("There is an EDNS option 3 present: "..a) end loc = newCA("127.0.0.1") if(dq.remoteaddr:equal(loc)) then print("Query from loopback") end -- note that the comparisons below are CaSe InSensiTivE and you don't have to worry about trailing dots if(dq.qname:equal("magic.com")) then magicMetric:inc() print("Magic!") else print("not magic..") end if(dq.qname:__eq(magic2)) -- we hope to improve this syntax then print("Faster magic") -- compares against existing DNSName end -- sadly, dq.qname == magic2 won't work yet if blockset:check(dq.qname) then dq.variable = true -- disable packet cache in any case if dq.qtype == pdns.A then dq:addAnswer(pdns.A, "1.2.3.4") dq:addAnswer(pdns.TXT, "\"Hello!\"", 3601) -- ttl return true; end end if dropset:check(dq.qname) then dq.rcode = pdns.DROP return true; end if malwareset:check(dq.qname) then dq:addAnswer(pdns.CNAME, "xs.powerdns.com.") dq.rcode = 0 dq.followupFunction="followCNAMERecords" -- this makes PowerDNS lookup your CNAME return true; end return false; end -- this implements DNS64 function nodata(dq) if dq.qtype == pdns.AAAA then dq.followupFunction="getFakeAAAARecords" dq.followupName=dq.qname dq.followupPrefix="fe80::" return true end if dq.qtype == pdns.PTR then dq.followupFunction="getFakePTRRecords" dq.followupName=dq.qname dq.followupPrefix="fe80::" return true end return false end badips = newNMG() badips:addMask("127.1.0.0/16") -- this check is applied before any packet parsing is done function ipfilter(rem, loc, dh) print("ipfilter called, rem: ", rem:toStringWithPort(), "loc: ",loc:toStringWithPort(),"match:", badips:match(rem)) print("id: ",dh:getID(), "aa: ", dh:getAA(), "ad: ", dh:getAD(), "arcount: ", dh:getARCOUNT()) print("ports: ",rem:getPort(),loc:getPort()) return badips:match(rem) end -- postresolve runs after the packet has been answered, and can be used to change things -- or still drop function postresolve(dq) print("postresolve called for ",dq.qname:toString()) local records = dq:getRecords() for k,v in pairs(records) do print(k, v.name:toString(), v:getContent()) if v.type == pdns.A and v:getContent() == "185.31.17.73" then print("Changing content!") v:changeContent("130.161.252.29") v.ttl=1 end end dq:setRecords(records) return true end nxdomainsuffix=newDN("com") function nxdomain(dq) print("Hooking: ",dq.qname:toString()) if dq.qname:isPartOf(nxdomainsuffix) then dq.rcode=0 -- make it a normal answer dq:addAnswer(pdns.CNAME, "ourhelpfulservice.com") dq:addAnswer(pdns.A, "1.2.3.4", 60, "ourhelpfulservice.com") return true end return false end
gpl-2.0
Jagannadhvj/sipml5
asterisk/etc/extensions.lua
317
5827
CONSOLE = "Console/dsp" -- Console interface for demo --CONSOLE = "DAHDI/1" --CONSOLE = "Phone/phone0" IAXINFO = "guest" -- IAXtel username/password --IAXINFO = "myuser:mypass" TRUNK = "DAHDI/G2" TRUNKMSD = 1 -- TRUNK = "IAX2/user:pass@provider" -- -- Extensions are expected to be defined in a global table named 'extensions'. -- The 'extensions' table should have a group of tables in it, each -- representing a context. Extensions are defined in each context. See below -- for examples. -- -- Extension names may be numbers, letters, or combinations thereof. If -- an extension name is prefixed by a '_' character, it is interpreted as -- a pattern rather than a literal. In patterns, some characters have -- special meanings: -- -- X - any digit from 0-9 -- Z - any digit from 1-9 -- N - any digit from 2-9 -- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9) -- . - wildcard, matches anything remaining (e.g. _9011. matches -- anything starting with 9011 excluding 9011 itself) -- ! - wildcard, causes the matching process to complete as soon as -- it can unambiguously determine that no other matches are possible -- -- For example the extension _NXXXXXX would match normal 7 digit -- dialings, while _1NXXNXXXXXX would represent an area code plus phone -- number preceded by a one. -- -- If your extension has special characters in it such as '.' and '!' you must -- explicitly make it a string in the tabale definition: -- -- ["_special."] = function; -- ["_special!"] = function; -- -- There are no priorities. All extensions to asterisk appear to have a single -- priority as if they consist of a single priority. -- -- Each context is defined as a table in the extensions table. The -- context names should be strings. -- -- One context may be included in another context using the 'includes' -- extension. This extension should be set to a table containing a list -- of context names. Do not put references to tables in the includes -- table. -- -- include = {"a", "b", "c"}; -- -- Channel variables can be accessed thorugh the global 'channel' table. -- -- v = channel.var_name -- v = channel["var_name"] -- v.value -- v:get() -- -- channel.var_name = "value" -- channel["var_name"] = "value" -- v:set("value") -- -- channel.func_name(1,2,3):set("value") -- value = channel.func_name(1,2,3):get() -- -- channel["func_name(1,2,3)"]:set("value") -- channel["func_name(1,2,3)"] = "value" -- value = channel["func_name(1,2,3)"]:get() -- -- Note the use of the ':' operator to access the get() and set() -- methods. -- -- Also notice the absence of the following constructs from the examples above: -- channel.func_name(1,2,3) = "value" -- this will NOT work -- value = channel.func_name(1,2,3) -- this will NOT work as expected -- -- -- Dialplan applications can be accessed through the global 'app' table. -- -- app.Dial("DAHDI/1") -- app.dial("DAHDI/1") -- -- More examples can be found below. -- -- An autoservice is automatically run while lua code is executing. The -- autoservice can be stopped and restarted using the autoservice_stop() and -- autoservice_start() functions. The autservice should be running before -- starting long running operations. The autoservice will automatically be -- stopped before executing applications and dialplan functions and will be -- restarted afterwards. The autoservice_status() function can be used to -- check the current status of the autoservice and will return true if an -- autoservice is currently running. -- function outgoing_local(c, e) app.dial("DAHDI/1/" .. e, "", "") end function demo_instruct() app.background("demo-instruct") app.waitexten() end function demo_congrats() app.background("demo-congrats") demo_instruct() end -- Answer the chanel and play the demo sound files function demo_start(context, exten) app.wait(1) app.answer() channel.TIMEOUT("digit"):set(5) channel.TIMEOUT("response"):set(10) -- app.set("TIMEOUT(digit)=5") -- app.set("TIMEOUT(response)=10") demo_congrats(context, exten) end function demo_hangup() app.playback("demo-thanks") app.hangup() end extensions = { demo = { s = demo_start; ["2"] = function() app.background("demo-moreinfo") demo_instruct() end; ["3"] = function () channel.LANGUAGE():set("fr") -- set the language to french demo_congrats() end; ["1000"] = function() app.goto("demo", "s", 1) end; ["1234"] = function() app.playback("transfer", "skip") -- do a dial here end; ["1235"] = function() app.voicemail("1234", "u") end; ["1236"] = function() app.dial("Console/dsp") app.voicemail(1234, "b") end; ["#"] = demo_hangup; t = demo_hangup; i = function() app.playback("invalid") demo_instruct() end; ["500"] = function() app.playback("demo-abouttotry") app.dial("IAX2/guest@misery.digium.com/s@default") app.playback("demo-nogo") demo_instruct() end; ["600"] = function() app.playback("demo-echotest") app.echo() app.playback("demo-echodone") demo_instruct() end; ["8500"] = function() app.voicemailmain() demo_instruct() end; }; default = { -- by default, do the demo include = {"demo"}; }; public = { -- ATTENTION: If your Asterisk is connected to the internet and you do -- not have allowguest=no in sip.conf, everybody out there may use your -- public context without authentication. In that case you want to -- double check which services you offer to the world. -- include = {"demo"}; }; ["local"] = { ["_NXXXXXX"] = outgoing_local; }; } hints = { demo = { [1000] = "SIP/1000"; [1001] = "SIP/1001"; }; default = { ["1234"] = "SIP/1234"; }; }
bsd-3-clause
yetsky/extra
luci/applications/luci-shadowsocks/luasrc/model/cbi/shadowsocks.lua
1
3723
--[[ RA-MOD ]]-- local fs = require "nixio.fs" local sslocal =(luci.sys.call("pidof ss-local > /dev/null") == 0) local ssredir =(luci.sys.call("pidof ss-redir > /dev/null") == 0) if sslocal or ssredir then m = Map("shadowsocks", translate("shadowsocks"), translate("shadowsocks is running")) else m = Map("shadowsocks", translate("shadowsocks"), translate("shadowsocks is not running")) end server = m:section(TypedSection, "shadowsocks", translate("Server Setting")) server.anonymous = true remote_server = server:option(Value, "remote_server", translate("Server Address")) remote_server.datatype = ipaddr remote_server.optional = false remote_port = server:option(Value, "remote_port", translate("Server Port")) remote_port.datatype = "range(0,65535)" remote_port.optional = false password = server:option(Value, "password", translate("Password")) password.password = true cipher = server:option(ListValue, "cipher", translate("Cipher Method")) cipher:value("table") cipher:value("rc4") cipher:value("rc4-md5") cipher:value("aes-128-cfb") cipher:value("aes-192-cfb") cipher:value("aes-256-cfb") cipher:value("bf-cfb") cipher:value("cast5-cfb") cipher:value("des-cfb") cipher:value("camellia-128-cfb") cipher:value("camellia-192-cfb") cipher:value("camellia-256-cfb") cipher:value("idea-cfb") cipher:value("rc2-cfb") cipher:value("seed-cfb") cipher:value("chacha20") cipher:value("salsa20") socks5 = m:section(TypedSection, "shadowsocks", translate("SOCKS5 Proxy")) socks5.anonymous = true switch = socks5:option(Flag, "enabled", translate("Enable")) switch.rmempty = false local_port = socks5:option(Value, "local_port", translate("Local Port")) local_port.datatype = "range(0,65535)" local_port.optional = false redir = m:section(TypedSection, "shadowsocks", translate("Transparent Proxy")) redir.anonymous = true redir_enable = redir:option(Flag, "redir_enabled", translate("Enable")) redir_enable.default = false redir_port = redir:option(Value, "redir_port", translate("Transparent Proxy Local Port")) redir_port.datatype = "range(0,65535)" redir_port.optional = false blacklist_enable = redir:option(Flag, "blacklist_enabled", translate("Bypass Lan IP")) blacklist_enable.default = false blacklist = redir:option(TextValue, "blacklist", " ", "") blacklist.template = "cbi/tvalue" blacklist.size = 30 blacklist.rows = 10 blacklist.wrap = "off" blacklist:depends("blacklist_enabled", 1) function blacklist.cfgvalue(self, section) return fs.readfile("/etc/ipset/blacklist") or "" end function blacklist.write(self, section, value) if value then value = value:gsub("\r\n?", "\n") fs.writefile("/tmp/blacklist", value) fs.mkdirr("/etc/ipset") if (fs.access("/etc/ipset/blacklist") ~= true or luci.sys.call("cmp -s /tmp/blacklist /etc/ipset/blacklist") == 1) then fs.writefile("/etc/ipset/blacklist", value) end fs.remove("/tmp/blacklist") end end whitelist_enable = redir:option(Flag, "whitelist_enabled", translate("Bypass IP Whitelist")) whitelist_enable.default = false whitelist = redir:option(TextValue, "whitelist", " ", "") whitelist.template = "cbi/tvalue" whitelist.size = 30 whitelist.rows = 10 whitelist.wrap = "off" whitelist:depends("whitelist_enabled", 1) function whitelist.cfgvalue(self, section) return fs.readfile("/etc/chinadns_chnroute.txt") or "" end function whitelist.write(self, section, value) if value then value = value:gsub("\r\n?", "\n") fs.writefile("/tmp/whitelist", value) fs.mkdirr("/etc/ipset") if (fs.access("/etc/chinadns_chnroute.txt") ~= true or luci.sys.call("cmp -s /tmp/whitelist /etc/chinadns_chnroute.txt") == 1) then fs.writefile("/etc/chinadns_chnroute.txt", value) end fs.remove("/tmp/whitelist") end end return m
gpl-2.0
frodrigo/osrm-backend
third_party/flatbuffers/samples/lua/MyGame/Sample/Monster.lua
17
3936
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: Sample local flatbuffers = require('flatbuffers') local Monster = {} -- the module local Monster_mt = {} -- the class metatable function Monster.New() local o = {} setmetatable(o, {__index = Monster_mt}) return o end function Monster.GetRootAsMonster(buf, offset) local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = Monster.New() o:Init(buf, n + offset) return o end function Monster_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function Monster_mt:Pos() local o = self.view:Offset(4) if o ~= 0 then local x = o + self.view.pos local obj = require('MyGame.Sample.Vec3').New() obj:Init(self.view.bytes, x) return obj end end function Monster_mt:Mana() local o = self.view:Offset(6) if o ~= 0 then return self.view:Get(flatbuffers.N.Int16, o + self.view.pos) end return 150 end function Monster_mt:Hp() local o = self.view:Offset(8) if o ~= 0 then return self.view:Get(flatbuffers.N.Int16, o + self.view.pos) end return 100 end function Monster_mt:Name() local o = self.view:Offset(10) if o ~= 0 then return self.view:String(o + self.view.pos) end end function Monster_mt:Inventory(j) local o = self.view:Offset(14) if o ~= 0 then local a = self.view:Vector(o) return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) end return 0 end function Monster_mt:InventoryLength() local o = self.view:Offset(14) if o ~= 0 then return self.view:VectorLen(o) end return 0 end function Monster_mt:Color() local o = self.view:Offset(16) if o ~= 0 then return self.view:Get(flatbuffers.N.Int8, o + self.view.pos) end return 2 end function Monster_mt:Weapons(j) local o = self.view:Offset(18) if o ~= 0 then local x = self.view:Vector(o) x = x + ((j-1) * 4) x = self.view:Indirect(x) local obj = require('MyGame.Sample.Weapon').New() obj:Init(self.view.bytes, x) return obj end end function Monster_mt:WeaponsLength() local o = self.view:Offset(18) if o ~= 0 then return self.view:VectorLen(o) end return 0 end function Monster_mt:EquippedType() local o = self.view:Offset(20) if o ~= 0 then return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos) end return 0 end function Monster_mt:Equipped() local o = self.view:Offset(22) if o ~= 0 then local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0) self.view:Union(obj, o) return obj end end function Monster.Start(builder) builder:StartObject(10) end function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end function Monster.AddColor(builder, color) builder:PrependInt8Slot(6, color, 2) end function Monster.AddWeapons(builder, weapons) builder:PrependUOffsetTRelativeSlot(7, weapons, 0) end function Monster.StartWeaponsVector(builder, numElems) return builder:StartVector(4, numElems, 4) end function Monster.AddEquippedType(builder, equippedType) builder:PrependUint8Slot(8, equippedType, 0) end function Monster.AddEquipped(builder, equipped) builder:PrependUOffsetTRelativeSlot(9, equipped, 0) end function Monster.End(builder) return builder:EndObject() end return Monster -- return the module
bsd-2-clause
Sevenanths/boson-t-nouveau
NewBosonT/NewBosonT/bin/Debug/boson/data/scan.lua
2
3181
local hscan_line = generate_hlightning(33) local speed = 2 function make_hscan(level) if level.generating then return end local y_error1 = -0.5 local y_error2 = man_height + 0.5 local x_error = config.platform_width_scale * 0.4 local player = level.player local y = config.level_center_y local x = 0 local z1 = -level.z - 800 local inner_cannon = models.cannon_inner:Rotate(0) local outer_cannon = models.cannon_outer:Rotate(0) local rotation_speed = math.random() * 2 - 1 local angle = (math.random(8) - 1) * 45 outer_cannon = outer_cannon:Scale(0):Translate(x, y, z1) inner_cannon = inner_cannon:Scale(0):Translate(x, y, z1) outer_cannon:Tween{scale = 33, time = 1, easing = "zoomout"} inner_cannon:Tween{scale = 33, time = 1, easing = "zoomout"} local track = electric_track() local scan_node = hscan_line:Rotate(0):Translate(x, y, z1) level.scan_layer:InsertBack(scan_node) level.scan_layer:Insert(track) local checked = false scan_node:Action(function(dt) local prev_z = level.z - level.speed local scan_z = scan_node.z + speed scan_node.z = scan_z inner_cannon.z = scan_z outer_cannon.z = scan_z angle = angle + rotation_speed if angle > 360 then angle = angle - 360 elseif angle < -360 then angle = angle + 360 end outer_cannon.angle = angle inner_cannon.angle = angle scan_node.angle = angle if -scan_z < (level.z + 2) and not checked and not player.dead then local dx = player.x - x local dy = player.y - y local h = math.sqrt(dx * dx + dy * dy) local theta = angle - player.angle local abs_theta = math.abs(theta) local ray_x, ray_y if abs_theta ~= 90 and abs_theta ~= 270 then local t = tan(theta) ray_y = t * dx + y ray_x = dy / t + x else ray_y = player.y + man_height/2 ray_x = x end if player.y + y_error1 < ray_y and ray_y < player.y + y_error2 or player.x > ray_x - x_error and player.x < ray_x + x_error then if player.artifact and player.artifact.is_shield_up then player.artifact.shield_effect() player.energy = player.energy - 0.3 if player.energy < 0 then player.energy = 0 end else player.die("scan") end end checked = true end if -scan_z < level.z - 2 then level.scan_layer:Remove(scan_node) track:Tween{gain = 0, time = 2, action = function() track:Stop() level.scan_layer:Remove(track) end} level.solids_layer:Remove(outer_cannon) level.glowing_layer:Remove(inner_cannon) end end) level.solids_layer:InsertBack(outer_cannon) level.glowing_layer:InsertBack(inner_cannon) end
gpl-2.0
mofax/cardpeek
dot_cardpeek_dir/scripts/e-passport.lua
16
19873
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009-2013 by 'L1L1' -- -- Cardpeek is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- require("lib.tlv") local SSC local KM_ENC local KM_MAC local KS_ENC local KS_MAC local TEST=false function epass_inc_SSC() local i=7 local e while i>=0 do SSC:set(i,SSC:get(i)+1) if SSC:get(i)~=0 then break end i=i-1 end --print("SSC: ",#SSC,SSC) return true end function epass_key_derivation(seed) local SHA1 local D local Kenc local Kmac SHA1 = crypto.create_context(0x0030) D = bytes.concat(seed, bytes.new(8,"00 00 00 01")) Kenc = crypto.digest(SHA1,D) D = bytes.concat(seed, bytes.new(8,"00 00 00 02")) Kmac = crypto.digest(SHA1,D) return bytes.sub(Kenc,0,15),bytes.sub(Kmac,0,15) end function epass_create_master_keys(mrz) local pass_no = string.sub(mrz,1,10) local pass_bd = string.sub(mrz,14,20) local pass_ed = string.sub(mrz,22,28) local mrz_info = pass_no..pass_bd..pass_ed; local hash local SHA1 SHA1 = crypto.create_context(0x0030); hash = crypto.digest(SHA1,bytes.new_from_chars(mrz_info)) KM_ENC, KM_MAC = epass_key_derivation(bytes.sub(hash,0,15)) return true end function epass_create_session_keys() local sw, resp local rnd_icc local rnd_ifd local k_ifd = bytes.new(8,"0B 79 52 40 CB 70 49 B0 1C 19 B3 3E 32 80 4F 0B") local S local iv = bytes.new(8,"00 00 00 00 00 00 00 00") local TDES_CBC = crypto.create_context(crypto.ALG_DES2_EDE_CBC+crypto.PAD_ZERO,KM_ENC); local CBC_MAC = crypto.create_context(crypto.ALG_ISO9797_M3+crypto.PAD_ISO9797_P2,KM_MAC); local e_ifd local m_ifd rnd_ifd = bytes.new(8,"01 23 45 67 89 AB DC FE") sw, rnd_icc = card.send(bytes.new(8,"00 84 00 00 08")) if (sw~=0x9000) then return false end S = rnd_ifd .. rnd_icc .. k_ifd e_ifd = crypto.encrypt(TDES_CBC,S,iv) m_ifd = crypto.mac(CBC_MAC,e_ifd) cmd_data = e_ifd..m_ifd sw, resp = card.send(bytes.new(8,"00 82 00 00 28",cmd_data,0x28)) if (sw==0x6300) then log.print(log.WARNING,"Perhaps you didn't enter the right MRZ data for this passport") end if (sw~=0x9000) then return false end R = crypto.decrypt(TDES_CBC,bytes.sub(resp,0,31),iv) k_icc = bytes.sub(R,16,31) k_seed = bytes.new(8) for i=0,15 do k_seed = bytes.concat(k_seed,bit.XOR(k_ifd:get(i),k_icc:get(i))) end SSC = bytes.sub(rnd_icc,4,7)..bytes.sub(rnd_ifd,4,7) KS_ENC, KS_MAC = epass_key_derivation(k_seed) return true end function epass_select(EF) local cmdheader = bytes.new(8,"0C A4 02 0C") local cmdbody = bytes.new(8,bit.SHR(EF,8),bit.AND(EF,0xFF)) local TDES_CBC = crypto.create_context(crypto.ALG_DES2_EDE_CBC+crypto.PAD_OPT_80_ZERO,KS_ENC) local CBC_MAC = crypto.create_context(crypto.ALG_ISO9797_M3+crypto.PAD_ISO9797_P2,KS_MAC) local iv = bytes.new(8,"00 00 00 00 00 00 00 00") local DO87, DO8E local command local DO99 M = bytes.concat("01",crypto.encrypt(TDES_CBC,cmdbody,iv)) DO87 = asn1.join(0x87,M) epass_inc_SSC() N = bytes.concat(SSC,cmdheader,"80 00 00 00",DO87) CC = crypto.mac(CBC_MAC,N) DO8E = asn1.join(0x8E,crypto.mac(CBC_MAC,N)) command=bytes.concat(cmdheader,(#DO87+#DO8E),DO87,DO8E,0) sw, resp = card.send(command) epass_inc_SSC() if sw~=0x9000 then return sw, resp end tag_99, value_99, rest = asn1.split(resp) tag_8E, value_8E, rest = asn1.split(rest) if tag_99~=0x99 then log.print(log.WARNING,"Expected tag 99 in card response") return 0x6FFF end if tag_8E~=0x8E then log.print(log.WARNING,"Expected tag 8E in card response") return 0x6FFF end sw = 0+bytes.tonumber(value_99) N = SSC..asn1.join(tag_99,value_99) CC = crypto.mac(CBC_MAC,N) if value_8E~=CC then log.print(log.WARNING,"Failed to verify MAC in response") end return sw, resp end function epass_read_binary(start,len) local cmdheader = bytes.new(8,"0C B0", bit.SHR(start,8),bit.AND(start,0xFF)) local CBC_MAC = crypto.create_context(crypto.ALG_ISO9797_M3+crypto.PAD_ISO9797_P2,KS_MAC) local TDES_CBC = crypto.create_context(crypto.ALG_DES2_EDE_CBC+crypto.PAD_OPT_80_ZERO,KS_ENC) local DO97,D08E local value_87 local iv = bytes.new(8,"00 00 00 00 00 00 00 00") DO97 = bytes.new(8,0x97,01,len) epass_inc_SSC() DO8E = asn1.join(0x8E,crypto.mac(CBC_MAC,bytes.concat(SSC,cmdheader,"80 00 00 00",DO97))) command = bytes.concat(cmdheader,(#DO97+#DO8E),DO97,DO8E,0) sw, resp = card.send(command) epass_inc_SSC() if (sw~=0x9000) and (sw~=0x6282) then return false end tag_87, value_87 = asn1.split(resp) decrypted_data = crypto.decrypt(TDES_CBC,bytes.sub(value_87,1,-1),iv) return sw, bytes.sub(decrypted_data,0,len-1) end function epass_read_file() sw,resp = epass_read_binary(0,4) if sw~=0x9000 then return nil end log.print(log.INFO,"Heading is " .. tostring(resp)) tag, rest = asn1.split_tag(resp) len, rest = asn1.split_length(rest) --io.write("read_file: [") if len>127 then to_read = len + 2 + resp:get(1)-128 else to_read = len + 2 end log.print(log.INFO,"Expecting " .. to_read) result = bytes.new(8) already_read = 0 while to_read>0 do --io.write(".");io.flush() if to_read>0x80 then le = 0x80 else le = to_read end sw, resp = epass_read_binary(already_read,le) if sw~=0x9000 then return result end result = bytes.concat(result,resp) already_read = already_read + #resp to_read = to_read - #resp end --io.write("] "..#result.."bytes\n") return result end function ui_parse_version(node,data) local ver = bytes.format(bytes.sub(data,0,1),"%P") local i for i=1,(#data/2)-1 do ver = ver .. "." .. bytes.format(bytes.sub(data,i*2,i*2+1),"%P") end nodes.set_attribute(node,"val",data) nodes.set_attribute(node,"alt",ver) return true end function ui_parse_cstring(node,data) nodes.set_attribute(node,"val",data) if #data>1 then nodes.set_attribute(node,"alt",bytes.format(bytes.sub(data,0,#data-2),"%P")) end end BL_FAC_RECORD_HEADER = { { "Format Identifier", 4, ui_parse_cstring }, { "Format Version", 4, ui_parse_cstring }, { "Length of Record", 4, ui_parse_number }, { "Number of Faces", 2, ui_parse_number } } BL_FAC_INFORMATION = { { "Face Image Block Length", 4, ui_parse_number }, { "Number of Feature Points", 2, ui_parse_number }, { "Gender", 1 , { [0]="Unspecified", [1]="Male", [2]="Female", [3]="Unknown" }}, { "Eye Color", 1, { [0]="Unspecified", [1]="Black", [2]="Blue", [3]="Brown", [4]="Gray", [5]="Green", [6]="Multi-Coloured", [7]="Pink", [8]="Other or Unknown" }}, { "Hair Color", 1 , { [0]="Unspecified", [1]="Bald", [2]="Black", [3]="Blonde", [4]="Brown", [5]="Gray", [6]="White", [7]="Red", [8]="Green", [9]="Blue", [255]="Other or Unknown" }}, { "Feature Mask", 3 }, { "Expression", 2, { [0]="Unspecified", [1]="Neutral", [2]="Smile with closed mouth", [3]="Smile with open mouth", [4]="Raised eyebrows", [5]="Eyes looking away", [6]="Squinting", [7]="Frowning" }}, { "Pose Angle", 3 }, { "Pose Angle Uncertainty", 3 } } BL_FAC_FEATURE_POINT = { { "Feature Type", 1 }, { "Feature Point", 1 }, { "Horizontal Position (x)", 2 }, { "Vertical Position (y)", 2 }, { "Reserved", 2 } } BL_FAC_IMAGE_INFORMATION = { { "Face Image Type", 1 }, { "Image Data Type", 1 }, { "Width", 2, ui_parse_number }, { "Height", 2, ui_parse_number }, { "Image Color Space", 1 }, { "Source Type", 1 }, { "Device Type", 2 }, { "Quality", 2 } } BL_FIR_GENERAL_RECORD_HEADER = { { "Format Identifier", 4, ui_parse_cstring }, { "Version Number", 4, ui_parse_cstring }, { "Record Length", 6, ui_parse_number }, { "Vendor ID", 2 }, { "Scanner ID", 2 }, { "Number of fingers/palms", 1, ui_parse_number }, { "Scale Units", 1 }, { "Horizontal Scan Resolution", 2, ui_parse_number }, { "Vertical Scan Resolution", 2, ui_parse_number }, { "Horizontal Image Resolution", 2, ui_parse_number }, { "Vertical Image Resolution", 2, ui_parse_number }, { "Pixel Depth", 1 }, { "Image Compression Algorithm", 1, { [1]="Uncompressed – bit packed", [2]="Compressed – WSQ", [3]="Compressed – JPEG", [4]="Compressed – JPEG2000", [5]="PNG" }}, { "Reserved", 2 } } BL_FIR_IMAGE_RECORD_HEADER = { { "Length of finger data block", 4, ui_parse_number }, { "Finger/palm position", 1, { [0]="Unknown", [1]="Right thumb", [2]="Right index finger", [3]="Right middle finger", [4]="Right ring finger", [5]="Right little finger", [6]="Left thumb", [7]="Left index finger", [8]="Left middle finger", [9]="Left ring finger", [10]="Left little finger", [11]="Plain right thumb", [12]="Plain left thumb", [13]="Plain right four fingers", [14]="Plain left four fingers", [15]="Plain thumbs (2)" }}, { "Count of views", 1, ui_parse_number }, { "View number", 1, ui_parse_number }, { "Finger/palm image quality", 1 }, { "Impression type", 1 }, { "Horizontal line length", 2, ui_parse_number }, { "Vertical line length", 2, ui_parse_number }, { "Reserved", 1 } } function ui_parse_block(node,format,data,pos) local ITEM local block local i,v local index for i,v in ipairs(format) do ITEM = node:append({ classname="item", label=v[1], id=i-1, size=v[2] }) block = bytes.sub(data,pos,pos+v[2]-1) if v[3]~=nil then if type(v[3])=="function" then if v[3](ITEM,block)==false then return nil end elseif type(v[3])=="table" then index = bytes.tonumber(block) nodes.set_attribute(ITEM,"val",block) if v[3][index] then nodes.set_attribute(ITEM,"alt",v[3][index]) else nodes.set_attribute(ITEM,"alt",index) end else return nil end else nodes.set_attribute(ITEM,"val",block) end pos = pos + v[2] end return pos end FAC_FORMAT_IDENTIFIER = bytes.new(8,"46414300") FIR_FORMAT_IDENTIFIER = bytes.new(8,"46495200") function ui_parse_biometry_fac(node,data) local BLOCK local SUBBLOCK local SUBSUBBLOCK local SUBSUBSUBBLOCK local index = 0 local num_faces local num_features local block_length local block_start local image_len local i,j num_faces = bytes.tonumber(bytes.sub(data,12,13)) BLOCK = node:append({ classname="item", label="Facial Record Header" }) index = ui_parse_block(BLOCK,BL_FAC_RECORD_HEADER,data,index) if index==nil then log.print(log.ERROR,"Failed to parse facial header information") return false end BLOCK = node:append({ classname="item", label="Facial Data Records" }) for i = 1,num_faces do block_start = index block_length = bytes.tonumber(bytes.sub(data,index,index+3)) num_features = bytes.tonumber(bytes.sub(data,index+4,index+5)) SUBBLOCK = BLOCK:append({ classname="item", label="Facial Record Data", id=i, size=block_length }) SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Facial Information" }) index = ui_parse_block(SUBSUBBLOCK,BL_FAC_INFORMATION,data,index) if index==nil then log.print(log.ERROR,"Failed to parse facial information") return false end if num_features>0 then SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Feature points" }) for j=1,num_features do SUBSUBSUBBLOCK = node:append({ classname="item", label="Feature Point", id=j }) index = ui_parse_block(SUBSUBSUBBLOCK,BL_FEATURE_POINT,data,index) if index==nil then log.print(log.ERROR,"Failed to parse facial feature information") return false end end end SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Image Information" }) index = ui_parse_block(SUBSUBBLOCK,BL_FAC_IMAGE_INFORMATION,data,index) if index==nil then log.print(log.ERROR,"Failed to parse facial image information") return false end image_len = block_length-(index-block_start) SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Image Data", size=image_len }) nodes.set_attribute(SUBSUBBLOCK,"val",bytes.sub(data,index,index+image_len-1)) if image_len>2 and bytes.sub(data,index,index+1) == bytes.new(8,"FF D8") then nodes.set_attribute(SUBSUBBLOCK,"mime-type","image/jpeg") elseif image_len>6 and bytes.sub(data,index,index+5) == bytes.new(8,"00 00 00 0C 6A 50") then nodes.set_attribute(SUBSUBBLOCK,"mime-type","image/jp2") else log.print(log.WARNING,"Could not identify facial image format.") end index = index + image_len end return true end function ui_parse_biometry_fir(node,data) local BLOCK local SUBBLOCK local SUBSUBBLOCK local index = 0 local num_images local record_size local record_start local image_size local i BLOCK = node:append({ classname="item", label="Finger General Record Header" }) index = ui_parse_block(BLOCK,BL_FIR_GENERAL_RECORD_HEADER,data,index) if index==nil then log.print(log.ERROR,"Failed to parse finger general record header information") return false end num_images = bytes.tonumber(bytes.sub(data,18,18)) BLOCK = node:append({ classname="item", label="Finger Images" }) for i=1,num_images do record_size = bytes.tonumber(bytes.sub(data,index,index+3)) record_start = index SUBBLOCK = BLOCK:append({ classname="item", label="Finger Image", id=i, size=record_size }) SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Finger Image Record Header" }) index = ui_parse_block(SUBSUBBLOCK,BL_FIR_IMAGE_RECORD_HEADER,data,index) if index==nil then log.print(log.ERROR,"Failed to parse finger image record header information") return false end image_size = record_size-(index-record_start) SUBSUBBLOCK = SUBBLOCK:append({ classname="item", label="Finger Image Data" }) nodes.set_attribute(SUBSUBBLOCK,"val",bytes.sub(data,index,index+image_size-1)) index = index + image_size end return true end function ui_parse_biometry(node,data) local tag = bytes.sub(data,0,3) if tag==FAC_FORMAT_IDENTIFIER then ui_parse_biometry_fac(node,data) elseif tag==FIR_FORMAT_IDENTIFIER then ui_parse_biometry_fir(node,data) else nodes.set_attribute(node,"val",data) end return true end AID_MRTD = "#A0000002471001" MRP_REFERENCE = { ['5F01'] = { "LDS Version Number", ui_parse_version }, ['5F08'] = { "Date of birth (truncated)" }, ['5F1F'] = { "MRZ data elements", ui_parse_printable }, ['5F2E'] = { "Biometric data block", ui_parse_biometry }, ['5F36'] = { "Unicode Version number", ui_parse_version }, ['60'] = { "Common Data Elements" }, ['61'] = { "Template for MRZ Data Group" }, ['63'] = { "Template for finger biometric Data Group" }, ['65'] = { "Template for digitized facial image" }, ['67'] = { "Template for digitized signature or usual mark" }, ['68'] = { "Template for machine assisted security -- Encoded data" }, ['69'] = { "Template for machine assisted security -- Structure" }, ['6A'] = { "Template for machine assisted security -- Substance" }, ['6B'] = { "Template for additional personal details" }, ['6C'] = { "Template for additional document details" }, ['6D'] = { "Optional details" }, ['6E'] = { "Reserved for future use" }, ['70'] = { "Person to notify" }, ['75'] = { "Template for facial biometric Data Group" }, ['76'] = { "Template for iris (eye) biometric template" }, ['77'] = { "Security data (CMD/RFC 3369)" }, ['7F2E'] = { "Biometric data block (enciphered)" }, ['7F60'] = { "Biometric Information Template" }, ['7F61'] = { "Biometric Information Group Template" }, ['7F61/2'] = { "Number of instances" }, ['A1'] = { "Biometric Header Template" }, ['A1/80'] = { "ICAO header version" }, ['A1/81'] = { "Biometric type" }, ['A1/82'] = { "Biometric feature" }, ['A1/83'] = { "Creation date and time" }, ['A1/84'] = { "Validity period" }, ['A1/86'] = { "Creator of the biometric reference data (PID)" }, ['A1/87'] = { "Format owner" }, ['A1/88'] = { "Format type" } } FILES = { { ['FID']=0x011E, ['name']='EF.COM' }, { ['FID']=0x0101, ['name']='EF.DG1' }, { ['FID']=0x0102, ['name']='EF.DG2' }, { ['FID']=0x0103, ['name']='EF.DG3' }, { ['FID']=0x0104, ['name']='EF.DG4' }, { ['FID']=0x0105, ['name']='EF.DG5' }, { ['FID']=0x0106, ['name']='EF.DG6' }, { ['FID']=0x0107, ['name']='EF.DG7' }, { ['FID']=0x0108, ['name']='EF.DG8' }, { ['FID']=0x0109, ['name']='EF.DG9' }, { ['FID']=0x010A, ['name']='EF.DG10' }, { ['FID']=0x010B, ['name']='EF.DG11' }, { ['FID']=0x010C, ['name']='EF.DG12' }, { ['FID']=0x010D, ['name']='EF.DG13' }, { ['FID']=0x010E, ['name']='EF.DG14' }, { ['FID']=0x010F, ['name']='EF.DG15' }, { ['FID']=0x0110, ['name']='EF.DG16' }, { ['FID']=0x011D, ['name']='EF.SOD' } } local MRZ_DATA="" repeat MRZ_DATA = ui.readline("Enter the code from the lower MRZ data (printed inside the passport)",44,MRZ_DATA) if MRZ_DATA==nil then break end if #MRZ_DATA<28 then ui.question("You must enter at least 28 characters",{"OK"}) end until #MRZ_DATA>=28 if MRZ_DATA then if card.connect() then local ke,km,i,v,r CARD = card.tree_startup("e-passport") sw, resp = card.select(AID_MRTD,0) APP = CARD:append({classname="application", label="application", id=AID_MRTD}) if #resp>0 then tlv_parse(APP,resp) end epass_create_master_keys(MRZ_DATA) if epass_create_session_keys(ke,km) then for i,v in ipairs(FILES) do log.print(log.INFO,"Attempt to select " .. v['name']) sw, resp = epass_select(v['FID']) FID = APP:append({ classname="file", label=v['name'], id=string.format(".%04X",v['FID']) }) FID:append({classname="header", label="header", size=#resp, val=resp }) CONTENT = FID:append({classname="body", label="content" }) if sw==0x9000 then log.print(log.INFO,"Attempt to read from " .. v['name']) r = epass_read_file() if r then nodes.set_attribute(CONTENT,"size",#r) if r:get(0)==0x6D then tag_6D, value_6D = asn1.split(r) TAG6D = CONTENT:append({ classname="item", label="National specific data", size=#value_6D }) nodes.set_attribute(TAG6D,"val",value_6D) else tlv_parse(CONTENT,r,MRP_REFERENCE) end else nodes.set_attribute(CONTENT,"alt","Selected file, but data is not accessible") end else nodes.set_attribute(CONTENT,"alt",string.format("Content not accessible (code %04X)",sw)) end end else ui.question("Could not create session keys. Perhaps you didn't enter the correct MRZ data.",{"OK"}) end card.disconnect() else ui.question("No passport detected in proximity of the reader",{"OK"}) end else log.print(log.ERROR,"Aborted by the user.") end
gpl-3.0
weitjong/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/define.lua
43
1317
-- tolua: define class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: define.lua,v 1.2 1999/07/28 22:21:08 celes Exp $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Define class -- Represents a numeric const definition -- The following filds are stored: -- name = constant name classDefine = { name = '', } classDefine.__index = classDefine setmetatable(classDefine,classFeature) -- register define function classDefine:register (pre) if not self:check_public_access() then return end pre = pre or '' output(pre..'tolua_constant(tolua_S,"'..self.lname..'",'..self.name..');') end -- Print method function classDefine:print (ident,close) print(ident.."Define{") print(ident.." name = '"..self.name.."',") print(ident.." lname = '"..self.lname.."',") print(ident.."}"..close) end -- Internal constructor function _Define (t) setmetatable(t,classDefine) t:buildnames() if t.name == '' then error("#invalid define") end append(t) return t end -- Constructor -- Expects a string representing the constant name function Define (n) return _Define{ name = n } end
mit
osgcc/ryzom
ryzom/common/data_common/r2/r2_features_give_item.lua
3
17110
-- In Translation file -- Category : uiR2EdGiveItem -- -- CreationFrom : uiR2EdGiveItemParameters r2.Features.GiveItemFeature = {} local feature = r2.Features.GiveItemFeature feature.Name="GiveItemFeature" feature.Description="A feature that allows a NPC to give some item(s) to the player" feature.Components = {} feature.Components.GiveItem = { --PropertySheetHeader = r2.getHelpButtonHeader("GiveItem") , BaseClass="LogicEntity", Name="GiveItem", InEventUI = true, Menu="ui:interface:r2ed_feature_menu", DisplayerProperties = "R2::CDisplayerLua", DisplayerPropertiesParams = "giveItemDisplayer", DisplayerUI = "R2::CDisplayerLua", DisplayerUIParams = "defaultUIDisplayer", DisplayerVisual = "R2::CDisplayerVisualEntity", Parameters = {}, ApplicableActions = { "activate", "deactivate"}, Events = { "activation", "deactivation", "mission asked", "succeeded"}, Conditions = { "is active", "is inactive", "is succeeded" }, TextContexts = {}, TextParameters = {}, LiveParameters = {}, Prop = { {Name="InstanceId", Type="String", WidgetStyle="StaticText", Visible = false}, {Name="Components", Type="Table"}, {Name="Name", Type="String", MaxNumChar="32"}, {Name="MissionGiver", Type="RefId", PickFunction="r2:canPickTalkingNpc", SetRefIdFunction="r2:setTalkingNpc"}, {Name="ItemNumber", Type="Number", Category="uiR2EDRollout_ItemsToGive", WidgetStyle="EnumDropDown", Enum={"1", "2", "3"}, DefaultValue="3" }, {Name="Item1Qty", Type="Number", Category="uiR2EDRollout_ItemsToGive", Min="0", DefaultValue="1", Visible= function(this) return this:displayRefId(1) end}, {Name="Item1Id", Type="RefId", WidgetStyle="PlotItem", Category="uiR2EDRollout_ItemsToGive", Visible= function(this) return this:displayRefId(1) end}, {Name="Item2Qty", Type="Number", Category="uiR2EDRollout_ItemsToGive", Min="0", DefaultValue="0", Visible= function(this) return this:displayRefId(2) end}, {Name="Item2Id", Type="RefId", WidgetStyle="PlotItem", Category="uiR2EDRollout_ItemsToGive", Visible= function(this) return this:displayRefId(2) end}, {Name="Item3Qty", Type="Number", Category="uiR2EDRollout_ItemsToGive", Min="0", DefaultValue="0", Visible= function(this) return this:displayRefId(3) end}, {Name="Item3Id", Type="RefId", WidgetStyle="PlotItem", Category="uiR2EDRollout_ItemsToGive", Visible= function(this) return this:displayRefId(3) end}, {Name="ContextualText", Type="String", Category="uiR2EDRollout_TextToSay", MaxNumChar="100"}, {Name="MissionText", Type="String", Category="uiR2EDRollout_TextToSay"}, {Name="MissionSucceedText", Type="String", Category="uiR2EDRollout_TextToSay"}, {Name="BroadcastText", Type="String", Category="uiR2EDRollout_TextToSay", DefaultValue="", DefaultInBase = 1}, {Name="Active", Type="Number", WidgetStyle="Boolean", DefaultValue="1"}, {Name="Repeatable", Type="Number", WidgetStyle="Boolean", DefaultValue="0"} }, getParentTreeNode = function(this) return this:getFeatureParentTreeNode() end, getAvailableCommands = function(this, dest) r2.Classes.LogicEntity.getAvailableCommands(this, dest) -- fill by ancestor this:getAvailableDisplayModeCommands(dest) end, appendInstancesByType = function(this, destTable, kind) assert(type(kind) == "string") --this:delegate():appendInstancesByType(destTable, kind) r2.Classes.LogicEntity.appendInstancesByType(this, destTable, kind) for k, component in specPairs(this.Components) do component:appendInstancesByType(destTable, kind) end end, getSelectBarSons = function(this) return Components end, canHaveSelectBarSons = function(this) return false; end, onPostCreate = function(this) --this:createGhostComponents() if this.User.DisplayProp and this.User.DisplayProp == 1 then r2:setSelectedInstanceId(this.InstanceId) r2:showProperties(this) this.User.DisplayProp = nil end end, pretranslate = function(this, context) r2.Translator.createAiGroup(this, context) end, } local component = feature.Components.GiveItem function component:displayRefId(index) local nbItems = self.ItemNumber + 1 if index <= nbItems then return true end return false end local giveItemDisplayerTable = clone(r2:propertySheetDisplayer()) local oldOnAttrModified = giveItemDisplayerTable.onAttrModified function giveItemDisplayerTable:onAttrModified(instance, attributeName) oldOnAttrModified(self, instance, attributeName) r2:propertySheetDisplayer():onAttrModified(instance, attributeName) if attributeName == "ItemNumber" then local propertySheet = r2:getPropertySheet(instance) local nbRefId = instance.ItemNumber + 1 local i = 1 while i <= 3 do if i > nbRefId then local name = "Item"..tostring(i).."Id" local qty = "Item"..tostring(i).."Qty" r2.requestSetNode(instance.InstanceId, name, r2.RefId("")) r2.requestSetNode(instance.InstanceId, qty, 0) end i = i + 1 end propertySheet.Env.updatePropVisibility() return end end function giveItemDisplayerTable:onSelect(instance, isSelected) r2:logicEntityPropertySheetDisplayer():onSelect(instance, isSelected) end function component:onTargetInstancePreHrcMove(targetAttr, targetIndexInArray) local targetId = self[targetAttr] local tmpInstance = r2:getInstanceFromId(targetId) tmpInstance.User.SelfModified = true end function component:onTargetInstancePostHrcMove(targetAttr, targetIndexInArray) local targetId = self[targetAttr] local tmpInstance = r2:getInstanceFromId(targetId) assert(tmpInstance) if tmpInstance.User.SelfModified and tmpInstance.User.SelfModified == true then if tmpInstance.ParentInstance and tmpInstance.ParentInstance:isKindOf("NpcGrpFeature") then r2.requestSetNode(self.InstanceId, targetAttr, r2.RefId("")) end end end function r2:giveItemDisplayer() return giveItemDisplayerTable -- returned shared displayer to avoid wasting memory end function component:getItems() local str = "" local id = 1 while id <= 3 do local item = self["Item"..tostring(id).."Id"] local item2 = self.Item1Id if (item) then local qt = tonumber(self["Item"..tostring(id).."Qty"]) local plotItem = r2:getInstanceFromId(item) if plotItem then local plotItemSheetId = plotItem.SheetId if str ~= "" then str = str ..";" end local name = r2.getSheetIdName(plotItemSheetId) str = str .. tostring(name)..":"..qt end end id = id + 1 end return str end function component:textAdapter(text) local str = "" local items = {} local qts = {} local id = 1 while id <= 3 do local item = self["Item"..tostring(id).."Id"] local item2 = self.Item1Id if (item) then local qt = tonumber(self["Item"..tostring(id).."Qty"]) qts[id] = qt local plotItem = r2:getInstanceFromId(item) if plotItem then items[id] = plotItem.Name else items[id] = "" end end id = id + 1 end local str = text str=string.gsub (str, "<qt1>", tostring(qts[1])) str=string.gsub (str, "<qt2>", tostring(qts[2])) str=string.gsub (str, "<qt3>", tostring(qts[3])) str=string.gsub (str, "<item1>", tostring(items[1])) str=string.gsub (str, "<item2>", tostring(items[2])) str=string.gsub (str, "<item3>", tostring(items[3])) local mission_giver = "" if self.MissionGiver == nil then return end local npc = r2:getInstanceFromId(self.MissionGiver) if npc then mission_giver = npc.Name end str=string.gsub(str, "<mission_giver>", tostring(mission_giver)) return str end function component:translate(context) r2.Translator.translateAiGroup(self, context) if self.MissionGiver == nil then return end local npc = r2:getInstanceFromId(self.MissionGiver) if not npc then return end local npcGrp = r2.Translator.getRtGroup(context, npc.InstanceId) local rtGrp = r2.Translator.getRtGroup(context, self.InstanceId) local items = self:getItems() do local rtAction = r2.Translator.createAction("if_value_equal", rtGrp.Id, "Active", 1, -- Active r2.Translator.createAction("multi_actions", { r2.Translator.createAction("npc_say", self:textAdapter(self.MissionText), npcGrp.Id ..":"..npc.Name); r2.Translator.createAction("give_item", rtGrp.Id, items, self:textAdapter(self.ContextualText)), r2.Translator.createAction("user_event_trigger", rtGrp.Id, 2) }) ) r2.Translator.translateAiGroupEvent("player_target_npc", npc, context, rtAction) end do local action = r2.Translator.createAction("user_event_trigger", rtGrp.Id, 7) r2.Translator.translateAiGroupEvent("start_of_state" , self, context, action) end do local rtAction1 = r2.Translator.createAction("set_value", rtGrp.Id, "Active", self.Active) local rtAction2 = r2.Translator.createAction("set_value", rtGrp.Id, "v1", self.Repeatable) local rtAction3 = r2.Translator.createAction("set_value", rtGrp.Id, "v2", 0) -- Success local rtAction = r2.Translator.createAction("multi_actions", { rtAction1, rtAction2, rtAction3, } ) r2.Translator.translateAiGroupEvent("user_event_7", self, context, rtAction) end do local rtAction1 = r2.Translator.createAction("set_value", rtGrp.Id, "Active", 1) local rtAction2 = r2.Translator.createAction("set_value", rtGrp.Id, "v1", self.Repeatable) local rtAction3 = r2.Translator.createAction("set_value", rtGrp.Id, "v2", 0) -- Success local rtAction = r2.Translator.createAction("multi_actions", { rtAction1, rtAction2, rtAction3, } ) r2.Translator.translateAiGroupEvent("user_event_4", self, context, rtAction) end do local action1 = r2.Translator.createAction("npc_say", self:textAdapter(self.MissionSucceedText), npcGrp.Id ..":"..npc.Name); local action2 = r2.Translator.createAction("if_value_equal", rtGrp.Id, "v1", 1, -- Repeatable r2.Translator.createAction("multi_actions", { r2.Translator.createAction("set_value", rtGrp.Id, "Active", 1 ) , r2.Translator.createAction("set_value", rtGrp.Id, "v2", 0 ) }) ); local action3 = r2.Translator.createAction("if_value_equal", rtGrp.Id, "v1", 0, -- Not Repeatable r2.Translator.createAction("multi_actions", { r2.Translator.createAction("set_value", rtGrp.Id, "Active", 0 ) , r2.Translator.createAction("set_value", rtGrp.Id, "v2", 1 ), r2.Translator.createAction("user_event_trigger", rtGrp.Id, 5) }) ); local baseAct = r2.Scenario:getBaseAct() local baseActRtGrp = r2.Translator.getRtGroup(context, baseAct.InstanceId) local actionBroadcast = r2.Translator.createAction("broadcast_msg",baseActRtGrp.Id, self:textAdapter(self.BroadcastText) ) local rtAction = r2.Translator.createAction("multi_actions", {action1, action2, action3, actionBroadcast}) r2.Translator.translateAiGroupEvent("user_event_1", self, context, rtAction) end r2.Translator.translateFeatureActivation(self, context) -- ()receiveMissionItems("system_mp.sitem:2;system_mp_choice.sitem:1;system_mp_supreme.sitem:3", "Give some stuff hé!", @groupToNotify); end component.getLogicAction = function(entity, context, action) assert( action.Class == "ActionStep") local component = r2:getInstanceFromId(action.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) return r2.Translator.getFeatureActivationLogicAction(rtNpcGrp, action) end component.getLogicCondition = function(this, context, condition) assert( condition.Class == "ConditionStep") local component = r2:getInstanceFromId(condition.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) if condition.Condition.Type == "is active" then local action1 = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "Active", 1); return action1, action1 elseif condition.Condition.Type == "is inactive" then local action1 = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "Active", 0); return action1, action1 elseif condition.Condition.Type == "is succeeded" then local action1 = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "v2", 1); return action1, action1 else assert(nil) end return nil,nil end component.getLogicEvent = function(this, context, event) assert( event.Class == "LogicEntityAction") local component = this -- r2:getInstanceFromId(event.Entity) assert(component) local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId) assert(rtNpcGrp) local eventType = tostring(event.Event.Type) local eventHandler, lastCondition = nil, nil if eventType == "mission asked" then return r2.Translator.getComponentUserEvent(rtNpcGrp, 2) elseif eventType == "succeeded" then return r2.Translator.getComponentUserEvent(rtNpcGrp, 1) end return r2.Translator.getFeatureActivationLogicEvent(rtNpcGrp, event) end component.createComponent = function(x, y) local comp = r2.newComponent("GiveItem") assert(comp) local contextualText = i18n.get("uiR2EdGiveItem_ContextualText"):toUtf8() local missionText = i18n.get("uiR2EdGiveItem_MissionText"):toUtf8() local missionSucceedText = i18n.get("uiR2EdGiveItem_MissionSucceededText"):toUtf8() local broadcastText = i18n.get("uiR2EdGiveItem_BroadcastText"):toUtf8() comp.Base = r2.Translator.getDebugBase("palette.entities.botobjects.bot_request_item") comp.Name = r2:genInstanceName(i18n.get("uiR2EDGiveItem")):toUtf8() comp.ItemNumber = 0 comp.ContextualText = contextualText comp.MissionText = missionText comp.MissionSucceedText = missionSucceedText comp.BroadcastText = broadcastText comp.Position.x = x comp.Position.y = y comp.Position.z = r2:snapZToGround(x, y) -- comp.ItemQty = 1 comp._Seed = os.time() return comp end component.create = function() if not r2:checkAiQuota() then return end local function paramsOk(resultTable) r2.requestNewAction(i18n.get("uiR2EDNewGiveItemFeature")) local x = tonumber( resultTable["X"] ) local y = tonumber( resultTable["Y"] ) local showAgain = tonumber(resultTable["Display"]) if showAgain == 1 then r2.setDisplayInfo("GiveItemForm", 0) else r2.setDisplayInfo("GiveItemForm", 1) end if not x or not y then debugInfo("Can't create Component") return end local component = feature.Components.GiveItem.createComponent( x, y) r2:setCookie(component.InstanceId, "DisplayProp", 1) r2.requestInsertNode(r2:getCurrentAct().InstanceId, "Features", -1, "", component) end local function paramsCancel() debugInfo("Cancel form for 'GiveItem' creation") end local function posOk(x, y, z) debugInfo(string.format("Validate creation of 'GiveItem' at pos (%d, %d, %d)", x, y, z)) if r2.mustDisplayInfo("GiveItem") == 1 then r2.displayFeatureHelp("GiveItem") end r2.requestNewAction(i18n.get("uiR2EDNewGiveItemFeature")) local component = feature.Components.GiveItem.createComponent( x, y) r2:setCookie(component.InstanceId, "DisplayProp", 1) r2.requestInsertNode(r2:getCurrentAct().InstanceId, "Features", -1, "", component) end local function posCancel() debugInfo("Cancel choice 'GiveItem' position") end local creature = r2.Translator.getDebugCreature("object_component_bot_request_item.creature") r2:choosePos(creature, posOk, posCancel, "createFeatureGiveItem") end function component:registerMenu(logicEntityMenu) local name = i18n.get("uiR2EdGiveItem") logicEntityMenu:addLine(ucstring(name), "lua", "", "GiveItem") end function component:getLogicTranslations() local logicTranslations = { ["ApplicableActions"] = { ["activate"] = { menu=i18n.get( "uiR2AA0Activate" ):toUtf8(), text=i18n.get( "uiR2AA1Activate" ):toUtf8()}, ["deactivate"] = { menu=i18n.get( "uiR2AA0Deactivate" ):toUtf8(), text=i18n.get( "uiR2AA1Deactivate" ):toUtf8()} }, ["Events"] = { ["activation"] = { menu=i18n.get( "uiR2Event0Activation" ):toUtf8(), text=i18n.get( "uiR2Event1Activation" ):toUtf8()}, ["deactivation"] = { menu=i18n.get( "uiR2Event0Deactivation" ):toUtf8(), text=i18n.get( "uiR2Event1Deactivation" ):toUtf8()}, ["mission asked"] = { menu=i18n.get( "uiR2Event0MissionGiven" ):toUtf8(), text=i18n.get( "uiR2Event1MissionGiven" ):toUtf8()}, ["wait validation"] = { menu=i18n.get( "uiR2Event0TaskWaitValidation" ):toUtf8(), text=i18n.get( "uiR2Event1TaskWaitValidation" ):toUtf8()}, ["succeeded"] = { menu=i18n.get( "uiR2Event0TaskSuccess" ):toUtf8(), text=i18n.get( "uiR2Event1TaskSuccess" ):toUtf8()}, }, ["Conditions"] = { ["is active"] = { menu=i18n.get( "uiR2Test0Active" ):toUtf8(), text=i18n.get( "uiR2Test1Active" ):toUtf8()}, ["is inactive"] = { menu=i18n.get( "uiR2Test0Inactive" ):toUtf8(), text=i18n.get( "uiR2Test1Inactive" ):toUtf8()}, ["is succeeded"] = { menu=i18n.get( "uiR2Test0TaskSuccess" ):toUtf8(), text=i18n.get( "uiR2Test1TaskSuccess" ):toUtf8()}, } } return logicTranslations end r2.Features["GiveItem"] = feature
agpl-3.0
cochrane/OpenTomb
scripts/level/tr1/LEVEL2.lua
2
1111
-- OPENTOMB STATIC MESH COLLISION SCRIPT -- FOR TOMB RAIDER, LEVEL2 (CAVES) print("Level script loaded (LEVEL1.lua)"); -- STATIC COLLISION FLAGS ------------------------------------------------------ -------------------------------------------------------------------------------- static_tbl[06] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant static_tbl[08] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant static_tbl[10] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Wood barrier static_tbl[33] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Bridge part 1 static_tbl[34] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Bridge part 2 static_tbl[38] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Door frame static_tbl[39] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Wall bricks static_tbl[43] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Icicle
lgpl-3.0
mamadantimageeee/antimage
bot/seedbot.lua
1
10314
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 = '2' -- 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) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end 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", "admin" }, sudo_users = {225604010,103649648,143723991,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 Our team! Alphonse (@Iwals) I M /-\ N (@Imandaneshi) Siyanew (@Siyanew) Rondoozle (@Potus) Seyedan (@Seyedan25) Special thanks to: Juan Potato Siyanew Topkecleon Vamptacus Our channels: English: @TeleSeedCH Persian: @IranSeed ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [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 [grupo_id] Kick all memebers and delete group !kill realm [realm_id] 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 Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin 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 ]], 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 Get commands list !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 !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin 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(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) 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
plinkopenguin/wire-extras
lua/entities/gmod_wire_useholoemitter/cl_init.lua
1
6610
include( "shared.lua" ); CreateClientConVar("cl_wire_holoemitter_minfaderate",10,true,false); // mats local matbeam = Material( "tripmine_laser" ); local matpoint = Material( "sprites/gmdm_pickups/light" ); // init function ENT:Initialize( ) // point list self.PointList = {}; self.LastClear = self:GetNetworkedBool("Clear"); // active point self.ActivePoint = Vector( 0, 0, 0 ); // boundry. self.Boundry = 64; end // calculate point function ENT:CalculatePixelPoint( pos, emitterPos, fwd, right, up ) // calculate point return emitterPos + ( up * pos.z ) + ( fwd * pos.x ) + ( right * pos.y ); end // think function ENT:Think( ) // read point. local point = Vector( self:GetNetworkedFloat( "X" ), self:GetNetworkedFloat( "Y" ), self:GetNetworkedFloat( "Z" ) ); lastclear = self:GetNetworkedInt("Clear") if(lastclear != self.LastClear) then self.PointList = {} self.LastClear = lastclear end // did the point differ from active point? if( point != self.ActivePoint && self:GetNetworkedBool( "Active" ) ) then // fetch color. local a = self:GetColor().a; // store this point inside the point list local tempfaderate if (game.SinglePlayer()) then tempfaderate = math.Clamp( self:GetNetworkedFloat( "FadeRate" ), 0.1, 255 ) else -- Due to a request, in Multiplayer, the people can controle this with a CL side cvar (aVoN) local minfaderate = GetConVarNumber("cl_wire_holoemitter_minfaderate") or 10; tempfaderate = math.Clamp( self:GetNetworkedFloat( "FadeRate" ),minfaderate, 255 ) end table.insert( self.PointList, { pos = self.ActivePoint, alpha = a, faderate = tempfaderate } ); // store new active point self.ActivePoint = point; end end // draw function ENT:Draw( ) // render model self:DrawModel(); // are we rendering? if( !self:GetNetworkedBool( "Active" ) ) then return; end // read emitter. local emitter = self:GetNetworkedEntity( "grid" ); if( !emitter || !emitter:IsValid() ) then return; end // calculate emitter position. local fwd = emitter:GetForward(); local right = emitter:GetRight(); local up = emitter:GetUp(); local pos = emitter:GetPos() + up * 64; local usegps = emitter:GetNetworkedBool( "UseGPS" ) // draw beam? local drawbeam = self:GetNetworkedBool( "ShowBeam" ); local groundbeam = self:GetNetworkedBool( "GroundBeam" ); // read point size local size = self:GetNetworkedFloat( "PointSize" ); local beamsize = size * 0.25; // read color local color = self:GetColor(); self:SetRenderBounds( Vector()*-16384, Vector()*16384 ) // calculate pixel point. local pixelpos if (usegps == true) then pixelpos = self.ActivePoint; else pixelpos = self:CalculatePixelPoint( self.ActivePoint, pos, fwd, right, up ); end // draw active point - beam if( drawbeam && groundbeam) then render.SetMaterial( matbeam ); render.DrawBeam( self:GetPos(), pixelpos, beamsize, 0, 1, color ); end // draw active point - sprite render.SetMaterial( matpoint ); render.DrawSprite( pixelpos, size, size, color ); // draw fading points. local point, lastpos, i = nil, pixelpos; local newlist = {} for i = table.getn( self.PointList ), 1, -1 do // easy access local point = self.PointList[i]; // I'm doing this here, to remove that extra loop in ENT:Think. // fade away point.alpha = point.alpha - point.faderate * FrameTime(); // die? if( point.alpha <= 0 ) then table.remove( self.PointList, i ); else table.insert( newlist, { pos = point.pos, alpha = point.alpha, faderate = point.faderate } ); // calculate pixel point. local pixelpos if (usegps == true) then pixelpos = point.pos else pixelpos = self:CalculatePixelPoint( point.pos, pos, fwd, right, up ); end // calculate color. local color = Color( r, g, b, point.alpha ); // draw active point - beam if( drawbeam ) then if (groundbeam) then render.SetMaterial( matbeam ); render.DrawBeam( self:GetPos(), pixelpos, beamsize, 0, 1, color ); end render.SetMaterial( matbeam ) render.DrawBeam( lastpos, pixelpos, beamsize * 2, 0, 1, color ); lastpos = pixelpos; end // draw active point - sprite render.SetMaterial( matpoint ); render.DrawSprite( pixelpos, size, size, color ); end end self.PointList = newlist end function Player_EyeAngle(ply) EyeTrace = ply:GetEyeTrace() StartPos = EyeTrace.StartPos EndPos = EyeTrace.HitPos Distance = StartPos:Distance(EndPos) Temp = EndPos - StartPos return Temp:Angle() end local function HoloPressCheck( ply, key ) if (key == IN_USE) then ply_EyeAng = Player_EyeAngle(ply) ply_EyeTrace = ply:GetEyeTrace() ply_EyePos = ply_EyeTrace.StartPos emitters = ents.FindByClass("gmod_wire_useholoemitter") if (#emitters > 0) then local ShortestDistance = 200 local LastX = 0 local LastY = 0 local LastZ = 0 local LastEnt = 0 for _,v in ipairs( emitters ) do local emitter = v.Entity:GetNetworkedEntity( "grid" ); if (v.Entity:GetNetworkedBool( "Active" )) then local fwd = emitter:GetForward(); local right = emitter:GetRight(); local up = emitter:GetUp(); local pos = emitter:GetPos() + (up*64) count = table.getn( v.PointList ) for i = count,1,-1 do point = v.PointList[i]; if (v.Entity:GetNetworkedBool( "UseGPS" )) then pixelpos = point.pos else pixelpos = v:CalculatePixelPoint( point.pos, pos, fwd, right, up ); end ObjPos = Vector(pixelpos.x,pixelpos.y,pixelpos.z) AbsDist = ply_EyePos:Distance(ObjPos) if (AbsDist <= ShortestDistance) then TempPos = ObjPos - ply_EyePos AbsAng = TempPos:Angle() PitchDiff = math.abs(AbsAng.p - ply_EyeAng.p) YawDiff = math.abs(AbsAng.y - ply_EyeAng.y) if (YawDiff <= 5 && PitchDiff <= 5) then ShortestDistance = AbsDist LastX = point.pos.x LastY = point.pos.y LastZ = point.pos.z LastEnt = v:EntIndex() end end end end end if (LastEnt > 0) then RunConsoleCommand("HoloInteract",LastEnt,LastX,LastY,LastZ) end end end end hook.Add( "KeyPress", "HoloPress", HoloPressCheck )
gpl-3.0
sealgair/Jolly-Xanthar
mobs/human.lua
1
2049
require 'utils' require 'mobs.mob' require 'weapons.bolter' require 'weapons.laser' require 'weapons.forcefield' Weapons = { [Bolter.name] = Bolter, [LaserRifle.name] = LaserRifle, [ForceField.name] = ForceField, } Human = Mob:extend('Human') function Human:init(coord, opts) if opts == nil then opts = {} end local palette = love.graphics.newImage('assets/palette.png'):getData() local choices = palette:getHeight() local toColors = opts.colors if toColors == nil then toColors = {} local seen = {} for i = 1,3 do local c repeat c = math.random(0, choices - 1) until seen[c] == nil seen[c] = true table.insert(toColors, {palette:getPixel(0, c)}) table.insert(toColors, {palette:getPixel(1, c)}) end end self.colors = toColors self.shader = palletSwapShader({ {255, 0, 0}, {128, 0, 0}, {0, 255, 0}, {0, 128, 0}, {0, 0, 255}, {0, 0, 128}, }, toColors) Human.super.init(self, { x = coord.x, y = coord.y, confFile = 'assets/mobs/human.json', speed = 50, momentum = 20, stunFactor = 1.5, shader = self.shader }) self.weapons = opts.weapons if self.weapons == nil then self.weapons = {} local allWeapons = {Bolter.name, LaserRifle.name, ForceField.name} local a = math.random(1, #allWeapons) local b repeat b = math.random(1, #allWeapons) until b ~= a self.weapons.a = allWeapons[a] self.weapons.b = allWeapons[b] end self.weapons = map(self.weapons, function(w) return Weapons[w](self) end) if opts.name == nil then local forename = randomLine("assets/names/forenames.txt") local surname = randomLine("assets/names/surnames.txt") self.name = forename .. " " .. surname else self.name = opts.name end self.isFriendly = true end function Human:serialize() return { colors = self.colors, weapons = map(self.weapons, function(w) return w.name end), name = self.name, } end function Human:__tostring() return self.name .. " the human" end
gpl-3.0
rigeirani/sg1
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
mamaddeveloper/uzz
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
masterweb121/telegram-bot
plugins/time.lua
771
2865
-- 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 }
gpl-2.0
MmxBoy/mmxanti2
plugins/time.lua
771
2865
-- 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 }
gpl-2.0
hoelzl/Xbt.lua
src/sci/mcmc/_nuts.lua
2
10457
-------------------------------------------------------------------------------- -- NUTS MCMC sampler. -- -- Copyright (C) 2011-2014 Stefano Peluchetti. All rights reserved. -- -- Features, documentation and more: http://www.scilua.org . -- -- This file is part of the SciLua library, which is released under the MIT -- license: full text in file LICENSE.TXT in the library's root folder. -------------------------------------------------------------------------------- -- TODO: At the moment single cache, algorithm, ecc ecc so nested calls are not -- TODO: possible nor are use of NUTS for sampling subset of the parameters, -- TODO: change when improving MCMC framework. local alg = require "sci.alg" local dist = require "sci.dist" local stat = require "sci.stat" local math = require "sci.math" local xsys = require "xsys" local normald = dist.normal(0, 1) local unifm1p1d = dist.uniform(-1, 1) local exp, log, sqrt, sign, step, min, abs, floor = xsys.from(math, "exp, log, sqrt, sign, step, min, abs, floor") local vec, mat = alg.vec, alg.mat local width = xsys.string.width -- Only leapfrog (for th1, r1) and evalgrad (for grad) modify elements of some -- vector (the newly initialized ones), no vector is modified after -- initialization => it's safe to cache based on reference instead of value for -- the parameters in evalgrad. local cache = { } local invert, factor, correlate, sigestimate, kinectic -- Caching is done based on theta by-ref. Fine as thetas are never mutated. local function evalfgrad(fgrad, theta) local found = cache[theta] if found then return found[1], found[2] else local grad = vec(#theta) -- Newly created grad vector is initialized: local val = fgrad(theta, grad) if not (abs(val) < 1/0) then -- If val is nan or not finite. val = - 1/0 -- No nan allowed. -- Gradient is almost surely nan or not finite: for i=1,#grad do grad[i] = 0 end end cache[theta] = { val, grad } return val, grad end end local function stop_iter(n) local c = 0 return function() c = c + 1 return c >= n end end local function invert(m, sig, mass) if mass == "diagonal" then for i=1,#m do m[i] = 1/sig[i] end else alg.invert(m, sig, "posdef") end end local function factor(mfac, m, mass) if mass == "diagonal" then for i=1,#mfac do mfac[i] = sqrt(m[i]) end else alg.factor(mfac, m, "posdef") end end local function correlate(r, mfac, mass) if mass == "diagonal" then for i=1,#r do r[i] = mfac[i]*r[i] end else alg.mulmv(r, mfac, r) end end local function sigestimate(sig, sigestimator, mass) if mass == "diagonal" then sigestimator:var(sig) else sigestimator:cov(sig) end end local function logpdf(fgrad, theta, r, sig, mass) local n = #r -- Kinetic energy: p^t*M^1*p/2 == p^t*sig*p/2. local sum = 0; if mass == "diagonal" then for i=1,n do sum = sum + r[i]^2*sig[i] end else local t = r:stack().vec(#r) alg.mulmv(t, sig, r) for i=1,n do sum = sum + t[i]*r[i] end r:stack().clear() end local v = evalfgrad(fgrad, theta) - 0.5*sum return v end -- Newly created vectors th1, r1 vectors are initialized: local function leapfrog(fgrad, eps, th0, r0, sig, mass) local n = #r0 local th1, r1 = vec(n), vec(n) -- Leapfrog step: eps*M^-1*esp == eps*sig. if mass == "diagonal" then local _, grad = evalfgrad(fgrad, th0) for i=1,n do r1[i] = r0[i] + 0.5*eps*grad[i] end for i=1,n do th1[i] = th0[i] + eps*sig[i]*r1[i] end local _, grad = evalfgrad(fgrad, th1) for i=1,n do r1[i] = r1[i] + 0.5*eps*grad[i] end else local _, grad = evalfgrad(fgrad, th0) for i=1,n do r1[i] = r0[i] + 0.5*eps*grad[i] end local t = th1:stack().vec(#th1) alg.mulmv(t, sig, r1) for i=1,n do th1[i] = th0[i] + eps*t[i] end th1:stack().clear() local _, grad = evalfgrad(fgrad, th1) for i=1,n do r1[i] = r1[i] + 0.5*eps*grad[i] end end return th1, r1 end local function heuristiceps(rng, fgrad, th0, sig, mass) local dim = #th0 local r0 = vec(dim) local eps = 1 for i=1,#r0 do r0[i] = normald:sample(rng) end local logpdf0 = logpdf(fgrad, th0, r0, sig, mass) local tht, rt = leapfrog(fgrad, eps, th0, r0, sig, mass) local alpha = sign((logpdf(fgrad, tht, rt, sig, mass) - logpdf0) - log(0.5)) while alpha*(logpdf(fgrad, tht, rt, sig, mass) - logpdf0) > alpha*log(0.5) do eps = eps*2^alpha tht, rt = leapfrog(fgrad, eps, th0, r0, sig, mass) end return eps end local function evalsr(sl, thp, thm, rp, rm) local n = #thp local sum1 = 0; for i=1,n do sum1 = sum1 + (thp[i] - thm[i])*rm[i] end; local sum2 = 0; for i=1,n do sum2 = sum2 + (thp[i] - thm[i])*rp[i] end; return sl*step(sum1)*step(sum2) end -- Shorts: m = minus, p = plus, 1 = 1 prime, 2 = 2 primes. -- This function does not modify any of its arguments. -- Also all of the returned arguments are not modified in the recursion. -- As long as the input or returned vectors are *not* modified it's fine to -- work with references that may alias each other (see also caching of fgrad). -- This means that all vectors here are effectively immutable after -- "initialization", which in this context means after being passed to the -- leapfrog function which modifies them. local function buildtree(rng, fgrad, th, r, logu, v, j, eps, th0, r0, sig, dlmax, mass) local dim = #th if j == 0 then local th1, r1 = leapfrog(fgrad, v*eps, th, r, sig, mass) local logpdfv1 = logpdf(fgrad, th1, r1, sig, mass) local n1 = step(logpdfv1 - logu) local s1 = step(dlmax + logpdfv1 - logu) return th1, r1, th1, r1, th1, n1, s1, min(exp(logpdfv1 - logpdf(fgrad, th0, r0, sig, mass)), 1), 1 else local thm, rm, thp, rp, th1, n1, s1, a1, na1 = buildtree(rng, fgrad, th, r, logu, v, j - 1, eps, th0, r0, sig, dlmax, mass) local _, th2, n2, s2, a2, na2 if s1 == 1 then if v == -1 then thm, rm, _, _, th2, n2, s2, a2, na2 = buildtree(rng, fgrad, thm, rm, logu, v, j - 1, eps, th0, r0, sig, dlmax, mass) else _, _, thp, rp, th2, n2, s2, a2, na2 = buildtree(rng, fgrad, thp, rp, logu, v, j - 1, eps, th0, r0, sig, dlmax, mass) end if rng:sample() < n2/(n1 + n2) then th1 = th2 end a1 = a1 + a2 na1 = na1 + na2 s1 = evalsr(s2, thp, thm, rp, rm) n1 = n1 + n2 end return thm, rm, thp, rp, th1, n1, s1, a1, na1 end end -- Work by references on the vectors, only newly created one are modified in -- the leapforg function. Use vectors as read-only. local function nuts(rng, fgrad, theta0, o) local stop = o.stop local stopadapt = o.stopadapt or 1024 if type(stop) == "number" then stop = stop_iter(stop) end if stopadapt ~= 0 and (log(stopadapt)/log(2) ~= floor(log(stopadapt)/log(2) or stopadapt < 64)) then error("stopadapt must be 0 or a power of 2 which is >= 64") end local olstat = o.olstat local delta = o.delta or 0.8 local gamma = o.gamma or 0.05 local t0 = o.t0 or 10 local k = o.k or 0.75 local dlmax = o.deltamax or 1000 local mass = o.mass or "diagonal" local dim = #theta0 local thr0, thr1 = theta0:copy() local r0 = vec(dim) -- m must be precision matrix (Cov^-1) or Var^-1 for diagonal mass case: local sigestimator, sig, mfac, m if mass == "diagonal" then sigestimator, sig, mfac, m = stat.olvar(dim), vec(dim), vec(dim), vec(dim) if o.var then sig = o.var:copy() elseif o.cov then for i=1,dim do sig[i] = o.cov[i][i] end else for i=1,dim do sig[i] = 1/1e3 end end elseif mass == "dense" then sigestimator, sig, mfac, m = stat.olcov(dim), mat(dim, dim), mat(dim, dim), mat(dim, dim) if o.cov then sig = o.cov:copy() elseif o.var then for i=1,dim do sig[i][i] = o.var[i] end else for i=1,dim do for j=1,dim do sig[i][j] = 1/1e3 end end end else error("mass can only be 'diagonal' or 'dense', passed: "..mass) end local varu = 32 invert(m, sig, mass) factor(mfac, m, mass) local eps = o.eps or heuristiceps(rng, fgrad, thr0, sig, mass) local mu = log(10*eps) local madapt, Ht, lepst, leps = 0, 0, 0 local totadapt = 0 while true do for i=1,dim do r0[i] = normald:sample(rng) end correlate(r0, mfac, mass) local logpdfr0 = logpdf(fgrad, thr0, r0, sig, mass) assert(logpdfr0 > -1/0) local logu = log(rng:sample()) + logpdfr0 local thm, thp = thr0, thr0 local rm, rp = r0, r0 local j, n, s = 0, 1, 1 local a, na thr1 = thr0 while s == 1 do local v = sign(unifm1p1d:sample(rng)) local _, th1, n1, s1 if v == -1 then thm, rm, _, _, th1, n1, s1, a, na = buildtree(rng, fgrad, thm, rm, logu, v, j, eps, thr0, r0, sig, dlmax, mass) else _, _, thp, rp, th1, n1, s1, a, na = buildtree(rng, fgrad, thp, rp, logu, v, j, eps, thr0, r0, sig, dlmax, mass) end if s1 == 1 then if rng:sample() < min(n1/n, 1) then thr1 = th1 end end n = n + n1 s = evalsr(s1, thp, thm, rp, rm) j = j + 1 -- Limit tree depth during initial adaptation phase: if totadapt <= stopadapt/2 and j >= 10 then break end end local alpha = a/na if totadapt < stopadapt then totadapt = totadapt + 1 -- Last possible totadapt is stopadapt. madapt = madapt + 1 Ht = (1 - 1/(madapt + t0))*Ht + 1/(madapt + t0)*(delta - alpha) leps = mu - sqrt(madapt)/gamma*Ht -- Log-eps used in adaptation. lepst = (madapt^-k)*leps + (1 - madapt^-k)*lepst -- Optimal log-eps. if totadapt == stopadapt then eps = exp(lepst) else eps = exp(leps) end sigestimator:push(thr1) if totadapt == varu then -- Set mass using current var estimates. sigestimate(sig, sigestimator, mass) invert(m, sig, mass) factor(mfac, m, mass) -- Re-initialize var estimators. sigestimator:clear() varu = varu*2 mu = log(10*eps) madapt, Ht, lepst = 1, 0, 0 end else olstat:push(thr1) if stop(thr1) then break end end thr0 = thr1 cache = { thr0 = cache[thr0] } end return thr1:copy(), eps, sig:copy() end return { mcmc = nuts }
mit
ImagicTheCat/vRP
vrp/cfg/phone.lua
1
3496
local cfg = {} -- size of the sms history cfg.sms_history = 15 -- maximum size of an sms cfg.sms_size = 500 -- duration of a sms position marker (in seconds) cfg.smspos_duration = 300 -- {ent,cfg} will fill cfg.title, cfg.pos cfg.smspos_map_entity = {"PoI", {blip_id = 162, blip_color = 37}} cfg.clear_phone_on_death = true -- phone sounds (playAudioSource) cfg.dialing_sound = "sounds/phone_dialing.ogg" -- loop cfg.ringing_sound = "sounds/phone_ringing.ogg" -- loop cfg.sms_sound = "sounds/phone_sms.ogg" -- phone voice config (see Audio:registerVoiceChannel) cfg.phone_voice = { } cfg.phone_call_css = [[ .div_phone_call{ position: absolute; right: 0; top: 35%; margin: 6px; width: 200px; overflow: hidden; font-weight: bold; border-radius: 8px; padding: 5px; color: #3facff; background-color: rgb(0,0,0,0.75); } .div_phone_call:before{ content: "\260E"; color: white; padding-right: 5px; } ]] -- define phone services -- map_entity: {ent,cfg} will fill cfg.title, cfg.pos -- alert_time (alert blip display duration in seconds) -- alert_permission (permission required to receive the alert) -- alert_notify (notification received when an alert is sent) -- notify (notification when sending an alert) cfg.services = { ["police"] = { map_entity = {"PoI", {blip_id = 304, blip_color = 38}}, alert_time = 300, -- 5 minutes alert_permission = "police.service", alert_notify = "~r~Police alert:~n~~s~", notify = "~b~You called the police.", answer_notify = "~b~The police is coming." }, ["emergency"] = { map_entity = {"PoI", {blip_id = 153, blip_color = 1}}, alert_time = 300, -- 5 minutes alert_permission = "emergency.service", alert_notify = "~r~Emergency alert:~n~~s~", notify = "~b~You called the emergencies.", answer_notify = "~b~The emergencies are coming." }, ["taxi"] = { map_entity = {"PoI", {blip_id = 198, blip_color = 5}}, alert_time = 300, alert_permission = "taxi.service", alert_notify = "~y~Taxi alert:~n~~s~", notify = "~y~You called a taxi.", answer_notify = "~y~A taxi is coming." }, ["repair"] = { map_entity = {"PoI", {blip_id = 446, blip_color = 5}}, alert_time = 300, alert_permission = "repair.service", alert_notify = "~y~Repair alert:~n~~s~", notify = "~y~You called a repairer.", answer_notify = "~y~A repairer is coming." } } -- define phone announces -- image: background image for the announce (800x150 px) -- price: amount to pay to post the announce -- description (optional) -- permission (optional): permission required to post the announce cfg.announces = { ["admin"] = { --image = "nui://vrp_mod/announce_admin.png", image = "http://i.imgur.com/kjDVoI6.png", price = 0, description = "Admin only.", permission = "admin.announce" }, ["police"] = { --image = "nui://vrp_mod/announce_police.png", image = "http://i.imgur.com/DY6DEeV.png", price = 0, description = "Only for police, ex: wanted advert.", permission = "police.announce" }, ["commercial"] = { --image = "nui://vrp_mod/announce_commercial.png", image = "http://i.imgur.com/b2O9WMa.png", description = "Commercial stuff (buy, sell, work).", price = 5000 }, ["party"] = { --image = "nui://vrp_mod/announce_party.png", image = "http://i.imgur.com/OaEnk64.png", description = "Organizing a party ? Let everyone know the rendez-vous.", price = 5000 } } return cfg
mit
xordspar0/synthein
src/world/shipparts/part.lua
1
1438
-- Utilities local vector = require("vector") local LocationTable = require("locationTable") local Draw = require("world/draw") local Part = class() function Part:__create() self.physicsShape = nil self.connectableSides = {true, true, true, true} self.thrust = 0 self.torque = 0 self.gun = false self.type = "generic" self.modules = {} end function Part:loadData(data) if data[1] then self.modules.hull.health = data[1] end end function Part:saveData() return {self.modules.hull.health} end function Part:getModules() return self.modules end function Part:addFixtures(body) self.modules["hull"]:addFixtures(body) end function Part:removeFixtures() self.modules["hull"]:removeFixtures() end function Part:setLocation(location) self.location = location self.modules["hull"].userData.location = location end function Part:withinPart(x, y) return self.modules["hull"].fixture:testPoint(x, y) end function Part:getWorldLocation() if not self.modules["hull"].fixture:isDestroyed() then return (LocationTable(self.modules["hull"].fixture, self.location)) end end function Part:getPartSide(locationX, locationY) local partX, partY, partAngle = self:getWorldLocation():getXYA() local angleToCursor = vector.angle( locationX - partX, locationY - partY ) local angleDifference = angleToCursor - partAngle local partSide = math.floor((angleDifference*2/math.pi - 1/2) % 4 +1) return partSide end return Part
gpl-3.0
osgcc/ryzom
ryzom/common/data_common/r2/r2_features.lua
3
34413
-- for client : register a component into C using the 'registerGenerator' function and add -- it into the list of classes -- copy class properties & methods local reservedMembers = { Prop = true, BaseClass = true, NameToProp = true, -- native properties Parent = true, ParentInstance= true, IndexInParent = true, User = true, Size = true, DisplayerUI = true, DisplayerVisual = true, DisplayerProperties = true, Selectable = true, SelectableFromRoot = true } -- check is a string is a valid identifier (e.g begin with an alphabetic letter followed by alpha numeric letters) local function isValidIdentifier(id) return string.match(id, "[%a_][%w_]*") end -- register a new class (features, components ...) r2.registerComponent = function(generator, package) -- check that all identifiers are correct local badProps = {} if generator.Prop == nil then generator.Prop = {} end -- serach invalid identifiers for k, prop in pairs(generator.Prop) do if (type(prop) ~= "table") then debugWarning("Invalid property found in ".. generator.Name) end if not isValidIdentifier( prop.Name ) then debugWarning("Invalid property name found : '" .. tostring(prop.Name) .. "' in class " .. tostring(generator.Name) .. ". Property is ignored") table.insert(badProps, k) end if reservedMembers[prop.Name] then debugWarning("Invalid property name found : '" .. tostring(prop.Name) .. "' in class " .. tostring(generator.Name) .. ". This is the name of a native poperty, and can't be redefined") table.insert(badProps, k) end end -- check that no identifier is duplicated local propName = {} for k, prop in pairs(generator.Prop) do if propName[prop.Name] ~= nil then debugWarning("Duplicated property found when registering class " .. tostring(generator.Name) .. ", property = " .. tostring(prop.Name)) debugWarning("Aborting class registration.") return end propName[prop.Name] = true end -- remove bad properties from the class for k, prop in pairs(badProps) do generator.Prop[prop] = nil end local name = nil if package then name = generator.Name --name = package:getUniqId() .. "|" .. generator.Name TODO else name = generator.Name; end if r2.Classes[name] ~= nil then debugWarning("Component registered twice : " .. generator.Name) return end if type(name) ~= "string" then debugWarning("Can't register class, 'Name' field not found or bad type") assert(false) end r2.Classes[name] = generator end -- private : perform subclassing by copying properties / methods of the base class into the class passed as a parameter -- only methods / props that are present in the base class and not in the derived class are copied -- subclass is done recursively so after calling 'subclass' on a class definition it will be complete function r2.Subclass(classDef) assert(classDef) assert(type(classDef) == "table") if classDef.BaseClass ~= "" and classDef.BaseClass ~= nil then local baseClass = r2.Classes[classDef.BaseClass] if baseClass == nil then debugInfo("Cant found base class " .. strify(classDef.BaseClass) .. " of class " .. strify(classDef.Name)) return end --debugInfo("sub classing " .. tostring(classDef.Name) .. " from " .. tostring(baseClass.Name)) -- make sure that base class is complete, too r2.Subclass(baseClass) for key, value in pairs(baseClass) do if classDef[key] == nil then -- if property or method not defined in derived class then copy from the base class -- if this is a method, then just replace with a function that will delegate -- the call to the parent class --if type(value) == "function" and key ~= "delegate" then -- assert(type(key) == "string") -- local localKey = key -- apparently, closure are not supported with locals from the enclosing 'for' loop -- local function delegator(this, ...) --debugInfo("Calling parent version in parent class '" .. tostring(baseClass.Name) .. "' for " .. tostring(localKey)) -- TODO nico : here if would be much faster to call the -- first parent class where function is defined instead -- of chaining the calls to 'delegate' -- There are 1 thing to rememeber however : -- * The this pointer could be a delegated one, -- so when doing the call directly this should be with the non-delgated this (to have a polymorphic call) -- local delegated = this:delegate() -- return delegated[localKey](delegated, unpack(arg)) -- end -- classDef[key] = delegator --else classDef[key] = value --end end end -- copy instances properties assert(classDef.NameToProp) assert(baseClass.NameToProp) for key, prop in pairs(baseClass.Prop) do -- if property not declared in derived class then add it if classDef.NameToProp[prop.Name] == nil then -- its okay to make a reference here because classes definitions are read-only classDef.NameToProp[prop.Name] = prop table.insert(classDef.Prop, prop) end end end -- else no-op end function r2.getLoadedFeaturesStatic() local loadedFeatures = { --Mob Spawners {"r2_features_boss_spawner.lua", "BossSpawnerFeature", "uiR2EdMobSpawnersCategory"}, {"r2_features_timed_spawn.lua", "TimedSpawner", "uiR2EdMobSpawnersCategory"}, {"r2_features_scenery_object_remover.lua", "SceneryObjectRemoverFeature", "uiR2EdMobSpawnersCategory"}, --Chests {"r2_features_easter_egg.lua", "EasterEggFeature", "uiR2EdChestsCategory"}, {"r2_features_random_chest.lua", "RandomChest", "uiR2EdChestsCategory"}, {"r2_features_get_item_from_scenery.lua", "GetItemFromSceneryObject", "uiR2EdChestsCategory"}, --Tasks {"r2_features_give_item.lua", "GiveItemFeature", "uiR2EdTaskStepCategory"}, {"r2_features_talk_to.lua", "TalkToFeature", "uiR2EdTaskStepCategory"}, {"r2_features_request_item.lua", "RequestItemFeature", "uiR2EdTaskStepCategory"}, {"r2_features_visit_zone.lua", "VisitZone", "uiR2EdTasksCategory"}, {"r2_features_target_mob.lua", "TargetMob", "uiR2EdTasksCategory"}, {"r2_features_kill_npc.lua", "KillNpc", "uiR2EdTasksCategory"}, {"r2_features_hunt_task.lua", "HuntTask", "uiR2EdTasksCategory"}, {"r2_features_delivery_task.lua", "DeliveryTask", "uiR2EdTasksCategory"}, {"r2_features_get_item_from_scenery_task.lua", "GetItemFromSceneryObjectTaskStep", "uiR2EdTaskStepCategory"}, {"r2_features_scenery_object_interaction_task.lua", "SceneryObjectInteractionTaskStep", "uiR2EdTaskStepCategory"}, --Triggers {"r2_features_timer.lua", "TimerFeature", "uiR2EdTriggersCategory"}, {"r2_features_zone_triggers.lua", "ZoneTrigger", "uiR2EdTriggersCategory"}, {"r2_features_user_trigger.lua", "UserTriggerFeature", "uiR2EdTriggersCategory"}, {"r2_features_man_hunt.lua", "ManHuntFeature", "uiR2EdTriggersCategory"}, {"r2_features_scenery_object_interaction.lua", "SceneryObjectInteractionFeature", "uiR2EdTriggersCategory"}, {"r2_features_proximity_dialog.lua", "ChatSequence", "uiR2EdTriggersCategory"}, --{"r2_features_reward_provider.lua", "RewardProvider", "uiR2EdTriggersCategory"}, --MacroComponents {"r2_features_ambush.lua", "Ambush", "uiR2EdMacroComponentsCategory"}, {"r2_features_loot_spawner.lua", "LootSpawnerFeature", "uiR2EdMacroComponentsCategory"}, {"r2_features_hidden_chest.lua", "HiddenChest", "uiR2EdMacroComponentsCategory"}, {"r2_features_proximity_dialog.lua", "ProximityDialog", "uiR2EdMacroComponentsCategory"}, {"r2_features_bandits_camp.lua", "BanditCampFeature", "uiR2EdMacroComponentsCategory"}, {"r2_features_fauna.lua", "FaunaFeature", "uiR2EdMacroComponentsCategory"}, } return loadedFeatures end function r2.doFileProtected(filename) local ok, msg = pcall(r2.doFile, filename) if not ok then debugInfo("Error while loading component '"..filename.."' err: "..msg) end end r2.loadFeatures = function() r2.doFileProtected("r2_features_default.lua") r2.doFileProtected("r2_features_npc_groups.lua") r2.doFileProtected("r2_features_counter.lua") r2.doFileProtected("r2_features_reward_provider.lua") --Loading features r2.doFileProtected("r2_features_loaded.lua") local loadedFeatures = r2.getLoadedFeaturesStatic() local k, v = next(loadedFeatures, nil) while k do if v and v[1] then r2.doFileProtected(v[1]) end k, v = next(loadedFeatures, k) end if config.R2EDLoadDynamicFeatures == 1 then local loadedFeatures = r2.getLoadedFeaturesDynamic() local k, v = next(loadedFeatures, nil) while k do if v and v[1] then r2.doFileProtected(v[1]) end k, v = next(loadedFeatures, k) end end r2.doFileProtected("r2_texts.lua") r2.doFileProtected("r2_logic.lua") r2.doFileProtected("r2_logic_entities.lua") r2.doFileProtected("r2_event_handler_system.lua") r2.doFileProtected("r2_unit_test.lua") r2.doFileProtected("r2_core_user_component_manager.lua") --r2_core.UserComponentManager:init() --debugInfo("REGISTERING FEATURES") r2.UserComponentsManager:updateUserComponents() local featureId, feature = next(r2.Features, nil) while (featureId ~= nil) do --debugInfo("Registering feature " .. feature.Name) local componentId, component = next(feature.Components, nil) while (component ~= nil) do --debugInfo(" Registering feature component " .. component.Name) r2.registerComponent(component) componentId, component = next(feature.Components, componentId) end featureId, feature = next(r2.Features, featureId); end end -- Function to init default scenario stuffs, with the given client ID -- tmp : returns ids for the scenario, the first act, and the default group r2.initBaseScenario = function() local function ici(index) -- debugInfo(colorTag(255, 255, 0) .. "ICI " .. tostring(index)) end -- create scenario ici(1) local scenario= r2.newComponent("Scenario") if (scenario == nil) then debugWarning("Failed to create Scenario"); return end ici(2) --debugInfo("Scenario created with id " .. scenario.InstanceId) scenario.title = "TestMap" scenario.shortDescription = "TestMap" scenario.optimalNumberOfPlayer = 1 -- create first act & default feature group do local act =r2.newComponent("Act") act.States = {} if (act == nil) then debugWarning("Failed to create first 'Act'"); return end local features = act.Features local tmpDefault = r2.newComponent("DefaultFeature") if (tmpDefault == nil) then debugWarning("Failed to create default feature"); return end table.insert(features, tmpDefault) table.insert(scenario.Acts, act) end -- By default create act I and have it selected do local act =r2.newComponent("Act") -- force to select the act 1 at display r2.ActUIDisplayer.LastSelfCreatedActInstanceId = act.InstanceId act.States = {} if (act == nil) then debugWarning("Failed to create secondary 'Act'"); return end act.Name = i18n.get("uiR2EDAct1"):toUtf8() act.Title = i18n.get("uiR2EDAct1"):toUtf8() -- obsolete local features = act.Features local tmpDefault = r2.newComponent("DefaultFeature") if (tmpDefault == nil) then debugWarning("Failed to create default feature"); return end table.insert(features, tmpDefault) table.insert(scenario.Acts, act) end r2.requestCreateScenario(scenario) end -- called by the frame work to reset the current scenario -- function r2.resetScenario() -- -- do -- -- r2.requestEraseNode(r2.ScenarioInstanceId, "Acts" ) -- -- -- local acts= {} -- -- do -- local act =r2.newComponent("Act") -- local features = act.Features -- local tmpDefault = r2.newComponent("DefaultFeature") -- table.insert(features, tmpDefault) -- table.insert(acts, act) -- end -- do -- local act =r2.newComponent("Act") -- local features = act.Features -- local tmpDefault = r2.newComponent("DefaultFeature") -- r2.ActUIDisplayer.LastSelfCreatedActInstanceId = act.InstanceId -- act.Title = i18n.get("uiR2EDAct1"):toUtf8() -- table.insert(features, tmpDefault) -- table.insert(acts, act) -- -- table.insert(scenario.Acts, act) -- end -- -- -- r2.requestInsertNode(r2.ScenarioInstanceId, "", -1, "Acts", acts) -- r2.requestReconnection() -- end --end -- called when a gm/ai has do a scheduleStartAct (Animation or test time) function r2.onScheduleStartAct(errorId, actId, nbSeconds) if (r2.Mode == "DM" or r2.Mode == "AnimationModeDm") then if errorId == 0 then local ucStringMsg = ucstring() local str = "Act " .. actId if nbSeconds ~= 0 then str = str .. " will start in " .. nbSeconds .. " seconds" end ucStringMsg:fromUtf8(str) displaySystemInfo(ucStringMsg, "BC") elseif errorId == 1 then messageBox("Act ".. actId .." can not be started because another act is already starting.") elseif errorId == 2 then messageBox("Act ".. actId .." can not be started because this act does not exist.") end end end function r2.onDisconnected() local str = "You have been disconnected by the server." local ucStringMsg = ucstring() messageBox(str) ucStringMsg:fromUtf8(str) displaySystemInfo(ucStringMsg, "BC") end function r2.onKicked(timeBeforeDisconnection, kicked) if kicked then local str = "You have been kicked. You must come back to mainland or leave this session otherwise you will be disconnected in " .. tostring(timeBeforeDisconnection) .. " secondes." local ucStringMsg = ucstring() messageBox(str) ucStringMsg:fromUtf8(str) displaySystemInfo(ucStringMsg, "BC") else local str = "You have been unkicked." local ucStringMsg = ucstring() messageBox(str) ucStringMsg:fromUtf8(str) displaySystemInfo(ucStringMsg, "BC") end end -- called in start mode of a dm function r2.onRuntimeActUpdated(runtimeAct) -- use runtimeAct or r2.getRunTimeActs() r2.AnimGlobals.Acts = runtimeAct -- update the ui r2.ui.AnimBar:update() end function r2.onTalkingAsListUpdated() r2.ui.AnimBar:updateDMControlledEntitiesWindow() end function r2.onIncarnatingListUpdated() r2.ui.AnimBar:updateDMControlledEntitiesWindow() end function r2.onScenarioHeaderUpdated(scenario) local ui=getUI('ui:interface:r2ed_scenario_control') if ui.active == true then ui.active = false ui.active = true end -- inspect(scenario) -- or use r2.getScenarioHeader(); end function r2.onSystemMessageReceived(msgType, msgWho, msg) local ucStringMsg = ucstring() ucStringMsg:fromUtf8(msg) if string.len(msg) > 2 and string.sub(msg, 1, 2) == "ui" then ucStringMsg = i18n.get(msg) msg = ucStringMsg:toString() end if msgType == "BC" or msgType == "BC_ML" then printMsgML(msg) elseif msgType == "SYS" or msgType == "DM" then local str = "" if msgType == "DM" then str = "(AM ONLY)"..str if (r2.Mode ~= "DM" and r2.Mode ~= "AnimationModeDm") then return end end if string.len(msgWho) ~= 0 then str = str .. msgWho .. ": " end str = str.. msg printMsgML(msg) elseif msgType == "ERR" then printMsgML(msg) messageBox(msg) end end -- TMP : place holder function to know the current act if not r2.getCurrentActIndex then debugInfo("Creating place holder for r2.getCurrentActIndex") function r2.getCurrentActIndex() return 1 end end function r2.onUserTriggerDescriptionUpdated(userTrigger) -- use userTrigger or r2.getUserTriggers() r2.AnimGlobals.UserTriggers = userTrigger r2.ui.AnimBar:update() end function r2.onCurrentActIndexUpdated( actIndex) -- actIndex==r2.getCurrentActIndex()) end -- called when a session has begin but no scenario has been created function r2.onEmptyScenarioUpdated() if r2.Mode == "AnimationModeLoading" then UnitTest.testLoadAnimationScenarioUi() elseif r2.Mode == "AnimationModeWaitingForLoading" then UnitTest.testWaitAnimationScenarioLoadingUi() else --UnitTest.testCreateScenarioUi() r2.acts:openScenarioActEditor(true, true) end end -- called by the framework when the scenario has been updated function r2.onScenarioUpdated(scenario, startingActIndex) --luaObject(scenario) --breakPoint() if (scenario == nil) then r2.onEmptyScenarioUpdated() return else hide('ui:interface:r2ed_form_CreateNewAdventureStep2') end r2.Scenario = r2:getInstanceFromId(scenario.InstanceId) r2.ScenarioInstanceId = scenario.InstanceId -- add permanent nodes to act node r2:defaultUIDisplayer():addPermanentNodes() if r2.Version.updateVersion() then r2.setScenarioUpToDate(true) else r2.setScenarioUpToDate(false) end local currentAct = nil assert(startingActIndex); assert( type(startingActIndex) == "number"); if startingActIndex < table.getn(scenario.Acts) then r2.DefaultActInstanceId = scenario.Acts[startingActIndex].InstanceId r2.ActUIDisplayer.LastSelfCreatedActInstanceId = scenario.Acts[startingActIndex].InstanceId if scenario.Acts[startingActIndex].Features.Size > 0 then r2.DefaultFeatureInstanceId = scenario.Acts[startingActIndex].Features[0].InstanceId end currentAct=scenario.Acts[startingActIndex] r2.ScenarioWindow:setAct(currentAct) else r2.DefaultActInstanceId = scenario.Acts[0].InstanceId r2.ActUIDisplayer.LastSelfCreatedActInstanceId = scenario.Acts[0].InstanceId if scenario.Acts[0].Features.Size > 0 then r2.DefaultFeatureInstanceId = scenario.Acts[0].Features[0].InstanceId end currentAct=scenario.Acts[0] end if scenario ~= nil and currentAct ~= nil then r2.Scenario.User.SelectedActInstanceId = tostring(currentAct.InstanceId) r2.Scenario.User.SelectedLocationInstanceId = tostring(currentAct.LocationId) end r2.ScenarioWindow:updateScenarioProperties() -- usefull to know if the scenario is updating ld.lock = 0 if not r2.RingAccess.LoadAnimation and not r2.getIsAnimationSession() then local ok, level, err = r2.RingAccess.verifyScenario() r2.updateScenarioAck(ok, level, err.What) return end r2.acts.deleteOldScenario = false if r2.getUseVerboseRingAccess() then r2.RingAccess.dumpRingAccess() end end function r2.verifyScenario() local ok, level, err = r2.RingAccess.verifyScenario() local msg="" if not ok then printMsg(err.What) msg = err.What end return ok, msg end function r2.printMsg(msg) r2.printMsg(msg) end -- assign default menu for each classes function r2.initDefaultMenuSetup() forEach(r2.Classes, function(k, v) if v.Menu ~= nil and v.onSetupMenu == nil then v.onSetupMenu = r2.defaultMenuSetup end end ) end -- assign default menu for each classes function r2.initDefaultPropertyDisplayer() for k, class in pairs(r2.Classes) do if class.BuildPropertySheet == true then if class.DisplayerProperties == nil then class.DisplayerProperties = "R2::CDisplayerLua" class.DisplayerPropertiesParams = "propertySheetDisplayer" end end end end -- setup the classes function r2.setupClasses() -- first build a table that gives access to a property from its name for k, class in pairs(r2.Classes) do class.NameToProp = {} for k, prop in pairs(class.Prop) do if prop.Name == nil then debugInfo("Found a property in class " .. tostring(class.Name) .. " with no field 'Name'") end class.NameToProp[prop.Name] = prop end end -- perform subclassing for k, class in pairs(r2.Classes) do r2.Subclass(class) end -- register into C for k, class in pairs(r2.Classes) do r2.registerGenerator(class) end end -- returns a table which map each instanceId of the scenario component's to each component r2.createComponentsMap = function (scenario) function createComponentsMapImpl (t, components) if ( type(t) == "table") then if (t.InstanceId ~= nil) then components[t.InstanceId] = t end for key, value in pairs(t) do createComponentsMapImpl(value, components) end end end local components = {} createComponentsMapImpl(scenario, components) return components end r2.updateActCost = function(act) assert(act) local cost = 0 local staticCost = 0 local features = act.Features assert(features ~= nil ) local featureId, feature = next(features, nil) while (featureId ~= nil) do -- feature:getCost() is obsolete if feature.User.GhostDuplicate ~= true then if feature and feature.getAiCost then local added = feature:getAiCost() if added then cost = cost + added end end if feature and feature.getStaticObjectCost then local added = feature:getStaticObjectCost() if added then staticCost = staticCost + added end end end featureId, feature = next(features, featureId) end -- NB nico : removed cost from the real object and put is in the 'User' table (interfere with undo redo, because considered -- as an action) act:setLocalCost(cost) --if (act.Cost ~= cost) then -- r2.requestSetLocalNode(act.InstanceId, "Cost", cost) -- r2.requestCommitLocalNode(act.InstanceId, "Cost") --end act:setLocalStaticCost(staticCost) --if (act.StaticCost ~= staticCost) then -- r2.requestSetLocalNode(act.InstanceId, "StaticCost", staticCost) -- r2.requestCommitLocalNode(act.InstanceId, "StaticCost") --end end r2.registerText = function(text) --TODO : when several texts are registered "at the same time", the local scenario --has not the time to receive the changes, and a new entry is created. local checkText = r2.Features["TextManager"].checkText local textMgr = getTextMgr() if(textMgr==nil) then debugInfo("text mgr nil!!") end local result = checkText(textMgr,text) if result.Count ~= 0 then --the entry already exist, just increment the counter r2.requestSetNode(result.InstanceId,"Count",result.Count+1) --temporaire --result.Count = result.Count + 1 --/temporaire debugInfo("Entry already exist") else --the entry don't exist, insert it result.Count=1 -- debugInfo("New entry created") r2.requestInsertNode(r2.Scenario.Texts.InstanceId,"Texts",-1,"",result) --temporaire --table.insert(r2.TextMgr.Texts,result) --temporaire end return result end getTextMgr = function() --return r2.TextMgr return r2.Scenario.Texts end r2.unregisterText = function(text) local removeText = r2.Features["TextManager"].removeText removeText(r2.Scenario.Texts,text) end r2.unregisterTextFromId = function(id) local text = r2.getText(id) if text ~= nil then r2.unregisterText(text) end end r2.getText = function(id) local textMgr = getTextMgr() return r2.Features["TextManager"].getText(textMgr, id) end r2.split = function(str, sep) assert( type(str) == "string") local ret = {} local start=0 if sep == nil then sep = "\n" end local fin=string.find(str, sep) while fin ~= nil do local tmp = string.sub(str,start,fin-1) if string.len(tmp)~=0 then table.insert(ret,tmp) end start = fin+1 fin = string.find(str,sep,start) end if start<string.len(str) then local tmp =string.sub(str,start) if string.len(tmp)~=0 then table.insert(ret,tmp) end end return ret end r2.dumpAI = function(rtAct, rtGrp) if 1 == 0 then do local event = Actions.createEvent("timer_t0_triggered", "", rtGrp.Id) local action = Actions.createAction("code","print(\"timer_t0_triggered\");\n" .. "print(\"--------".. rtGrp.Id .. "---\");\n" .. "print(\"oldActivitySequenceVar:\",oldActivitySequenceVar);\n" .. "print(\"currentActivitySequenceVar:\",currentActivitySequenceVar);\n" .. "print(\"oldActivityStepVar:\", oldActivityStepVar);\n" .. "print(\"v2:\",v2);\n" .. "print(\"oldChatStepVar:\", oldChatStepVar);\n" .. "print(\"v1:\",v1);\n" .. "print(\"oldChatSequenceVar:\", oldChatSequenceVar);\n" .. "print(\"v0:\",v0);\n" .. "print(\"----------------\");\n" ); table.insert(rtAct.Actions, action) table.insert(rtAct.Events, event) table.insert(event.ActionsId, action.Id) end do local event = Actions.createEvent("timer_t1_triggered", "", rtGrp.Id) local action = Actions.createAction("code", "print(\"timer_t1_triggered\");\n" .. "print(\"--------".. rtGrp.Id .. "---\");\n" .. "print(\"oldActivitySequenceVar:\",oldActivitySequenceVar);\n" .. "print(\"currentActivitySequenceVar:\",currentActivitySequenceVar);\n" .. "print(\"oldActivityStepVar:\",oldActivityStepVar);\n" .. "print(\"v2:\",v2);\n" .. "print(\"oldChatStepVar:\",oldChatStepVar);\n" .. "print(\"v1:\",v1);\n" .. "print(\"oldChatSequenceVar:\",oldChatSequenceVar);\n" .. "print(\"v0:\",v0);\n" .. "print(\"----------------\");\n" ); table.insert(rtAct.Actions, action) table.insert(rtAct.Events, event) table.insert(event.ActionsId, action.Id) end do local event = Actions.createEvent("variable_v0_changed", "", rtGrp.Id) local action = Actions.createAction("code", "print(\"variable_v0_changed\");\n" .. "print(\"--------".. rtGrp.Id .. "---\");\n" .. "print(\"oldActivitySequenceVar:\",oldActivitySequenceVar);\n" .. "print(\"currentActivitySequenceVar:\",currentActivitySequenceVar);\n" .. "print(\"oldActivityStepVar:\",oldActivityStepVar);\n" .. "print(\"v2:\",v2);\n" .. "print(\"oldChatStepVar:\",oldChatStepVar);\n" .. "print(\"v1:\",v1);\n" .. "print(\"oldChatSequenceVar:\",oldChatSequenceVar);\n" .. "print(\"v0:\",v0);\n" .. "print(\"----------------\");\n" ); table.insert(rtAct.Actions, action) table.insert(rtAct.Events, event) table.insert(event.ActionsId, action.Id) end do local event = Actions.createEvent("variable_v1_changed", "", rtGrp.Id) local action = Actions.createAction("code", "print(\"variable_v1_changed\");\n" .. "print(\"--------".. rtGrp.Id .. "---\");\n" .. "print(\"oldActivitySequenceVar:\",oldActivitySequenceVar);\n" .. "print(\"currentActivitySequenceVar:\",currentActivitySequenceVar);\n" .. "print(\"oldActivityStepVar:\",oldActivityStepVar);\n" .. "print(\"v2:\",v2);\n" .. "print(\"oldChatStepVar:\",oldChatStepVar);\n" .. "print(\"v1:\",v1);\n" .. "print(\"oldChatSequenceVar:\",oldChatSequenceVar);\n" .. "print(\"v0:\",v0);\n" .. "print(\"----------------\");\n" ); table.insert(rtAct.Actions, action) table.insert(rtAct.Events, event) table.insert(event.ActionsId, action.Id) end do local event = Actions.createEvent("variable_v2_changed", "", rtGrp.Id) local action = Actions.createAction("code", "print(\"variable_v2_changed\");\n" .. "print(\"--------".. rtGrp.Id .. "---\");\n" .. "print(\"oldActivitySequenceVar:\",oldActivitySequenceVar);\n" .. "print(\"currentActivitySequenceVar:\",currentActivitySequenceVar);\n" .. "print(\"oldActivityStepVar:\",oldActivityStepVar);\n" .. "print(\"v2:\",v2);\n" .. "print(\"oldChatStepVar:\",oldChatStepVar);\n" .. "print(\"v1:\",v1);\n" .. "print(\"oldChatSequenceVar:\",oldChatSequenceVar);\n" .. "print(\"v0:\",v0);\n" .. "print(\"----------------\");\n" ); table.insert(rtAct.Actions, action) table.insert(rtAct.Events, event) table.insert(event.ActionsId, action.Id) end end end if r2.getInstanceFromId == nil then r2.getInstanceFromId = function(instanceId) local function look(node,instanceId) if node.InstanceId ~=nil then -- debugInfo("looking in "..node.InstanceId) else -- debugInfo("no instance id!!") end --look if this node is the good one if node.InstanceId == instanceId then --then return it return node else --else, look in its children local children = node.Children if children == nil then return nil else local max = table.getn(children) for i=1,max do local tmp = look(children[i],instanceId) if tmp ~=nil then return tmp end end end end end local tmp = look(r2.Scenario,instanceId) if tmp~=nil then return tmp end tmp = look(r2.Scenario.Acts,instanceId) if tmp~=nil then return tmp end tmp = look(r2.Scenario.Texts,instanceId) if tmp~=nil then return tmp end return nil end end r2.getAiCost = function(instance) -- if the object is a ghost duplicate (when shift-dragging for exemple), -- don't take the cost into acount if instance.User.GhostDuplicate then return 0 end local cost = 1 local components = instance.Components if components and table.getn(components) ~= 0 then local key, value = next(components, nil) while key do if value.getAiCost then cost = cost + value:getAiCost() end key, value = next(components, key) end end local ghosts = instance.Ghosts if ghosts and table.getn(ghosts) ~= 0 then local key, value = next(ghosts, nil) while key do if value.getAiCost then cost = cost + value:getAiCost() end key, value = next(ghosts, key) end end return cost end r2.getStaticObjectCost = function(instance) -- if the object is a ghost duplicate (when shift-dragging for exemple), -- don't take the cost into acount if instance.User.GhostDuplicate then return 0 end local cost = 0 local components = instance.Components if components and table.getn(components) ~= 0 then local key, value = next(components, nil) while key do if value.getStaticObjectCost then cost = cost + value:getStaticObjectCost() end key, value = next(components, key) end end return cost end --r2.displayFeatureHelp = function(title, help) r2.displayFeatureHelp = function(className) local title = "uiR2Ed"..className.."_HelpTitle" local test = i18n.get(title) if not test then debugInfo("Entry not found in translation file") assert(nil) end local help = "uiR2Ed"..className.."_HelpText" test = i18n.hasTranslation(help) if not test then debugInfo("Entry not found in translation file") assert(nil) end local checkBox = getUI("ui:interface:feature_help:content:custom_bbox_enabled") assert(checkBox) local chkBoxText = getUI("ui:interface:feature_help:content:text_custom") assert(chkBoxText) if className == "Npc" then debugInfo("ClassName = " ..className) checkBox.active = false chkBoxText.active = false else checkBox.active = true chkBoxText.active = true local pushed = false if r2.mustDisplayInfo(className) == 1 then pushed = true end checkBox.pushed = pushed end local uiInfo = getUI("ui:interface:feature_help") --local scrW, scrH = getWindowSize() --uiInfo.x = 0 --uiInfo.y = scrH --uiInfo.h = scrH / 2 --uiInfo.pop_min_h= scrH / 2 --uiInfo.pop_max_h= scrH / 2 uiInfo.active = true uiInfo:invalidateCoords() uiInfo:updateCoords() uiInfo.title = title uiInfo.Env.uc_title = title local uiText = getUI("ui:interface:feature_help:content:enclosing:help_text_enclosed:help_text") assert(uiText) uiText.uc_hardtext_format = ucstring(i18n.get(help)) uiInfo:invalidateCoords() uiInfo:updateCoords() --local textH = uiText.h_real --local localH = textH + 90 --if localH > scrH then -- localH = scrH --end --uiInfo.h = localH --uiInfo.pop_min_h= localH --uiInfo.pop_max_h= localH uiInfo:invalidateCoords() uiInfo:updateCoords() uiInfo:center() setTopWindow(uiInfo) end function r2.setFeatureDisplayHelp() local checkBox = getUI("ui:interface:feature_help:content:custom_bbox_enabled") assert(checkBox) local isChecked = checkBox.pushed debugInfo("checked: " ..tostring(isChecked)) local ui = getUI("ui:interface:feature_help") local name = ui.Env.uc_title local len = string.len(name) - 10 - 6 local className = string.sub(name, -10-len, 6+len) --removing uiR2Ed and _HelpTitle --formName = formName .."Form" assert(className) --debugInfo("Form name: " ..formName) if isChecked == false then r2.setDisplayInfo(className, 1) else r2.setDisplayInfo(className, 0) end end function r2.getDisplayButtonHeader(func, buttonText) local header = string.format( [[ <ctrl style="text_button_16" id="help" posref="TL TL" color="255 255 255 255" col_over="255 255 255 255" col_pushed="255 255 255 255" onclick_l="lua" params_l="%s" hardtext="%s"/> ]], func, buttonText) return header end function r2.updateLogicEvents(this, invalidEvents) assert(invalidEvents) assert(this) local actions = this.Behavior.Actions assert(actions) local function updateLogicEvent(k, action) local event = action.Event assert(event) if invalidEvents[event.Type] then local instanceId = tostring(event.InstanceId) r2.requestSetNode(instanceId, "Type", tostring(invalidEvents[event.Type])) end end forEach(actions, updateLogicEvent) end function r2.updateLogicActions(this, invalidActions, entityClass) assert(invalidActions) assert(this) assert(entityClass) local instance = r2:getInstanceFromId(this.Entity) if not instance or not instance:isKindOf(entityClass) then return end local action = this.Action assert(action) if invalidActions[action.Type] then r2.requestSetNode(action.InstanceId, "Type", invalidActions[action.Type]) end end function r2.onRingAccessUpdated(access) r2:buildPaletteUI() r2.acts:initActsEditor() updateBanditCampEnum() -- also available by r2.getRingAccess() end function r2:checkAiQuota(size) if not size then size = 1 end local leftQuota, leftAIQuota, leftStaticQuota = r2:getLeftQuota() if leftAIQuota < size then displaySystemInfo(i18n.get("uiR2EDMakeRoomAi"), "BC") return false end return true end function r2:checkStaticQuota(size) if not size then size = 1 end local leftQuota, leftAIQuota, leftStaticQuota = r2:getLeftQuota() if leftStaticQuota < size then displaySystemInfo(i18n.get("uiR2EDMakeRoomStaticObject"), "BC") return false end return true end function r2.DisplayNpcHeader() local npc = r2:getSelectedInstance() if not npc then return "" end if npc:isGrouped() then local header = [[ <view type="text" id="t" multi_line="true" sizeref="w" w="-36" x="4" y="-2" posref="TL TL" global_color="true" fontsize="12" shadow="true" hardtext="uiR2EdNpcHeader"/> ]] return header else return "" end end function r2.mustDisplayProp(prop) end
agpl-3.0
masterweb121/telegram-bot
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
iamliqiang/prosody-modules
mod_storage_ldap/ldap/vcard.lib.lua
40
5035
-- vim:sts=4 sw=4 -- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2012 Rob Hoelz -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require 'util.stanza'; local VCARD_NS = 'vcard-temp'; local builder_methods = {}; local base64_encode = require('util.encodings').base64.encode; function builder_methods:addvalue(key, value) self.vcard:tag(key):text(value):up(); end function builder_methods:addphotofield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; local config = format[format_section]; if not config then return; end if config.extval then if record[config.extval] then local tag = vcard:tag(tagname); tag:tag('EXTVAL'):text(record[config.extval]):up(); end elseif config.type and config.binval then if record[config.binval] then local tag = vcard:tag(tagname); tag:tag('TYPE'):text(config.type):up(); tag:tag('BINVAL'):text(base64_encode(record[config.binval])):up(); end else module:log('error', 'You have an invalid %s config section', tagname); return; end vcard:up(); end function builder_methods:addregularfield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; if not format[format_section] then return; end local tag = vcard:tag(tagname); for k, v in pairs(format[format_section]) do tag:tag(string.upper(k)):text(record[v]):up(); end vcard:up(); end function builder_methods:addmultisectionedfield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; if not format[format_section] then return; end for k, v in pairs(format[format_section]) do local tag = vcard:tag(tagname); if type(k) == 'string' then tag:tag(string.upper(k)):up(); end for k2, v2 in pairs(v) do if type(v2) == 'boolean' then tag:tag(string.upper(k2)):up(); else tag:tag(string.upper(k2)):text(record[v2]):up(); end end vcard:up(); end end function builder_methods:build() local record = self.record; local format = self.format; self:addvalue( 'VERSION', '2.0'); self:addvalue( 'FN', record[format.displayname]); self:addregularfield( 'N', 'name'); self:addvalue( 'NICKNAME', record[format.nickname]); self:addphotofield( 'PHOTO', 'photo'); self:addvalue( 'BDAY', record[format.birthday]); self:addmultisectionedfield('ADR', 'address'); self:addvalue( 'LABEL', nil); -- we don't support LABEL...yet. self:addmultisectionedfield('TEL', 'telephone'); self:addmultisectionedfield('EMAIL', 'email'); self:addvalue( 'JABBERID', record.jid); self:addvalue( 'MAILER', record[format.mailer]); self:addvalue( 'TZ', record[format.timezone]); self:addregularfield( 'GEO', 'geo'); self:addvalue( 'TITLE', record[format.title]); self:addvalue( 'ROLE', record[format.role]); self:addphotofield( 'LOGO', 'logo'); self:addvalue( 'AGENT', nil); -- we don't support AGENT...yet. self:addregularfield( 'ORG', 'org'); self:addvalue( 'CATEGORIES', nil); -- we don't support CATEGORIES...yet. self:addvalue( 'NOTE', record[format.note]); self:addvalue( 'PRODID', nil); -- we don't support PRODID...yet. self:addvalue( 'REV', record[format.rev]); self:addvalue( 'SORT-STRING', record[format.sortstring]); self:addregularfield( 'SOUND', 'sound'); self:addvalue( 'UID', record[format.uid]); self:addvalue( 'URL', record[format.url]); self:addvalue( 'CLASS', nil); -- we don't support CLASS...yet. self:addregularfield( 'KEY', 'key'); self:addvalue( 'DESC', record[format.description]); return self.vcard; end local function new_builder(params) local vcard_tag = st.stanza('vCard', { xmlns = VCARD_NS }); local object = { vcard = vcard_tag, __index = builder_methods, }; for k, v in pairs(params) do object[k] = v; end setmetatable(object, object); return object; end local _M = {}; function _M.create(params) local builder = new_builder(params); return builder:build(); end return _M;
mit
emptyrivers/WeakAuras2
WeakAuras/WeakAuras.lua
1
170642
local AddonName, Private = ... local internalVersion = 40 -- Lua APIs local insert = table.insert -- WoW APIs local GetTalentInfo, IsAddOnLoaded, InCombatLockdown = GetTalentInfo, IsAddOnLoaded, InCombatLockdown local LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid = LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid local UnitClass, UnitExists, UnitGUID, UnitAffectingCombat, GetInstanceInfo, IsInInstance = UnitClass, UnitExists, UnitGUID, UnitAffectingCombat, GetInstanceInfo, IsInInstance local UnitIsUnit, GetRaidRosterInfo, GetSpecialization, UnitInVehicle, UnitHasVehicleUI, GetSpellInfo = UnitIsUnit, GetRaidRosterInfo, GetSpecialization, UnitInVehicle, UnitHasVehicleUI, GetSpellInfo local SendChatMessage, GetChannelName, UnitInBattleground, UnitInRaid, UnitInParty, GetTime, GetSpellLink, GetItemInfo = SendChatMessage, GetChannelName, UnitInBattleground, UnitInRaid, UnitInParty, GetTime, GetSpellLink, GetItemInfo local CreateFrame, IsShiftKeyDown, GetScreenWidth, GetScreenHeight, GetCursorPosition, UpdateAddOnCPUUsage, GetFrameCPUUsage, debugprofilestop = CreateFrame, IsShiftKeyDown, GetScreenWidth, GetScreenHeight, GetCursorPosition, UpdateAddOnCPUUsage, GetFrameCPUUsage, debugprofilestop local debugstack, IsSpellKnown, GetFileIDFromPath = debugstack, IsSpellKnown, GetFileIDFromPath local GetNumTalentTabs, GetNumTalents = GetNumTalentTabs, GetNumTalents local ADDON_NAME = "WeakAuras" local WeakAuras = WeakAuras local L = WeakAuras.L local versionString = WeakAuras.versionString local prettyPrint = WeakAuras.prettyPrint WeakAurasTimers = setmetatable({}, {__tostring=function() return "WeakAuras" end}) LibStub("AceTimer-3.0"):Embed(WeakAurasTimers) Private.maxTimerDuration = 604800; -- A week, in seconds local maxUpTime = 4294967; -- 2^32 / 1000 Private.callbacks = LibStub("CallbackHandler-1.0"):New(Private) function WeakAurasTimers:ScheduleTimerFixed(func, delay, ...) if (delay < Private.maxTimerDuration) then if delay + GetTime() > maxUpTime then WeakAuras.prettyPrint(WeakAuras.L["Can't schedule timer with %i, due to a World of Warcraft bug with high computer uptime. (Uptime: %i). Please restart your computer."]:format(delay, GetTime())) return end return self:ScheduleTimer(func, delay, ...) end end local LDB = LibStub("LibDataBroker-1.1") local LDBIcon = LibStub("LibDBIcon-1.0") local LCG = LibStub("LibCustomGlow-1.0") local LGF = LibStub("LibGetFrame-1.0") local timer = WeakAurasTimers WeakAuras.timer = timer local loginQueue = {} local queueshowooc function WeakAuras.InternalVersion() return internalVersion; end function Private.LoadOptions(msg) if not(IsAddOnLoaded("WeakAurasOptions")) then if not WeakAuras.IsLoginFinished() then prettyPrint(Private.LoginMessage()) loginQueue[#loginQueue + 1] = WeakAuras.OpenOptions elseif InCombatLockdown() then -- inform the user and queue ooc prettyPrint(L["Options will finish loading after combat ends."]) queueshowooc = msg or ""; WeakAuras.frames["Addon Initialization Handler"]:RegisterEvent("PLAYER_REGEN_ENABLED") return false; else local loaded, reason = LoadAddOn("WeakAurasOptions"); if not(loaded) then reason = string.lower("|cffff2020" .. _G["ADDON_" .. reason] .. "|r.") WeakAuras.prettyPrint("Options could not be loaded, the addon is " .. reason); return false; end end end return true; end function WeakAuras.OpenOptions(msg) if Private.NeedToRepairDatabase() then StaticPopup_Show("WEAKAURAS_CONFIRM_REPAIR", nil, nil, {reason = "downgrade"}) elseif (WeakAuras.IsLoginFinished() and Private.LoadOptions(msg)) then WeakAuras.ToggleOptions(msg, Private); end end function Private.PrintHelp() print(L["Usage:"]) print(L["/wa help - Show this message"]) print(L["/wa minimap - Toggle the minimap icon"]) print(L["/wa pstart - Start profiling. Optionally include a duration in seconds after which profiling automatically stops. To profile the next combat/encounter, pass a \"combat\" or \"encounter\" argument."]) print(L["/wa pstop - Finish profiling"]) print(L["/wa pprint - Show the results from the most recent profiling"]) print(L["/wa repair - Repair tool"]) print(L["If you require additional assistance, please open a ticket on GitHub or visit our Discord at https://discord.gg/weakauras!"]) end SLASH_WEAKAURAS1, SLASH_WEAKAURAS2 = "/weakauras", "/wa"; function SlashCmdList.WEAKAURAS(input) if not WeakAuras.IsCorrectVersion() then prettyPrint(Private.wrongTargetMessage) return end local args, msg = {}, nil for v in string.gmatch(input, "%S+") do if not msg then msg = v else insert(args, v) end end if msg == "pstart" then WeakAuras.StartProfile(args[1]); elseif msg == "pstop" then WeakAuras.StopProfile(); elseif msg == "pprint" then WeakAuras.PrintProfile(); elseif msg == "pcancel" then WeakAuras.CancelScheduledProfile() elseif msg == "minimap" then Private.ToggleMinimap(); elseif msg == "help" then Private.PrintHelp(); elseif msg == "repair" then StaticPopup_Show("WEAKAURAS_CONFIRM_REPAIR", nil, nil, {reason = "user"}) else WeakAuras.OpenOptions(msg); end end if not WeakAuras.IsCorrectVersion() then return end function Private.ApplyToDataOrChildData(data, func, ...) if data.controlledChildren then for index, childId in ipairs(data.controlledChildren) do local childData = WeakAuras.GetData(childId) func(childData, ...) end return true else func(data, ...) end end function Private.ToggleMinimap() WeakAurasSaved.minimap.hide = not WeakAurasSaved.minimap.hide if WeakAurasSaved.minimap.hide then LDBIcon:Hide("WeakAuras"); prettyPrint(L["Use /wa minimap to show the minimap icon again."]) else LDBIcon:Show("WeakAuras"); end end BINDING_HEADER_WEAKAURAS = ADDON_NAME BINDING_NAME_WEAKAURASTOGGLE = L["Toggle Options Window"] BINDING_NAME_WEAKAURASPROFILINGTOGGLE = L["Toggle Performance Profiling Window"] BINDING_NAME_WEAKAURASPRINTPROFILING = L["Print Profiling Results"] -- An alias for WeakAurasSaved, the SavedVariables -- Noteable properties: -- debug: If set to true, WeakAura.debug() outputs messages to the chat frame -- displays: All aura settings, keyed on their id local db; local registeredFromAddons; -- List of addons that registered displays Private.addons = {}; local addons = Private.addons; -- used if an addon tries to register a display under an id that the user already has a display with that id Private.collisions = {}; local collisions = Private.collisions; -- While true no events are handled. E.g. WeakAuras is paused while the Options dialog is open local paused = true; local importing = false; -- squelches actions and sounds from auras. is used e.g. to prevent lots of actions/sounds from triggering -- on login or after closing the options dialog local squelch_actions = true; local in_loading_screen = false; -- Load functions, keyed on id local loadFuncs = {}; -- Load functions for the Options window that ignore various load options local loadFuncsForOptions = {}; -- Mapping of events to ids, contains true if a aura should be checked for a certain event local loadEvents = {} -- All regions keyed on id, has properties: region, regionType, also see clones WeakAuras.regions = {}; local regions = WeakAuras.regions; -- keyed on id, contains bool indicating whether the aura is loaded Private.loaded = {}; local loaded = Private.loaded; -- contains regions for clones WeakAuras.clones = {}; local clones = WeakAuras.clones; -- Unused regions that are kept around for clones local clonePool = {} -- One table per regionType, see RegisterRegionType, notable properties: create, modify and default WeakAuras.regionTypes = {}; local regionTypes = WeakAuras.regionTypes; Private.subRegionTypes = {} local subRegionTypes = Private.subRegionTypes -- One table per regionType, see RegisterRegionOptions WeakAuras.regionOptions = {}; local regionOptions = WeakAuras.regionOptions; Private.subRegionOptions = {} local subRegionOptions = Private.subRegionOptions -- Maps from trigger type to trigger system Private.triggerTypes = {}; local triggerTypes = Private.triggerTypes; -- Maps from trigger type to a function that can create options for the trigger Private.triggerTypesOptions = {}; -- Trigger State, updated by trigger systems, then applied to regions by UpdatedTriggerState -- keyed on id, triggernum, cloneid -- cloneid can be a empty string -- Noteable properties: -- changed: Whether this trigger state was recently changed and its properties -- need to be applied to a region. The glue code resets this -- after syncing the region to the trigger state -- show: Whether the region for this trigger state should be shown -- progressType: Either "timed", "static" -- duration: The duration if the progressType is timed -- expirationTime: The expirationTime if the progressType is timed -- autoHide: If the aura should be hidden on expiring -- value: The value if the progressType is static -- total: The total if the progressType is static -- inverse: The static values should be interpreted inversely -- name: The name information -- icon: The icon information -- texture: The texture information -- stacks: The stacks information -- index: The index of the buff/debuff for the buff trigger system, used to set the tooltip -- spellId: spellId of the buff/debuff, used to set the tooltip local triggerState = {} -- Fallback states local fallbacksStates = {}; -- List of all trigger systems, contains each system once local triggerSystems = {} local from_files = {}; local timers = {}; -- Timers for autohiding, keyed on id, triggernum, cloneid WeakAuras.timers = timers; WeakAuras.raidUnits = {}; WeakAuras.partyUnits = {}; do for i=1,40 do WeakAuras.raidUnits[i] = "raid"..i end for i=1,4 do WeakAuras.partyUnits[i] = "party"..i end end local playerLevel = UnitLevel("player"); local currentInstanceType = "none" -- Custom Action Functions, keyed on id, "init" / "start" / "finish" Private.customActionsFunctions = {}; -- Custom Functions used in conditions, keyed on id, condition number, "changes", property number WeakAuras.customConditionsFunctions = {}; -- Text format functions for chat messages, keyed on id, condition number, changes, property number WeakAuras.conditionTextFormatters = {} -- Helpers for conditions, that is custom run functions and preamble objects for built in checks -- keyed on UID not on id! WeakAuras.conditionHelpers = {} local load_prototype = Private.load_prototype; local levelColors = { [0] = "|cFFFFFFFF", [1] = "|cFF40FF40", [2] = "|cFF6060FF", [3] = "|cFFFF4040" }; function WeakAuras.validate(input, default) for field, defaultValue in pairs(default) do if(type(defaultValue) == "table" and type(input[field]) ~= "table") then input[field] = {}; elseif(input[field] == nil) or (type(input[field]) ~= type(defaultValue)) then input[field] = defaultValue; end if(type(input[field]) == "table") then WeakAuras.validate(input[field], defaultValue); end end end function WeakAuras.RegisterRegionType(name, createFunction, modifyFunction, default, properties, validate) if not(name) then error("Improper arguments to WeakAuras.RegisterRegionType - name is not defined", 2); elseif(type(name) ~= "string") then error("Improper arguments to WeakAuras.RegisterRegionType - name is not a string", 2); elseif not(createFunction) then error("Improper arguments to WeakAuras.RegisterRegionType - creation function is not defined", 2); elseif(type(createFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterRegionType - creation function is not a function", 2); elseif not(modifyFunction) then error("Improper arguments to WeakAuras.RegisterRegionType - modification function is not defined", 2); elseif(type(modifyFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterRegionType - modification function is not a function", 2) elseif not(default) then error("Improper arguments to WeakAuras.RegisterRegionType - default options are not defined", 2); elseif(type(default) ~= "table") then error("Improper arguments to WeakAuras.RegisterRegionType - default options are not a table", 2); elseif(type(default) ~= "table" and type(default) ~= "nil") then error("Improper arguments to WeakAuras.RegisterRegionType - properties options are not a table", 2); elseif(regionTypes[name]) then error("Improper arguments to WeakAuras.RegisterRegionType - region type \""..name.."\" already defined", 2); else regionTypes[name] = { create = createFunction, modify = modifyFunction, default = default, validate = validate, properties = properties, }; end end function WeakAuras.RegisterSubRegionType(name, displayName, supportFunction, createFunction, modifyFunction, onAcquire, onRelease, default, addDefaultsForNewAura, properties, supportsAdd) if not(name) then error("Improper arguments to WeakAuras.RegisterSubRegionType - name is not defined", 2); elseif(type(name) ~= "string") then error("Improper arguments to WeakAuras.RegisterSubRegionType - name is not a string", 2); elseif not(displayName) then error("Improper arguments to WeakAuras.RegisterSubRegionType - display name is not defined".." "..name, 2); elseif(type(displayName) ~= "string") then error("Improper arguments to WeakAuras.RegisterSubRegionType - display name is not a string", 2); elseif not(supportFunction) then error("Improper arguments to WeakAuras.RegisterSubRegionType - support function is not defined", 2); elseif(type(supportFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - support function is not a function", 2); elseif not(createFunction) then error("Improper arguments to WeakAuras.RegisterSubRegionType - creation function is not defined", 2); elseif(type(createFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - creation function is not a function", 2); elseif not(modifyFunction) then error("Improper arguments to WeakAuras.RegisterSubRegionType - modification function is not defined", 2); elseif(type(modifyFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - modification function is not a function", 2) elseif not(onAcquire) then error("Improper arguments to WeakAuras.RegisterSubRegionType - onAcquire function is not defined", 2); elseif(type(onAcquire) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - onAcquire function is not a function", 2) elseif not(onRelease) then error("Improper arguments to WeakAuras.RegisterSubRegionType - onRelease function is not defined", 2); elseif(type(onRelease) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - onRelease function is not a function", 2) elseif not(default) then error("Improper arguments to WeakAuras.RegisterSubRegionType - default options are not defined", 2); elseif(type(default) ~= "table" and type(default) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - default options are not a table or a function", 2); elseif(addDefaultsForNewAura and type(addDefaultsForNewAura) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionType - addDefaultsForNewAura function is not nil or a function", 2) elseif(subRegionTypes[name]) then error("Improper arguments to WeakAuras.RegisterSubRegionType - region type \""..name.."\" already defined", 2); else local pool = CreateObjectPool(createFunction) subRegionTypes[name] = { displayName = displayName, supports = supportFunction, modify = modifyFunction, default = default, addDefaultsForNewAura = addDefaultsForNewAura, properties = properties, supportsAdd = supportsAdd == nil or supportsAdd, acquire = function() local subRegion = pool:Acquire() onAcquire(subRegion) subRegion.type = name return subRegion end, release = function(subRegion) onRelease(subRegion) pool:Release(subRegion) end }; end end function WeakAuras.RegisterRegionOptions(name, createFunction, icon, displayName, createThumbnail, modifyThumbnail, description, templates, getAnchors) if not(name) then error("Improper arguments to WeakAuras.RegisterRegionOptions - name is not defined", 2); elseif(type(name) ~= "string") then error("Improper arguments to WeakAuras.RegisterRegionOptions - name is not a string", 2); elseif not(createFunction) then error("Improper arguments to WeakAuras.RegisterRegionOptions - creation function is not defined", 2); elseif(type(createFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterRegionOptions - creation function is not a function", 2); elseif not(icon) then error("Improper arguments to WeakAuras.RegisterRegionOptions - icon is not defined", 2); elseif not(type(icon) == "string" or type(icon) == "function") then error("Improper arguments to WeakAuras.RegisterRegionOptions - icon is not a string or a function", 2) elseif not(displayName) then error("Improper arguments to WeakAuras.RegisterRegionOptions - display name is not defined".." "..name, 2); elseif(type(displayName) ~= "string") then error("Improper arguments to WeakAuras.RegisterRegionOptions - display name is not a string", 2); elseif (getAnchors and type(getAnchors) ~= "function") then error("Improper arguments to WeakAuras.RegisterRegionOptions - anchors is not a function", 2); elseif(regionOptions[name]) then error("Improper arguments to WeakAuras.RegisterRegionOptions - region type \""..name.."\" already defined", 2); else if (type(icon) == "function") then -- We only want to create one icon and reparent it as needed icon = icon() icon:Hide() end local acquireThumbnail, releaseThumbnail if createThumbnail and modifyThumbnail then local thumbnailPool = CreateObjectPool(createThumbnail) acquireThumbnail = function(parent, data) local thumbnail, newObject = thumbnailPool:Acquire() thumbnail:Show() modifyThumbnail(parent, thumbnail, data) return thumbnail end releaseThumbnail = function(thumbnail) thumbnail:Hide() thumbnailPool:Release(thumbnail) end end regionOptions[name] = { create = createFunction, icon = icon, displayName = displayName, createThumbnail = createThumbnail, modifyThumbnail = modifyThumbnail, acquireThumbnail = acquireThumbnail, releaseThumbnail = releaseThumbnail, description = description, templates = templates, getAnchors = getAnchors }; end end function WeakAuras.RegisterSubRegionOptions(name, createFunction, description) if not(name) then error("Improper arguments to WeakAuras.RegisterSubRegionOptions - name is not defined", 2); elseif(type(name) ~= "string") then error("Improper arguments to WeakAuras.RegisterSubRegionOptions - name is not a string", 2); elseif not(createFunction) then error("Improper arguments to WeakAuras.RegisterSubRegionOptions - creation function is not defined", 2); elseif(type(createFunction) ~= "function") then error("Improper arguments to WeakAuras.RegisterSubRegionOptions - creation function is not a function", 2); elseif(subRegionOptions[name]) then error("Improper arguments to WeakAuras.RegisterSubRegionOptions - region type \""..name.."\" already defined", 2); else subRegionOptions[name] = { create = createFunction, description = description, }; end end -- This function is replaced in WeakAurasOptions.lua function WeakAuras.IsOptionsOpen() return false; end function Private.ParseNumber(numString) if not(numString and type(numString) == "string") then if(type(numString) == "number") then return numString, "notastring"; else return nil; end elseif(numString:sub(-1) == "%") then local percent = tonumber(numString:sub(1, -2)); if(percent) then return percent / 100, "percent"; else return nil; end else -- Matches any string with two integers separated by a forward slash -- Captures the two integers local _, _, numerator, denominator = numString:find("(%d+)%s*/%s*(%d+)"); numerator, denominator = tonumber(numerator), tonumber(denominator); if(numerator and denominator) then if(denominator == 0) then return nil; else return numerator / denominator, "fraction"; end else local num = tonumber(numString) if(num) then if(math.floor(num) ~= num) then return num, "decimal"; else return num, "whole"; end else return nil; end end end end -- Used for the load function, could be simplified a bit -- It used to be also used for the generic trigger system local function ConstructFunction(prototype, trigger, skipOptional) local input = {"event"}; local required = {}; local tests = {}; local debug = {}; local events = {} local init; local preambles = "" if(prototype.init) then init = prototype.init(trigger); else init = ""; end for index, arg in pairs(prototype.args) do local enable = arg.type ~= "collpase"; if(type(arg.enable) == "function") then enable = arg.enable(trigger); elseif type(arg.enable) == "boolean" then enable = arg.enable end if(enable) then local name = arg.name; if not(arg.name or arg.hidden) then tinsert(input, "_"); else if(arg.init == "arg") then tinsert(input, name); end if (arg.optional and skipOptional) then -- Do nothing elseif(arg.hidden or arg.type == "tristate" or arg.type == "toggle" or arg.type == "tristatestring" or (arg.type == "multiselect" and trigger["use_"..name] ~= nil) or ((trigger["use_"..name] or arg.required) and trigger[name])) then if(arg.init and arg.init ~= "arg") then init = init.."local "..name.." = "..arg.init.."\n"; end local number = trigger[name] and tonumber(trigger[name]); local test; if(arg.type == "tristate") then if(trigger["use_"..name] == false) then test = "(not "..name..")"; elseif(trigger["use_"..name]) then if(arg.test) then test = "("..arg.test:format(trigger[name])..")"; else test = name; end end elseif(arg.type == "tristatestring") then if(trigger["use_"..name] == false) then test = "("..name.. "~=".. (number or string.format("%q", trigger[name] or "")) .. ")" elseif(trigger["use_"..name]) then test = "("..name.. "==".. (number or string.format("%q", trigger[name] or "")) .. ")" end elseif(arg.type == "multiselect") then if(trigger["use_"..name] == false) then -- multi selection local any = false; if (trigger[name] and trigger[name].multi) then test = "("; for value, _ in pairs(trigger[name].multi) do if not arg.test then test = test..name.."=="..(tonumber(value) or "[["..value.."]]").." or "; else test = test..arg.test:format(tonumber(value) or "[["..value.."]]").." or "; end any = true; end if(any) then test = test:sub(1, -5); else test = "(false"; end test = test..")"; end elseif(trigger["use_"..name]) then -- single selection local value = trigger[name] and trigger[name].single; if not arg.test then test = trigger[name] and trigger[name].single and "("..name.."=="..(tonumber(value) or "[["..value.."]]")..")"; else test = trigger[name] and trigger[name].single and "("..arg.test:format(tonumber(value) or "[["..value.."]]")..")"; end end elseif(arg.type == "toggle") then if(trigger["use_"..name]) then if(arg.test) then test = "("..arg.test:format(trigger[name])..")"; else test = name; end end elseif (arg.type == "spell") then if arg.showExactOption then test = "("..arg.test:format(trigger[name], tostring(trigger["use_exact_" .. name]) or "false") ..")"; else test = "("..arg.test:format(trigger[name])..")"; end elseif(arg.test) then test = "("..arg.test:format(trigger[name])..")"; elseif(arg.type == "longstring" and trigger[name.."_operator"]) then if(trigger[name.."_operator"] == "==") then test = "("..name.."==[["..trigger[name].."]])"; else test = "("..name..":"..trigger[name.."_operator"]:format(trigger[name])..")"; end else if(type(trigger[name]) == "table") then trigger[name] = "error"; end test = "("..name..(trigger[name.."_operator"] or "==")..(number or "[["..(trigger[name] or "").."]]")..")"; end if (arg.preamble) then preambles = preambles .. arg.preamble:format(trigger[name]) .. "\n" end if test ~= "(test)" then if(arg.required) then tinsert(required, test); else tinsert(tests, test); end end if test and arg.events then for index, event in ipairs(arg.events) do events[event] = true end end if(arg.debug) then tinsert(debug, arg.debug:format(trigger[name])); end end end end end local ret = preambles .. "return function("..table.concat(input, ", ")..")\n"; ret = ret..(init or ""); ret = ret..(#debug > 0 and table.concat(debug, "\n") or ""); ret = ret.."if("; ret = ret..((#required > 0) and table.concat(required, " and ").." and " or ""); ret = ret..(#tests > 0 and table.concat(tests, " and ") or "true"); ret = ret..") then\n"; if(#debug > 0) then ret = ret.."print('ret: true');\n"; end ret = ret.."return true else return false end end"; return ret, events; end function WeakAuras.GetActiveConditions(id, cloneId) triggerState[id].activatedConditions[cloneId] = triggerState[id].activatedConditions[cloneId] or {}; return triggerState[id].activatedConditions[cloneId]; end local function LoadCustomActionFunctions(data) local id = data.id; Private.customActionsFunctions[id] = {}; if (data.actions) then if (data.actions.init and data.actions.init.do_custom and data.actions.init.custom) then local func = WeakAuras.LoadFunction("return function() "..(data.actions.init.custom).."\n end", id, "initialization"); Private.customActionsFunctions[id]["init"] = func; end if (data.actions.start) then if (data.actions.start.do_custom and data.actions.start.custom) then local func = WeakAuras.LoadFunction("return function() "..(data.actions.start.custom).."\n end", id, "show action"); Private.customActionsFunctions[id]["start"] = func; end if (data.actions.start.do_message and data.actions.start.message_custom) then local func = WeakAuras.LoadFunction("return "..(data.actions.start.message_custom), id, "show message"); Private.customActionsFunctions[id]["start_message"] = func; end end if (data.actions.finish) then if (data.actions.finish.do_custom and data.actions.finish.custom) then local func = WeakAuras.LoadFunction("return function() "..(data.actions.finish.custom).."\n end", id, "hide action"); Private.customActionsFunctions[id]["finish"] = func; end if (data.actions.finish.do_message and data.actions.finish.message_custom) then local func = WeakAuras.LoadFunction("return "..(data.actions.finish.message_custom), id, "hide message"); Private.customActionsFunctions[id]["finish_message"] = func; end end end end Private.talent_types_specific = {} Private.pvp_talent_types_specific = {} local function CreateTalentCache() local _, player_class = UnitClass("player") Private.talent_types_specific[player_class] = Private.talent_types_specific[player_class] or {}; if WeakAuras.IsClassic() then for tab = 1, GetNumTalentTabs() do for num_talent = 1, GetNumTalents(tab) do local talentName, talentIcon = GetTalentInfo(tab, num_talent); local talentId = (tab - 1)*20+num_talent if (talentName and talentIcon) then Private.talent_types_specific[player_class][talentId] = "|T"..talentIcon..":0|t "..talentName end end end else local spec = GetSpecialization() Private.talent_types_specific[player_class][spec] = Private.talent_types_specific[player_class][spec] or {}; for tier = 1, MAX_TALENT_TIERS do for column = 1, NUM_TALENT_COLUMNS do -- Get name and icon info for the current talent of the current class and save it local _, talentName, talentIcon = GetTalentInfo(tier, column, 1) local talentId = (tier-1)*3+column -- Get the icon and name from the talent cache and record it in the table that will be used by WeakAurasOptions if (talentName and talentIcon) then Private.talent_types_specific[player_class][spec][talentId] = "|T"..talentIcon..":0|t "..talentName end end end end end local pvpTalentsInitialized = false; local function CreatePvPTalentCache() if (pvpTalentsInitialized) then return end; local _, player_class = UnitClass("player") local spec = GetSpecialization() if (not player_class or not spec) then return; end Private.pvp_talent_types_specific[player_class] = Private.pvp_talent_types_specific[player_class] or {}; Private.pvp_talent_types_specific[player_class][spec] = Private.pvp_talent_types_specific[player_class][spec] or {}; local function formatTalent(talentId) local _, name, icon = GetPvpTalentInfoByID(talentId); return "|T"..icon..":0|t "..name end local slotInfo = C_SpecializationInfo.GetPvpTalentSlotInfo(1); if (slotInfo) then Private.pvp_talent_types_specific[player_class][spec] = {}; local pvpSpecTalents = slotInfo.availableTalentIDs; for i, talentId in ipairs(pvpSpecTalents) do Private.pvp_talent_types_specific[player_class][spec][i] = formatTalent(talentId); end pvpTalentsInitialized = true; end end function WeakAuras.CountWagoUpdates() if not (WeakAurasCompanion and WeakAurasCompanion.slugs) then return 0 end local WeakAurasSaved = WeakAurasSaved local updatedSlugs, updatedSlugsCount = {}, 0 for id, aura in pairs(WeakAurasSaved.displays) do if not aura.ignoreWagoUpdate and aura.url and aura.url ~= "" then local slug, version = aura.url:match("wago.io/([^/]+)/([0-9]+)") if not slug and not version then slug = aura.url:match("wago.io/([^/]+)$") version = 1 end if slug and version then local wago = WeakAurasCompanion.slugs[slug] if wago and wago.wagoVersion and tonumber(wago.wagoVersion) > ( aura.skipWagoUpdate and tonumber(aura.skipWagoUpdate) or tonumber(version) ) then if not updatedSlugs[slug] then updatedSlugs[slug] = true updatedSlugsCount = updatedSlugsCount + 1 end end end end end return updatedSlugsCount end local function tooltip_draw() local tooltip = GameTooltip; tooltip:ClearLines(); tooltip:AddDoubleLine("WeakAuras", versionString); if WeakAurasCompanion then local count = WeakAuras.CountWagoUpdates() if count > 0 then tooltip:AddLine(" "); tooltip:AddLine((L["There are %i updates to your auras ready to be installed!"]):format(count)); end end tooltip:AddLine(" "); tooltip:AddLine(L["|cffeda55fLeft-Click|r to toggle showing the main window."], 0.2, 1, 0.2); if not WeakAuras.IsOptionsOpen() then if paused then tooltip:AddLine("|cFFFF0000"..L["Paused"].." - "..L["Shift-Click to resume addon execution."], 0.2, 1, 0.2); else tooltip:AddLine(L["|cffeda55fShift-Click|r to pause addon execution."], 0.2, 1, 0.2); end end tooltip:AddLine(L["|cffeda55fRight-Click|r to toggle performance profiling window."], 0.2, 1, 0.2); tooltip:AddLine(L["|cffeda55fMiddle-Click|r to toggle the minimap icon on or off."], 0.2, 1, 0.2); tooltip:Show(); end local colorFrame = CreateFrame("frame"); WeakAuras.frames["LDB Icon Recoloring"] = colorFrame; local colorElapsed = 0; local colorDelay = 2; local r, g, b = 0.8, 0, 1; local r2, g2, b2 = random(2)-1, random(2)-1, random(2)-1; local tooltip_update_frame = CreateFrame("FRAME"); WeakAuras.frames["LDB Tooltip Updater"] = tooltip_update_frame; -- function copied from LibDBIcon-1.0.lua local function getAnchors(frame) local x, y = frame:GetCenter() if not x or not y then return "CENTER" end local hHalf = (x > UIParent:GetWidth()*2/3) and "RIGHT" or (x < UIParent:GetWidth()/3) and "LEFT" or "" local vHalf = (y > UIParent:GetHeight()/2) and "TOP" or "BOTTOM" return vHalf..hHalf, frame, (vHalf == "TOP" and "BOTTOM" or "TOP")..hHalf end local Broker_WeakAuras; Broker_WeakAuras = LDB:NewDataObject("WeakAuras", { type = "launcher", text = "WeakAuras", icon = "Interface\\AddOns\\WeakAuras\\Media\\Textures\\icon.blp", OnClick = function(self, button) if button == 'LeftButton' then if(IsShiftKeyDown()) then if not(WeakAuras.IsOptionsOpen()) then WeakAuras.Toggle(); end else WeakAuras.OpenOptions(); end elseif(button == 'MiddleButton') then Private.ToggleMinimap(); else WeakAuras.RealTimeProfilingWindow:Toggle() end tooltip_draw() end, OnEnter = function(self) colorFrame:SetScript("OnUpdate", function(self, elaps) colorElapsed = colorElapsed + elaps; if(colorElapsed > colorDelay) then colorElapsed = colorElapsed - colorDelay; r, g, b = r2, g2, b2; r2, g2, b2 = random(2)-1, random(2)-1, random(2)-1; end Broker_WeakAuras.iconR = r + (r2 - r) * colorElapsed / colorDelay; Broker_WeakAuras.iconG = g + (g2 - g) * colorElapsed / colorDelay; Broker_WeakAuras.iconB = b + (b2 - b) * colorElapsed / colorDelay; end); local elapsed = 0; local delay = 1; tooltip_update_frame:SetScript("OnUpdate", function(self, elap) elapsed = elapsed + elap; if(elapsed > delay) then elapsed = 0; tooltip_draw(); end end); GameTooltip:SetOwner(self, "ANCHOR_NONE"); GameTooltip:SetPoint(getAnchors(self)) tooltip_draw(); end, OnLeave = function(self) colorFrame:SetScript("OnUpdate", nil); tooltip_update_frame:SetScript("OnUpdate", nil); GameTooltip:Hide(); end, iconR = 0.6, iconG = 0, iconB = 1 }); do -- Archive stuff local Archivist = select(2, ...).Archivist local function OpenArchive() if Archivist:IsInitialized() then return Archivist else if not IsAddOnLoaded("WeakAurasArchive") then local ok, reason = LoadAddOn("WeakAurasArchive") if not ok then error("Could not load WeakAuras Archive, reason: |cFFFF00" .. (reason or "UNKNOWN")) end end Archivist:Initialize(WeakAurasArchive) end return Archivist end function WeakAuras.LoadFromArchive(storeType, storeID) local Archivist = OpenArchive() return Archivist:Load(storeType, storeID) end end local loginFinished, loginMessage = false, L["Options will open after the login process has completed."] function WeakAuras.IsLoginFinished() return loginFinished end function Private.LoginMessage() return loginMessage end local function CheckForPreviousEncounter() if (UnitAffectingCombat ("player") or InCombatLockdown()) then for i = 1, 5 do if (UnitExists ("boss" .. i)) then local guid = UnitGUID ("boss" .. i) if (guid and db.CurrentEncounter.boss_guids [guid]) then -- we are in the same encounter WeakAuras.CurrentEncounter = db.CurrentEncounter return true end end end db.CurrentEncounter = nil else db.CurrentEncounter = nil end end function Private.Login(initialTime, takeNewSnapshots) local loginThread = coroutine.create(function() Private.Pause(); if db.history then local histRepo = WeakAuras.LoadFromArchive("Repository", "history") local migrationRepo = WeakAuras.LoadFromArchive("Repository", "migration") for uid, hist in pairs(db.history) do local histStore = histRepo:Set(uid, hist.data) local migrationStore = migrationRepo:Set(uid, hist.migration) coroutine.yield() end -- history is now in archive so we can shrink WeakAurasSaved db.history = nil coroutine.yield(); end local toAdd = {}; loginFinished = false loginMessage = L["Options will open after the login process has completed."] for id, data in pairs(db.displays) do if(id ~= data.id) then print("|cFF8800FFWeakAuras|r detected a corrupt entry in WeakAuras saved displays - '"..tostring(id).."' vs '"..tostring(data.id).."'" ); data.id = id; end tinsert(toAdd, data); end coroutine.yield(); WeakAuras.AddMany(toAdd, takeNewSnapshots); coroutine.yield(); WeakAuras.AddManyFromAddons(from_files); WeakAuras.RegisterDisplay = WeakAuras.AddFromAddon; coroutine.yield(); Private.ResolveCollisions(function() registeredFromAddons = true; end); coroutine.yield(); -- check in case of a disconnect during an encounter. if (db.CurrentEncounter) then CheckForPreviousEncounter() end coroutine.yield(); Private.RegisterLoadEvents(); Private.Resume(); coroutine.yield(); local nextCallback = loginQueue[1]; while nextCallback do tremove(loginQueue, 1); if type(nextCallback) == 'table' then nextCallback[1](unpack(nextCallback[2])) else nextCallback() end coroutine.yield(); nextCallback = loginQueue[1]; end loginFinished = true Private.ResumeAllDynamicGroups(); end) if initialTime then local startTime = debugprofilestop() local finishTime = debugprofilestop() local ok, msg -- hard limit seems to be 19 seconds. We'll do 15 for now. while coroutine.status(loginThread) ~= 'dead' and finishTime - startTime < 15000 do ok, msg = coroutine.resume(loginThread) finishTime = debugprofilestop() end if coroutine.status(loginThread) ~= 'dead' then Private.dynFrame:AddAction('login', loginThread) end if not ok then loginMessage = L["WeakAuras has encountered an error during the login process. Please report this issue at https://github.com/WeakAuras/Weakauras2/issues/new."] .. "\nMessage:" .. msg geterrorhandler()(msg .. '\n' .. debugstack(loginThread)) end else Private.dynFrame:AddAction('login', loginThread) end end local frame = CreateFrame("FRAME", "WeakAurasFrame", UIParent); WeakAuras.frames["WeakAuras Main Frame"] = frame; frame:SetAllPoints(UIParent); local loadedFrame = CreateFrame("FRAME"); WeakAuras.frames["Addon Initialization Handler"] = loadedFrame; loadedFrame:RegisterEvent("ADDON_LOADED"); loadedFrame:RegisterEvent("PLAYER_LOGIN"); loadedFrame:RegisterEvent("PLAYER_ENTERING_WORLD"); loadedFrame:RegisterEvent("LOADING_SCREEN_ENABLED"); loadedFrame:RegisterEvent("LOADING_SCREEN_DISABLED"); if not WeakAuras.IsClassic() then loadedFrame:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED"); loadedFrame:RegisterEvent("PLAYER_PVP_TALENT_UPDATE"); else loadedFrame:RegisterEvent("CHARACTER_POINTS_CHANGED"); loadedFrame:RegisterEvent("SPELLS_CHANGED"); end loadedFrame:SetScript("OnEvent", function(self, event, addon) if(event == "ADDON_LOADED") then if(addon == ADDON_NAME) then WeakAurasSaved = WeakAurasSaved or {}; db = WeakAurasSaved; -- Defines the action squelch period after login -- Stored in SavedVariables so it can be changed by the user if they find it necessary db.login_squelch_time = db.login_squelch_time or 10; -- Deprecated fields with *lots* of data, clear them out db.iconCache = nil; db.iconHash = nil; db.tempIconCache = nil; db.dynamicIconCache = db.dynamicIconCache or {}; db.displays = db.displays or {}; db.registered = db.registered or {}; Private.UpdateCurrentInstanceType(); Private.SyncParentChildRelationships(); local isFirstUIDValidation = db.dbVersion == nil or db.dbVersion < 26; Private.ValidateUniqueDataIds(isFirstUIDValidation); if db.lastArchiveClear == nil then db.lastArchiveClear = time(); elseif db.lastArchiveClear < time() - 86400 then Private.CleanArchive(db.historyCutoff, db.migrationCutoff); end db.minimap = db.minimap or { hide = false }; LDBIcon:Register("WeakAuras", Broker_WeakAuras, db.minimap); end elseif(event == "PLAYER_LOGIN") then local dbIsValid, takeNewSnapshots if not db.dbVersion or db.dbVersion < internalVersion then -- db is out of date, will run any necessary migrations in AddMany db.dbVersion = internalVersion db.lastUpgrade = time() dbIsValid = true takeNewSnapshots = true elseif db.dbVersion > internalVersion then -- user has downgraded past a forwards-incompatible migration dbIsValid = false else -- db has same version as code, can commit to login dbIsValid = true end if dbIsValid then -- run login thread for up to 15 seconds, then defer to dynFrame Private.Login(15000, takeNewSnapshots) else -- db isn't valid. Request permission to run repair tool before logging in StaticPopup_Show("WEAKAURAS_CONFIRM_REPAIR", nil, nil, {reason = "downgrade"}) end elseif(event == "LOADING_SCREEN_ENABLED") then in_loading_screen = true; elseif(event == "LOADING_SCREEN_DISABLED") then in_loading_screen = false; else local callback if(event == "PLAYER_ENTERING_WORLD") then -- Schedule events that need to be handled some time after login local now = GetTime() callback = function() local elapsed = GetTime() - now local remainingSquelch = db.login_squelch_time - elapsed if remainingSquelch > 0 then timer:ScheduleTimer(function() squelch_actions = false; end, remainingSquelch); -- No sounds while loading end CreateTalentCache() -- It seems that GetTalentInfo might give info about whatever class was previously being played, until PLAYER_ENTERING_WORLD Private.UpdateCurrentInstanceType(); Private.InitializeEncounterAndZoneLists() end elseif(event == "PLAYER_PVP_TALENT_UPDATE") then callback = CreatePvPTalentCache; elseif(event == "ACTIVE_TALENT_GROUP_CHANGED" or event == "CHARACTER_POINTS_CHANGED" or event == "SPELLS_CHANGED") then callback = CreateTalentCache; elseif(event == "PLAYER_REGEN_ENABLED") then callback = function() if (queueshowooc) then WeakAuras.OpenOptions(queueshowooc) queueshowooc = nil WeakAuras.frames["Addon Initialization Handler"]:UnregisterEvent("PLAYER_REGEN_ENABLED") end end end if WeakAuras.IsLoginFinished() then callback() else loginQueue[#loginQueue + 1] = callback end end end) function WeakAuras.SetImporting(b) importing = b; Private.RefreshTooltipButtons() end function WeakAuras.IsImporting() return importing; end function WeakAuras.IsPaused() return paused; end function Private.Pause() -- Forcibly hide all displays, and clear all trigger information (it will be restored on .Resume() due to forced events) for id, region in pairs(regions) do region.region:Collapse(); -- ticket 366 end for id, cloneList in pairs(clones) do for cloneId, clone in pairs(cloneList) do clone:Collapse(); end end paused = true; end function WeakAuras.Toggle() if(paused) then Private.Resume(); else Private.Pause(); end end function Private.SquelchingActions() return squelch_actions; end function WeakAuras.InLoadingScreen() return in_loading_screen; end function Private.PauseAllDynamicGroups() for id, region in pairs(regions) do if (region.region.Suspend) then region.region:Suspend(); end end end function Private.ResumeAllDynamicGroups() for id, region in pairs(regions) do if (region.region.Resume) then region.region:Resume(); end end end -- Encounter stuff local function StoreBossGUIDs() Private.StartProfileSystem("boss_guids") if (WeakAuras.CurrentEncounter and WeakAuras.CurrentEncounter.boss_guids) then for i = 1, 5 do if (UnitExists ("boss" .. i)) then local guid = UnitGUID ("boss" .. i) if (guid) then WeakAuras.CurrentEncounter.boss_guids [guid] = true end end end db.CurrentEncounter = WeakAuras.CurrentEncounter end Private.StopProfileSystem("boss_guids") end local function DestroyEncounterTable() if (WeakAuras.CurrentEncounter) then wipe(WeakAuras.CurrentEncounter) end WeakAuras.CurrentEncounter = nil db.CurrentEncounter = nil end local function CreateEncounterTable(encounter_id) local _, _, _, _, _, _, _, ZoneMapID = GetInstanceInfo() WeakAuras.CurrentEncounter = { id = encounter_id, zone_id = ZoneMapID, boss_guids = {}, } timer:ScheduleTimer(StoreBossGUIDs, 2) return WeakAuras.CurrentEncounter end local encounterScriptsDeferred = {} local function LoadEncounterInitScriptsImpl(id) if (currentInstanceType ~= "raid") then return end if (id) then local data = db.displays[id] if (data and data.load.use_encounterid and not Private.IsEnvironmentInitialized(id) and data.actions.init and data.actions.init.do_custom) then Private.ActivateAuraEnvironment(id) Private.ActivateAuraEnvironment(nil) end encounterScriptsDeferred[id] = nil else for id, data in pairs(db.displays) do if (data.load.use_encounterid and not Private.IsEnvironmentInitialized(id) and data.actions.init and data.actions.init.do_custom) then Private.ActivateAuraEnvironment(id) Private.ActivateAuraEnvironment(nil) end end end end local function LoadEncounterInitScripts(id) if not WeakAuras.IsLoginFinished() then if encounterScriptsDeferred[id] then return end loginQueue[#loginQueue + 1] = {LoadEncounterInitScriptsImpl, {id}} encounterScriptsDeferred[id] = true return end LoadEncounterInitScriptsImpl(id) end function Private.UpdateCurrentInstanceType(instanceType) if (not IsInInstance()) then currentInstanceType = "none" else currentInstanceType = instanceType or select (2, GetInstanceInfo()) end end local pausedOptionsProcessing = false; function Private.pauseOptionsProcessing(enable) pausedOptionsProcessing = enable; end function Private.IsOptionsProcessingPaused() return pausedOptionsProcessing; end function WeakAuras.GroupType() if (IsInRaid()) then return "raid"; end if (IsInGroup()) then return "group"; end return "solo"; end local function GetInstanceTypeAndSize() local size, difficulty local inInstance, Type = IsInInstance() local _, instanceType, difficultyIndex, _, _, _, _, ZoneMapID = GetInstanceInfo() if (inInstance) then size = Type local difficultyInfo = Private.difficulty_info[difficultyIndex] if difficultyInfo then size, difficulty = difficultyInfo.size, difficultyInfo.difficulty end return size, difficulty, instanceType, ZoneMapID, difficultyIndex end return "none", "none", nil, nil, nil end function WeakAuras.InstanceType() return GetInstanceTypeAndSize(), nil end function WeakAuras.InstanceDifficulty() return select(2, GetInstanceTypeAndSize()) end function WeakAuras.InstanceTypeRaw() return select(5, GetInstanceTypeAndSize()) end local toLoad = {} local toUnload = {}; local function scanForLoadsImpl(toCheck, event, arg1, ...) if (Private.IsOptionsProcessingPaused()) then return; end toCheck = toCheck or loadEvents[event or "SCAN_ALL"] -- PET_BATTLE_CLOSE fires twice at the end of a pet battle. IsInBattle evaluates to TRUE during the -- first firing, and FALSE during the second. I am not sure if this check is necessary, but the -- following IF statement limits the impact of the PET_BATTLE_CLOSE event to the second one. if (event == "PET_BATTLE_CLOSE" and C_PetBattles.IsInBattle()) then return end if (event == "PLAYER_LEVEL_UP") then playerLevel = arg1; end -- encounter id stuff, we are holding the current combat id to further load checks. -- there is three ways to unload: encounter_end / zone changed (hearthstone used) / reload or disconnect -- regen_enabled isn't good due to combat drop abilities such invisibility, vanish, fake death, etc. local encounter_id = WeakAuras.CurrentEncounter and WeakAuras.CurrentEncounter.id or 0 if (event == "ENCOUNTER_START") then encounter_id = tonumber (arg1) CreateEncounterTable (encounter_id) elseif (event == "ENCOUNTER_END") then encounter_id = 0 DestroyEncounterTable() end if toCheck == nil or next(toCheck) == nil then return end local player, realm, zone = UnitName("player"), GetRealmName(), GetRealZoneText() local spec, specId, covenant, role, raidRole = false, false, false, false, false local inPetBattle, vehicle, vehicleUi = false, false, false local zoneId = C_Map.GetBestMapForUnit("player") local zonegroupId = zoneId and C_Map.GetMapGroupID(zoneId) local _, race = UnitRace("player") local faction = UnitFactionGroup("player") local _, class = UnitClass("player") local inCombat = UnitAffectingCombat("player") local inEncounter = encounter_id ~= 0; if WeakAuras.IsClassic() then local raidID = UnitInRaid("player") if raidID then raidRole = select(10, GetRaidRosterInfo(raidID)) end spec = 1 vehicle = UnitOnTaxi('player') role = "none" else spec = GetSpecialization() specId = GetSpecializationInfo(spec) role = select(5, GetSpecializationInfo(spec)) covenant = C_Covenants.GetActiveCovenantID() inPetBattle = C_PetBattles.IsInBattle() vehicle = UnitInVehicle('player') or UnitOnTaxi('player') vehicleUi = UnitHasVehicleUI('player') or HasOverrideActionBar() or HasVehicleActionBar() end local size, difficulty, instanceType, ZoneMapID, difficultyIndex = GetInstanceTypeAndSize() Private.UpdateCurrentInstanceType(instanceType) if (WeakAuras.CurrentEncounter) then if (ZoneMapID ~= WeakAuras.CurrentEncounter.zone_id and not inCombat) then encounter_id = 0 DestroyEncounterTable() end end if (event == "ZONE_CHANGED_NEW_AREA") then LoadEncounterInitScripts(); end local group = WeakAuras.GroupType() local affixes, warmodeActive, effectiveLevel = 0, false, 0 if not WeakAuras.IsClassic() then effectiveLevel = UnitEffectiveLevel("player") affixes = C_ChallengeMode.IsChallengeModeActive() and select(2, C_ChallengeMode.GetActiveKeystoneInfo()) warmodeActive = C_PvP.IsWarModeDesired(); end local changed = 0; local shouldBeLoaded, couldBeLoaded; wipe(toLoad); wipe(toUnload); for id in pairs(toCheck) do local data = WeakAuras.GetData(id) if (data and not data.controlledChildren) then local loadFunc = loadFuncs[id]; local loadOpt = loadFuncsForOptions[id]; if WeakAuras.IsClassic() then shouldBeLoaded = loadFunc and loadFunc("ScanForLoads_Auras", inCombat, inEncounter, vehicle, group, player, realm, class, race, faction, playerLevel, zone, encounter_id, size, raidRole); couldBeLoaded = loadOpt and loadOpt("ScanForLoads_Auras", inCombat, inEncounter, vehicle, group, player, realm, class, race, faction, playerLevel, zone, encounter_id, size, raidRole); else shouldBeLoaded = loadFunc and loadFunc("ScanForLoads_Auras", inCombat, inEncounter, warmodeActive, inPetBattle, vehicle, vehicleUi, group, player, realm, class, spec, specId, covenant, race, faction, playerLevel, effectiveLevel, zone, zoneId, zonegroupId, encounter_id, size, difficulty, difficultyIndex, role, affixes); couldBeLoaded = loadOpt and loadOpt("ScanForLoads_Auras", inCombat, inEncounter, warmodeActive, inPetBattle, vehicle, vehicleUi, group, player, realm, class, spec, specId, covenant, race, faction, playerLevel, effectiveLevel, zone, zoneId, zonegroupId, encounter_id, size, difficulty, difficultyIndex, role, affixes); end if(shouldBeLoaded and not loaded[id]) then changed = changed + 1; toLoad[id] = true; end if(loaded[id] and not shouldBeLoaded) then toUnload[id] = true; changed = changed + 1; end if(shouldBeLoaded) then loaded[id] = true; elseif(couldBeLoaded) then loaded[id] = false; else loaded[id] = nil; end end end if(changed > 0 and not paused) then Private.LoadDisplays(toLoad, event, arg1, ...); Private.UnloadDisplays(toUnload, event, arg1, ...); Private.FinishLoadUnload(); end for id, data in pairs(db.displays) do if(data.controlledChildren) then if(#data.controlledChildren > 0) then local any_loaded; for index, childId in pairs(data.controlledChildren) do if(loaded[childId] ~= nil) then any_loaded = true; break; end end loaded[id] = any_loaded; else loaded[id] = true; end end end Private.callbacks:Fire("ScanForLoads") wipe(toLoad); wipe(toUnload) end function Private.ScanForLoads(toCheck, event, arg1, ...) if not WeakAuras.IsLoginFinished() then return end scanForLoadsImpl(toCheck, event, arg1, ...) end local loadFrame = CreateFrame("FRAME"); WeakAuras.loadFrame = loadFrame; WeakAuras.frames["Display Load Handling"] = loadFrame; loadFrame:RegisterEvent("ENCOUNTER_START"); loadFrame:RegisterEvent("ENCOUNTER_END"); if not WeakAuras.IsClassic() then loadFrame:RegisterEvent("PLAYER_TALENT_UPDATE"); loadFrame:RegisterEvent("PLAYER_PVP_TALENT_UPDATE"); loadFrame:RegisterEvent("PLAYER_DIFFICULTY_CHANGED"); loadFrame:RegisterEvent("PET_BATTLE_OPENING_START"); loadFrame:RegisterEvent("PET_BATTLE_CLOSE"); loadFrame:RegisterEvent("VEHICLE_UPDATE"); loadFrame:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR") loadFrame:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR"); loadFrame:RegisterEvent("CHALLENGE_MODE_COMPLETED") loadFrame:RegisterEvent("CHALLENGE_MODE_START") loadFrame:RegisterEvent("COVENANT_CHOSEN") else loadFrame:RegisterEvent("CHARACTER_POINTS_CHANGED") end loadFrame:RegisterEvent("GROUP_ROSTER_UPDATE"); loadFrame:RegisterEvent("ZONE_CHANGED"); loadFrame:RegisterEvent("ZONE_CHANGED_INDOORS"); loadFrame:RegisterEvent("ZONE_CHANGED_NEW_AREA"); loadFrame:RegisterEvent("PLAYER_LEVEL_UP"); loadFrame:RegisterEvent("PLAYER_REGEN_DISABLED"); loadFrame:RegisterEvent("PLAYER_REGEN_ENABLED"); loadFrame:RegisterEvent("PLAYER_ROLES_ASSIGNED"); loadFrame:RegisterEvent("SPELLS_CHANGED"); loadFrame:RegisterEvent("UNIT_INVENTORY_CHANGED") loadFrame:RegisterEvent("PLAYER_EQUIPMENT_CHANGED") local unitLoadFrame = CreateFrame("FRAME"); WeakAuras.unitLoadFrame = unitLoadFrame; WeakAuras.frames["Display Load Handling 2"] = unitLoadFrame; unitLoadFrame:RegisterUnitEvent("UNIT_FLAGS", "player"); if not WeakAuras.IsClassic() then unitLoadFrame:RegisterUnitEvent("UNIT_ENTERED_VEHICLE", "player"); unitLoadFrame:RegisterUnitEvent("UNIT_EXITED_VEHICLE", "player"); end function Private.RegisterLoadEvents() loadFrame:SetScript("OnEvent", function(frame, ...) Private.StartProfileSystem("load"); Private.ScanForLoads(nil, ...) Private.StopProfileSystem("load"); end); C_Timer.NewTicker(0.5, function() Private.StartProfileSystem("load"); local zoneId = C_Map.GetBestMapForUnit("player"); if loadFrame.zoneId ~= zoneId then Private.ScanForLoads(nil, "ZONE_CHANGED") loadFrame.zoneId = zoneId; end Private.StopProfileSystem("load"); end) unitLoadFrame:SetScript("OnEvent", function(frame, e, arg1, ...) Private.StartProfileSystem("load"); if (arg1 == "player") then Private.ScanForLoads(nil, e, arg1, ...) end Private.StopProfileSystem("load"); end); end local function UnloadAll() -- Even though auras are collapsed, their finish animation can be running for id in pairs(loaded) do Private.CancelAnimation(WeakAuras.regions[id].region, true, true, true, true, true, true) if clones[id] then for cloneId, region in pairs(clones[id]) do Private.CancelAnimation(region, true, true, true, true, true, true) end end end for _, v in pairs(triggerState) do for i = 1, v.numTriggers do if (v[i]) then wipe(v[i]); end end end for _, aura in pairs(timers) do for _, trigger in pairs(aura) do for _, record in pairs(trigger) do if (record.handle) then timer:CancelTimer(record.handle); end end end end wipe(timers); Private.UnloadAllConditions() for _, triggerSystem in pairs(triggerSystems) do triggerSystem.UnloadAll(); end wipe(loaded); end function Private.Resume() paused = false; Private.PauseAllDynamicGroups(); for id, region in pairs(regions) do region.region:Collapse(); end for id, cloneList in pairs(clones) do for cloneId, clone in pairs(cloneList) do clone:Collapse(); end end UnloadAll(); scanForLoadsImpl(); Private.ResumeAllDynamicGroups(); end function Private.LoadDisplays(toLoad, ...) for id in pairs(toLoad) do local uid = WeakAuras.GetData(id).uid Private.RegisterForGlobalConditions(uid); triggerState[id].triggers = {}; triggerState[id].triggerCount = 0; triggerState[id].show = false; triggerState[id].activeTrigger = nil; triggerState[id].activatedConditions = {}; end for _, triggerSystem in pairs(triggerSystems) do triggerSystem.LoadDisplays(toLoad, ...); end end function Private.UnloadDisplays(toUnload, ...) for _, triggerSystem in pairs(triggerSystems) do triggerSystem.UnloadDisplays(toUnload, ...); end for id in pairs(toUnload) do -- Even though auras are collapsed, their finish animation can be running Private.CancelAnimation(WeakAuras.regions[id].region, true, true, true, true, true, true) if clones[id] then for cloneId, region in pairs(clones[id]) do Private.CancelAnimation(region, true, true, true, true, true, true) end end for i = 1, triggerState[id].numTriggers do if (triggerState[id][i]) then wipe(triggerState[id][i]); end end triggerState[id].show = nil; triggerState[id].activeTrigger = nil; if (timers[id]) then for _, trigger in pairs(timers[id]) do for _, record in pairs(trigger) do if (record.handle) then timer:CancelTimer(record.handle); end end end timers[id] = nil; end local uid = WeakAuras.GetData(id).uid Private.UnloadConditions(uid) WeakAuras.regions[id].region:Collapse(); Private.CollapseAllClones(id); end end function Private.FinishLoadUnload() for _, triggerSystem in pairs(triggerSystems) do triggerSystem.FinishLoadUnload(); end end -- transient cache of uid => id -- eventually, the database will be migrated to index by uid -- and this mapping will become redundant -- this cache is loaded lazily via pAdd() local UIDtoID = {} function Private.GetDataByUID(uid) return WeakAuras.GetData(UIDtoID[uid]) end function Private.UIDtoID(uid) return UIDtoID[uid] end function WeakAuras.Delete(data) local id = data.id; local uid = data.uid local parentId = data.parent local parentUid = data.parent and db.displays[data.parent].uid Private.callbacks:Fire("AboutToDelete", uid, id, parentUid, parentId) if(data.parent) then local parentData = db.displays[data.parent]; if(parentData and parentData.controlledChildren) then for index, childId in pairs(parentData.controlledChildren) do if(childId == id) then tremove(parentData.controlledChildren, index); end end if parentData.sortHybridTable then parentData.sortHybridTable[id] = nil end Private.ClearAuraEnvironment(data.parent); end end UIDtoID[data.uid] = nil if(data.controlledChildren) then for index, childId in pairs(data.controlledChildren) do local childData = db.displays[childId]; if(childData) then childData.parent = nil; WeakAuras.Add(childData); end end end regions[id].region:Collapse() Private.CollapseAllClones(id); Private.CancelAnimation(WeakAuras.regions[id].region, true, true, true, true, true, true) if clones[id] then for cloneId, region in pairs(clones[id]) do Private.CancelAnimation(region, true, true, true, true, true, true) end end regions[id].region:SetScript("OnUpdate", nil); regions[id].region:SetScript("OnShow", nil); regions[id].region:SetScript("OnHide", nil); regions[id].region:Hide(); db.registered[id] = nil; if(WeakAuras.importDisplayButtons and WeakAuras.importDisplayButtons[id]) then local button = WeakAuras.importDisplayButtons[id]; button.checkbox:SetChecked(false); if(button.updateChecked) then button.updateChecked(); end end for _, triggerSystem in pairs(triggerSystems) do triggerSystem.Delete(id); end regions[id].region = nil; regions[id] = nil; loaded[id] = nil; loadFuncs[id] = nil; loadFuncsForOptions[id] = nil; for event, eventData in pairs(loadEvents) do eventData[id] = nil end db.displays[id] = nil; Private.DeleteAuraEnvironment(id) triggerState[id] = nil; if (Private.personalRessourceDisplayFrame) then Private.personalRessourceDisplayFrame:delete(id); end if (Private.mouseFrame) then Private.mouseFrame:delete(id); end Private.customActionsFunctions[id] = nil; WeakAuras.customConditionsFunctions[id] = nil; WeakAuras.conditionTextFormatters[id] = nil Private.frameLevels[id] = nil; WeakAuras.conditionHelpers[data.uid] = nil Private.RemoveHistory(data.uid) -- Add the parent if parentUid then WeakAuras.Add(Private.GetDataByUID(parentUid)) end Private.callbacks:Fire("Delete", uid, id, parentUid, parentId) end function WeakAuras.Rename(data, newid) local oldid = data.id if(data.parent) then local parentData = db.displays[data.parent]; if(parentData.controlledChildren) then for index, childId in pairs(parentData.controlledChildren) do if(childId == data.id) then parentData.controlledChildren[index] = newid; end end if parentData.sortHybridTable and parentData.sortHybridTable[oldid] then parentData.sortHybridTable[newid] = true parentData.sortHybridTable[oldid] = nil end end local parentRegion = WeakAuras.GetRegion(data.parent) if parentRegion and parentRegion.ReloadControlledChildren then parentRegion:ReloadControlledChildren() end end UIDtoID[data.uid] = newid regions[newid] = regions[oldid]; regions[oldid] = nil; regions[newid].region.id = newid; for _, triggerSystem in pairs(triggerSystems) do triggerSystem.Rename(oldid, newid); end loaded[newid] = loaded[oldid]; loaded[oldid] = nil; loadFuncs[newid] = loadFuncs[oldid]; loadFuncs[oldid] = nil; loadFuncsForOptions[newid] = loadFuncsForOptions[oldid] loadFuncsForOptions[oldid] = nil; for event, eventData in pairs(loadEvents) do eventData[newid] = eventData[oldid] eventData[oldid] = nil end timers[newid] = timers[oldid]; timers[oldid] = nil; triggerState[newid] = triggerState[oldid]; triggerState[oldid] = nil; Private.RenameAuraEnvironment(oldid, newid) db.displays[newid] = db.displays[oldid]; db.displays[oldid] = nil; if(clones[oldid]) then clones[newid] = clones[oldid]; clones[oldid] = nil; for cloneid, clone in pairs(clones[newid]) do clone.id = newid; end end db.displays[newid].id = newid; if(data.controlledChildren) then for index, childId in pairs(data.controlledChildren) do local childData = db.displays[childId]; if(childData) then childData.parent = data.id; end end if regions[newid].ReloadControlledChildren then regions[newid]:ReloadControlledChildren() end end if (Private.personalRessourceDisplayFrame) then Private.personalRessourceDisplayFrame:rename(oldid, newid); end if (Private.mouseFrame) then Private.mouseFrame:rename(oldid, newid); end Private.customActionsFunctions[newid] = Private.customActionsFunctions[oldid]; Private.customActionsFunctions[oldid] = nil; WeakAuras.customConditionsFunctions[newid] = WeakAuras.customConditionsFunctions[oldid]; WeakAuras.customConditionsFunctions[oldid] = nil; WeakAuras.conditionTextFormatters[newid] = WeakAuras.conditionTextFormatters[oldid] WeakAuras.conditionTextFormatters[oldid] = nil Private.frameLevels[newid] = Private.frameLevels[oldid]; Private.frameLevels[oldid] = nil; Private.ProfileRenameAura(oldid, newid); -- TODO: This should not be necessary WeakAuras.Add(data) Private.callbacks:Fire("Rename", data.uid, oldid, newid) end function Private.Convert(data, newType) local id = data.id; regions[id].region:SetScript("OnUpdate", nil); regions[id].region:Hide(); Private.EndEvent(id, 0, true); Private.FakeStatesFor(id, false) regions[id].region = nil; regions[id] = nil; data.regionType = newType; WeakAuras.Add(data); Private.FakeStatesFor(id, true) local parentRegion = WeakAuras.GetRegion(data.parent) if parentRegion and parentRegion.ReloadControlledChildren then parentRegion:ReloadControlledChildren() end end -- The default mixin doesn't recurse, this does function WeakAuras.DeepMixin(dest, source) local function recurse(source, dest) for i,v in pairs(source) do if(type(v) == "table") then dest[i] = type(dest[i]) == "table" and dest[i] or {}; recurse(v, dest[i]); else dest[i] = v; end end end recurse(source, dest); end function WeakAuras.RegisterAddon(addon, displayName, description, icon) if(addons[addon]) then addons[addon].displayName = displayName; addons[addon].description = description; addons[addon].icon = icon; addons[addon].displays = addons[addon].displays or {}; else addons[addon] = { displayName = displayName, description = description, icon = icon, displays = {} }; end end function WeakAuras.RegisterDisplay(addon, data, force) tinsert(from_files, {addon, data, force}); end function WeakAuras.AddManyFromAddons(table) for _, addData in ipairs(table) do WeakAuras.AddFromAddon(addData[1], addData[2], addData[3]); end end function WeakAuras.AddFromAddon(addon, data, force) local id = data.id; if(id and addons[addon]) then addons[addon].displays[id] = data; if(db.registered[id]) then -- This display was already registered -- It is unnecessary to add it again elseif(force and not db.registered[id] == false) then if(db.displays[id]) then -- ID collision collisions[id] = {addon, data}; else db.registered[id] = addon; WeakAuras.Add(data); end end end end function WeakAuras.CollisionResolved(addon, data, force) WeakAuras.AddFromAddon(addon, data, force); end function Private.IsDefinedByAddon(id) return db.registered[id]; end function Private.ResolveCollisions(onFinished) local num = 0; for id, _ in pairs(collisions) do num = num + 1; end if(num > 0) then local baseText; local buttonText; if(registeredFromAddons) then if(num == 1) then baseText = L["Resolve collisions dialog singular"]; buttonText = L["Done"]; else baseText = L["Resolve collisions dialog"]; buttonText = L["Next"]; end else if(num == 1) then baseText = L["Resolve collisions dialog startup singular"]; buttonText = L["Done"]; else baseText = L["Resolve collisions dialog startup"]; buttonText = L["Next"]; end end local numResolved = 0; local currentId = next(collisions); local function UpdateText(popup) popup.text:SetText(baseText..(numResolved or "error").."/"..(num or "error")); end StaticPopupDialogs["WEAKAURAS_RESOLVE_COLLISIONS"] = { text = baseText, button1 = buttonText, OnAccept = function(self) -- Do the collision resolution local newId = self.editBox:GetText(); if(WeakAuras.OptionsFrame and WeakAuras.OptionsFrame() and WeakAuras.displayButtons and WeakAuras.displayButtons[currentId]) then WeakAuras.displayButtons[currentId].callbacks.OnRenameAction(newId) else local data = WeakAuras.GetData(currentId); if(data) then WeakAuras.Rename(data, newId); else print("|cFF8800FFWeakAuras|r: Data not found"); end end WeakAuras.CollisionResolved(collisions[currentId][1], collisions[currentId][2], true); numResolved = numResolved + 1; -- Get the next id to resolve currentId = next(collisions, currentId); if(currentId) then -- There is another conflict to resolve - hook OnHide to reshow the dialog as soon as it hides self:SetScript("OnHide", function(self) self:Show(); UpdateText(self); self.editBox:SetText(currentId); self:SetScript("OnHide", nil); if not(next(collisions, currentId)) then self.button1:SetText(L["Done"]); end end); else self.editBox:SetScript("OnTextChanged", nil); wipe(collisions); if(onFinished) then onFinished(); end end end, hasEditBox = true, hasWideEditBox = true, hideOnEscape = true, whileDead = true, showAlert = true, timeout = 0, preferredindex = STATICPOPUP_NUMDIALOGS }; local popup = StaticPopup_Show("WEAKAURAS_RESOLVE_COLLISIONS"); popup.editBox:SetScript("OnTextChanged", function(self) local newid = self:GetText(); if(collisions[newid] or db.displays[newid]) then popup.button1:Disable(); else popup.button1:Enable(); end end); popup.editBox:SetText(currentId); popup.text:SetJustifyH("left"); popup.icon:SetTexture("Interface\\Addons\\WeakAuras\\Media\\Textures\\icon.blp"); popup.icon:SetVertexColor(0.833, 0, 1); UpdateText(popup); elseif(onFinished) then onFinished(); end end local function LastUpgrade() return db.lastUpgrade and date(nil, db.lastUpgrade) or "unknown" end function Private.NeedToRepairDatabase() return db.dbVersion and db.dbVersion > WeakAuras.InternalVersion() end local function RepairDatabase(loginAfter) local coro = coroutine.create(function() WeakAuras.SetImporting(true) -- set db version to current code version db.dbVersion = WeakAuras.InternalVersion() -- reinstall snapshots from history local newDB = Mixin({}, db.displays) coroutine.yield() for id, data in pairs(db.displays) do local snapshot = Private.GetMigrationSnapshot(data.uid) if snapshot then newDB[id] = nil newDB[snapshot.id] = snapshot coroutine.yield() end end db.displays = newDB WeakAuras.SetImporting(false) -- finally, login Private.Login() end) Private.dynFrame:AddAction("repair", coro) end StaticPopupDialogs["WEAKAURAS_CONFIRM_REPAIR"] = { text = "", button1 = L["Repair"], button2 = L["Cancel"], OnAccept = function(self) RepairDatabase() end, OnShow = function(self) if self.data.reason == "user" then self.text:SetText(L["Manual Repair Confirmation Dialog"]:format(LastUpgrade())) else self.text:SetText(L["Automatic Repair Confirmation Dialog"]:format(LastUpgrade())) end end, OnCancel = function(self) if self.data.reason ~= "user" then Private.Login() end end, whileDead = true, showAlert = true, timeout = 0, preferredindex = STATICPOPUP_NUMDIALOGS } function Private.ValidateUniqueDataIds(silent) -- ensure that there are no duplicated uids anywhere in the database local seenUIDs = {} for _, data in pairs(db.displays) do if type(data.uid) == "string" then if seenUIDs[data.uid] then if not silent then prettyPrint("Duplicate uid \""..data.uid.."\" detected in saved variables between \""..data.id.."\" and \""..seenUIDs[data.uid].id.."\".") end data.uid = WeakAuras.GenerateUniqueID() seenUIDs[data.uid] = data else seenUIDs[data.uid] = data end elseif data.uid ~= nil then if not silent then prettyPrint("Invalid uid detected in saved variables for \""..data.id.."\"") end data.uid = WeakAuras.GenerateUniqueID() seenUIDs[data.uid] = data end end for uid, data in pairs(seenUIDs) do UIDtoID[uid] = data.id end end function Private.SyncParentChildRelationships(silent) -- 1. Find all auras where data.parent ~= nil or data.controlledChildren ~= nil -- If an aura has both, then remove data.parent -- If an aura has data.parent which doesn't exist, then remove data.parent -- If an aura has data.parent which doesn't have data.controlledChildren, then remove data.parent -- 2. For each aura with data.controlledChildren, iterate through the list of children and remove entries where: -- The child doesn't exist in the database -- The child ID is duplicated in data.controlledChildren (only the first will be kept) -- The child's data.parent points to a different parent -- Otherwise, mark the child as having a valid parent relationship -- 3. For each aura with data.parent, remove data.parent if it was not marked to have a valid relationship in 2. local parents = {} local children = {} local childHasParent = {} for id, data in pairs(db.displays) do if data.parent then if data.controlledChildren then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." is a group that thinks it's a parent.") end -- A display cannot have both children and a parent data.parent = nil parents[id] = data elseif not db.displays[data.parent] then if not(silent) then prettyPrint("Detected corruption in saved variables: "..id.." has a nonexistent parent.") end data.parent = nil elseif not db.displays[data.parent].controlledChildren then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." thinks "..data.parent.. " controls it, but "..data.parent.." is not a group.") end data.parent = nil else children[id] = data end elseif data.controlledChildren then parents[id] = data end end for id, data in pairs(parents) do local groupChildren = {} local childrenToRemove = {} for index, childID in ipairs(data.controlledChildren) do local child = children[childID] if not child then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." thinks it controls "..childID.." which doesn't exist.") end childrenToRemove[index] = true elseif child.parent ~= id then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." thinks it controls "..childID.." which it does not.") end childrenToRemove[index] = true elseif groupChildren[childID] then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." has "..childID.." as a child in multiple positions.") end childrenToRemove[index] = true else groupChildren[childID] = index childHasParent[childID] = true end end if next(childrenToRemove) ~= nil then for i = #data.controlledChildren, 1, -1 do if childrenToRemove[i] then tremove(data.controlledChildren, i) end end end end for id, data in pairs(children) do if not childHasParent[id] then if not silent then prettyPrint("Detected corruption in saved variables: "..id.." should be controlled by "..data.parent.." but isn't.") end local parent = parents[data.parent] tinsert(parent.controlledChildren, id) end end end function WeakAuras.AddMany(table, takeSnapshots) local idtable = {}; for _, data in ipairs(table) do idtable[data.id] = data; end local loaded = {}; local function load(id, depends) local data = idtable[id]; if(data.parent) then if(idtable[data.parent]) then if(tContains(depends, data.parent)) then error("Circular dependency in WeakAuras.AddMany between "..table.concat(depends, ", ")); else if not(loaded[data.parent]) then local dependsOut = {}; for i,v in pairs(depends) do dependsOut[i] = v; end tinsert(dependsOut, data.parent); load(data.parent, dependsOut); end end else data.parent = nil; end end if not(loaded[id]) then WeakAuras.Add(data, takeSnapshots); coroutine.yield(); loaded[id] = true; end end local groups = {} for id, data in pairs(idtable) do load(id, {}); if data.regionType == "dynamicgroup" or data.regionType == "group" then groups[data] = true end end for data in pairs(groups) do if data.type == "dynamicgroup" then regions[data.id].region:ReloadControlledChildren() else WeakAuras.Add(data) end coroutine.yield(); end end local function customOptionIsValid(option) if not option.type then return false elseif Private.author_option_classes[option.type] == "simple" then if not option.key or not option.name or not option.default == nil then return false end elseif Private.author_option_classes[option.type] == "group" then if not option.key or not option.name or not option.default == nil or not option.subOptions then return false end end return true end local function validateUserConfig(data, options, config) local authorOptionKeys, corruptOptions = {}, {} for index, option in ipairs(options) do if not customOptionIsValid(option) then prettyPrint(data.id .. " Custom Option #" .. index .. " in " .. data.id .. " has been detected as corrupt, and has been deleted.") corruptOptions[index] = true else local optionClass = Private.author_option_classes[option.type] if optionClass == "simple" then if not option.key then option.key = WeakAuras.GenerateUniqueID() end authorOptionKeys[option.key] = index if config[option.key] == nil then if type(option.default) ~= "table" then config[option.key] = option.default else config[option.key] = CopyTable(option.default) end end elseif optionClass == "group" then authorOptionKeys[option.key] = "group" local subOptions = option.subOptions if type(config[option.key]) ~= "table" then config[option.key] = {} end local subConfig = config[option.key] if option.groupType == "array" then for k, v in pairs(subConfig) do if type(k) ~= "number" or type(v) ~= "table" then -- if k was not a number, then this was a simple group before -- if v is not a table, then this was likely a color option wipe(subConfig) -- second iteration will fill table with defaults break end end if option.limitType == "fixed" then for i = #subConfig + 1, option.size do -- add missing entries subConfig[i] = {} end end if option.limitType ~= "none" then for i = option.size + 1, #subConfig do -- remove excess entries subConfig[i] = nil end end for _, toValidate in pairs(subConfig) do validateUserConfig(data, subOptions, toValidate) end else if type(next(subConfig)) ~= "string" then -- either there are no sub options, in which case this is a noop -- or this group was previously an array, in which case we need to wipe wipe(subConfig) end validateUserConfig(data, subOptions, subConfig) end end end end for i = #options, 1, -1 do if corruptOptions[i] then tremove(options, i) end end for key, value in pairs(config) do if not authorOptionKeys[key] then config[key] = nil elseif authorOptionKeys[key] ~= "group" then local option = options[authorOptionKeys[key]] if type(value) ~= type(option.default) then -- if type mismatch then we know that it can't be right if type(option.default) ~= "table" then config[key] = option.default else config[key] = CopyTable(option.default) end elseif option.type == "input" and option.useLength then config[key] = config[key]:sub(1, option.length) elseif option.type == "number" or option.type == "range" then if (option.max and option.max < value) or (option.min and option.min > value) then config[key] = option.default else if option.type == "number" and option.step then local min = option.min or 0 config[key] = option.step * Round((value - min)/option.step) + min end end elseif option.type == "select" then if value < 1 or value > #option.values then config[key] = option.default end elseif option.type == "multiselect" then local multiselect = config[key] for i, v in ipairs(multiselect) do if option.default[i] ~= nil then if type(v) ~= "boolean" then multiselect[i] = option.default[i] end else multiselect[i] = nil end end for i, v in ipairs(option.default) do if type(multiselect[i]) ~= "boolean" then multiselect[i] = v end end elseif option.type == "color" then for i = 1, 4 do local c = config[key][i] if type(c) ~= "number" or c < 0 or c > 1 then config[key] = option.default break end end end end end end local function removeSpellNames(data) local trigger for i = 1, #data.triggers do trigger = data.triggers[i].trigger if trigger and trigger.type == "aura" then if type(trigger.spellName) == "number" then trigger.realSpellName = GetSpellInfo(trigger.spellName) or trigger.realSpellName end if (trigger.spellId) then trigger.name = GetSpellInfo(trigger.spellId) or trigger.name; end if (trigger.spellIds) then for i = 1, 10 do if (trigger.spellIds[i]) then trigger.names = trigger.names or {}; trigger.names[i] = GetSpellInfo(trigger.spellIds[i]) or trigger.names[i]; end end end end end end local oldDataStub = { -- note: this is the minimal data stub which prevents false positives in diff upon reimporting an aura. -- pending a refactor of other code which adds unnecessary fields, it is possible to shrink it trigger = { type = "aura", names = {}, event = "Health", subeventPrefix = "SPELL", subeventSuffix = "_CAST_START", spellIds = {}, unit = "player", debuffType = "HELPFUL", }, numTriggers = 1, untrigger = {}, load = { size = { multi = {}, }, spec = { multi = {}, }, class = { multi = {}, }, }, actions = { init = {}, start = {}, finish = {}, }, animation = { start = { type = "none", duration_type = "seconds", }, main = { type = "none", duration_type = "seconds", }, finish = { type = "none", duration_type = "seconds", }, }, conditions = {}, } local oldDataStub2 = { -- note: this is the minimal data stub which prevents false positives in diff upon reimporting an aura. -- pending a refactor of other code which adds unnecessary fields, it is possible to shrink it triggers = { { trigger = { type = "aura", names = {}, event = "Health", subeventPrefix = "SPELL", subeventSuffix = "_CAST_START", spellIds = {}, unit = "player", debuffType = "HELPFUL", }, untrigger = {}, }, }, load = { size = { multi = {}, }, spec = { multi = {}, }, class = { multi = {}, }, }, actions = { init = {}, start = {}, finish = {}, }, animation = { start = { type = "none", duration_type = "seconds", }, main = { type = "none", duration_type = "seconds", }, finish = { type = "none", duration_type = "seconds", }, }, conditions = {}, } function WeakAuras.PreAdd(data) -- Readd what Compress removed before version 8 if (not data.internalVersion or data.internalVersion < 7) then WeakAuras.validate(data, oldDataStub) elseif (data.internalVersion < 8) then WeakAuras.validate(data, oldDataStub2) end local default = data.regionType and WeakAuras.regionTypes[data.regionType] and WeakAuras.regionTypes[data.regionType].default if default then WeakAuras.validate(data, default) end local regionValidate = data.regionType and WeakAuras.regionTypes[data.regionType] and WeakAuras.regionTypes[data.regionType].validate if regionValidate then regionValidate(data) end Private.Modernize(data); WeakAuras.validate(data, WeakAuras.data_stub); if data.subRegions then local result = {} for index, subRegionData in ipairs(data.subRegions) do local subType = subRegionData.type if subType and Private.subRegionTypes[subType] then -- If it is not supported, then drop it if Private.subRegionTypes[subType].supports(data.regionType) then local default = Private.subRegionTypes[subType].default if type(default) == "function" then default = default(data.regionType) end if default then WeakAuras.validate(subRegionData, default) end tinsert(result, subRegionData) end else -- Unknown sub type is because the user didn't restart their client -- so keep it tinsert(result, subRegionData) end end data.subRegions = result end validateUserConfig(data, data.authorOptions, data.config) removeSpellNames(data) data.init_started = nil data.init_completed = nil data.expanded = nil end local function pAdd(data, simpleChange) local id = data.id; if not(id) then error("Improper arguments to WeakAuras.Add - id not defined"); return; end data.uid = data.uid or WeakAuras.GenerateUniqueID() local otherID = UIDtoID[data.uid] if not otherID then UIDtoID[data.uid] = id elseif otherID ~= id then -- duplicate uid data.uid = WeakAuras.GenerateUniqueID() UIDtoID[data.uid] = id end if simpleChange then db.displays[id] = data WeakAuras.SetRegion(data) Private.UpdatedTriggerState(id) else if (data.controlledChildren) then Private.ClearAuraEnvironment(id); if data.parent then Private.ClearAuraEnvironment(data.parent); end db.displays[id] = data; WeakAuras.SetRegion(data); else local visible if (WeakAuras.IsOptionsOpen()) then visible = Private.FakeStatesFor(id, false) else if (WeakAuras.regions[id] and WeakAuras.regions[id].region) then WeakAuras.regions[id].region:Collapse() else Private.CollapseAllClones(id) end end Private.ClearAuraEnvironment(id); if data.parent then Private.ClearAuraEnvironment(data.parent); end db.displays[id] = data; if (not data.triggers.activeTriggerMode or data.triggers.activeTriggerMode > #data.triggers) then data.triggers.activeTriggerMode = Private.trigger_modes.first_active; end for _, triggerSystem in pairs(triggerSystems) do triggerSystem.Add(data); end local loadFuncStr, events = ConstructFunction(load_prototype, data.load); for event, eventData in pairs(loadEvents) do eventData[id] = nil end for event in pairs(events) do loadEvents[event] = loadEvents[event] or {} loadEvents[event][id] = true end loadEvents["SCAN_ALL"] = loadEvents["SCAN_ALL"] or {} loadEvents["SCAN_ALL"][id] = true local loadForOptionsFuncStr = ConstructFunction(load_prototype, data.load, true); local loadFunc = WeakAuras.LoadFunction(loadFuncStr, id, "load"); local loadForOptionsFunc = WeakAuras.LoadFunction(loadForOptionsFuncStr, id, "options load"); local triggerLogicFunc; if data.triggers.disjunctive == "custom" then triggerLogicFunc = WeakAuras.LoadFunction("return "..(data.triggers.customTriggerLogic or ""), id, "trigger combination"); end LoadCustomActionFunctions(data); Private.LoadConditionPropertyFunctions(data); Private.LoadConditionFunction(data) loadFuncs[id] = loadFunc; loadFuncsForOptions[id] = loadForOptionsFunc; clones[id] = clones[id] or {}; if (timers[id]) then for _, trigger in pairs(timers[id]) do for _, record in pairs(trigger) do if (record.handle) then timer:CancelTimer(record.handle); end end end timers[id] = nil; end local region = WeakAuras.SetRegion(data); triggerState[id] = { disjunctive = data.triggers.disjunctive or "all", numTriggers = #data.triggers, activeTriggerMode = data.triggers.activeTriggerMode or Private.trigger_modes.first_active, triggerLogicFunc = triggerLogicFunc, triggers = {}, triggerCount = 0, activatedConditions = {}, }; LoadEncounterInitScripts(id); if (WeakAuras.IsOptionsOpen()) then Private.FakeStatesFor(id, visible) end if not(paused) then Private.ScanForLoads({[id] = true}); end end end end function WeakAuras.Add(data, takeSnapshot, simpleChange) local snapshot if takeSnapshot or (data.internalVersion or 0) < internalVersion then snapshot = CopyTable(data) end if takeSnapshot then Private.SetMigrationSnapshot(data.uid, snapshot) end local ok = xpcall(WeakAuras.PreAdd, geterrorhandler(), data) if ok then pAdd(data, simpleChange) end end function WeakAuras.SetRegion(data, cloneId) local regionType = data.regionType; if not(regionType) then error("Improper arguments to WeakAuras.SetRegion - regionType not defined"); else if(not regionTypes[regionType]) then regionType = "fallback"; print("Improper arguments to WeakAuras.CreateRegion - regionType \""..data.regionType.."\" is not supported"); end local id = data.id; if not(id) then error("Improper arguments to WeakAuras.SetRegion - id not defined"); else local region; if(cloneId) then region = clones[id][cloneId]; if (not region or region.regionType ~= data.regionType) then if (region) then clonePool[region.regionType] = clonePool[region.regionType] or {}; tinsert(clonePool[region.regionType], region); region:Hide(); end if(clonePool[data.regionType] and clonePool[data.regionType][1]) then clones[id][cloneId] = tremove(clonePool[data.regionType]); else local clone = regionTypes[data.regionType].create(frame, data); clone.regionType = data.regionType; clone:Hide(); clones[id][cloneId] = clone; end region = clones[id][cloneId]; end else if((not regions[id]) or (not regions[id].region) or regions[id].regionType ~= regionType) then region = regionTypes[regionType].create(frame, data); region.regionType = regionType; regions[id] = { regionType = regionType, region = region }; if regionType ~= "dynamicgroup" and regionType ~= "group" then region.toShow = false region:Hide() else region.toShow = true end else region = regions[id].region; end end region.id = id; region.cloneId = cloneId or ""; WeakAuras.validate(data, regionTypes[regionType].default); local parent = frame; if(data.parent) then if(regions[data.parent]) then parent = regions[data.parent].region; else data.parent = nil; end end local loginFinished = WeakAuras.IsLoginFinished(); local anim_cancelled = loginFinished and Private.CancelAnimation(region, true, true, true, true, true, true); regionTypes[regionType].modify(parent, region, data); WeakAuras.regionPrototype.AddSetDurationInfo(region); WeakAuras.regionPrototype.AddExpandFunction(data, region, cloneId, parent, parent.regionType) data.animation = data.animation or {}; data.animation.start = data.animation.start or {type = "none"}; data.animation.main = data.animation.main or {type = "none"}; data.animation.finish = data.animation.finish or {type = "none"}; if(Private.CanHaveDuration(data)) then data.animation.start.duration_type = data.animation.start.duration_type or "seconds"; data.animation.main.duration_type = data.animation.main.duration_type or "seconds"; data.animation.finish.duration_type = data.animation.finish.duration_type or "seconds"; else data.animation.start.duration_type = "seconds"; data.animation.main.duration_type = "seconds"; data.animation.finish.duration_type = "seconds"; end if(cloneId) then clonePool[regionType] = clonePool[regionType] or {}; end if(anim_cancelled) then Private.Animate("display", data.uid, "main", data.animation.main, region, false, nil, true, cloneId); end return region; end end end local function EnsureClone(id, cloneId) clones[id] = clones[id] or {}; if not(clones[id][cloneId]) then local data = WeakAuras.GetData(id); WeakAuras.SetRegion(data, cloneId); clones[id][cloneId].justCreated = true; end return clones[id][cloneId]; end function WeakAuras.GetRegion(id, cloneId) if(cloneId and cloneId ~= "") then return EnsureClone(id, cloneId); end return WeakAuras.regions[id] and WeakAuras.regions[id].region; end -- Note, does not create a clone! function Private.GetRegionByUID(uid, cloneId) local id = Private.UIDtoID(uid) if(cloneId and cloneId ~= "") then return id and clones[id] and clones[id][cloneId]; end return id and WeakAuras.regions[id] and WeakAuras.regions[id].region end function Private.CollapseAllClones(id, triggernum) if(clones[id]) then for i,v in pairs(clones[id]) do v:Collapse(); end end end function Private.SetAllStatesHidden(id, triggernum) local triggerState = WeakAuras.GetTriggerStateForTrigger(id, triggernum); local changed = false for id, state in pairs(triggerState) do changed = changed or state.show state.show = false; state.changed = true; end return changed end function Private.SetAllStatesHiddenExcept(id, triggernum, list) local triggerState = WeakAuras.GetTriggerStateForTrigger(id, triggernum); for cloneId, state in pairs(triggerState) do if (not (list[cloneId])) then state.show = false; state.changed = true; end end end function Private.ReleaseClone(id, cloneId, regionType) if (not clones[id]) then return; end local region = clones[id][cloneId]; clones[id][cloneId] = nil; clonePool[regionType][#clonePool[regionType] + 1] = region; end function Private.HandleChatAction(message_type, message, message_dest, message_channel, r, g, b, region, customFunc, when, formatters) local useHiddenStates = when == "finish" if (message:find('%%')) then message = Private.ReplacePlaceHolders(message, region, customFunc, useHiddenStates, formatters); end if(message_type == "PRINT") then DEFAULT_CHAT_FRAME:AddMessage(message, r or 1, g or 1, b or 1); elseif message_type == "ERROR" then UIErrorsFrame:AddMessage(message, r or 1, g or 1, b or 1) elseif(message_type == "COMBAT") then if(CombatText_AddMessage) then CombatText_AddMessage(message, COMBAT_TEXT_SCROLL_FUNCTION, r or 1, g or 1, b or 1); end elseif(message_type == "WHISPER") then if(message_dest) then if(message_dest == "target" or message_dest == "'target'" or message_dest == "\"target\"" or message_dest == "%t" or message_dest == "'%t'" or message_dest == "\"%t\"") then pcall(function() SendChatMessage(message, "WHISPER", nil, UnitName("target")) end); else pcall(function() SendChatMessage(message, "WHISPER", nil, message_dest) end); end end elseif(message_type == "SMARTRAID") then local isInstanceGroup = IsInGroup(LE_PARTY_CATEGORY_INSTANCE) if UnitInBattleground("player") then pcall(function() SendChatMessage(message, "INSTANCE_CHAT") end) elseif UnitInRaid("player") then pcall(function() SendChatMessage(message, "RAID") end) elseif UnitInParty("player") then if isInstanceGroup then pcall(function() SendChatMessage(message, "INSTANCE_CHAT") end) else pcall(function() SendChatMessage(message, "PARTY") end) end else if IsInInstance() then pcall(function() SendChatMessage(message, "SAY") end) end end elseif(message_type == "SAY" or message_type == "YELL") then if IsInInstance() then pcall(function() SendChatMessage(message, message_type, nil, nil) end) end else pcall(function() SendChatMessage(message, message_type, nil, nil) end); end end local function actionGlowStop(actions, frame, id) if not frame.__WAGlowFrame then return end if actions.glow_type == "buttonOverlay" then LCG.ButtonGlow_Stop(frame.__WAGlowFrame) elseif actions.glow_type == "Pixel" then LCG.PixelGlow_Stop(frame.__WAGlowFrame, id) elseif actions.glow_type == "ACShine" then LCG.AutoCastGlow_Stop(frame.__WAGlowFrame, id) end end local function actionGlowStart(actions, frame, id) if not frame.__WAGlowFrame then frame.__WAGlowFrame = CreateFrame("Frame", nil, frame) frame.__WAGlowFrame:SetAllPoints(frame) frame.__WAGlowFrame:SetSize(frame:GetSize()) end local glow_frame = frame.__WAGlowFrame if glow_frame:GetWidth() < 1 or glow_frame:GetHeight() < 1 then actionGlowStop(actions, frame) return end local color = actions.use_glow_color and actions.glow_color or nil if actions.glow_type == "buttonOverlay" then LCG.ButtonGlow_Start(glow_frame, color) elseif actions.glow_type == "Pixel" then LCG.PixelGlow_Start( glow_frame, color, actions.glow_lines, actions.glow_frequency, actions.glow_length, actions.glow_thickness, actions.glow_XOffset, actions.glow_YOffset, actions.glow_border, id ) elseif actions.glow_type == "ACShine" then LCG.AutoCastGlow_Start( glow_frame, color, actions.glow_lines, actions.glow_frequency, actions.glow_scale, actions.glow_XOffset, actions.glow_YOffset, id ) end end local glow_frame_monitor local anchor_unitframe_monitor Private.dyngroup_unitframe_monitor = {} do local function frame_monitor_callback(event, frame, unit) local new_frame local update_frame = event == "FRAME_UNIT_UPDATE" local dynamicGroupsToUpdate = {} if type(glow_frame_monitor) == "table" then for region, data in pairs(glow_frame_monitor) do if region.state and region.state.unit == unit and (data.frame ~= frame) == update_frame then if not new_frame then new_frame = WeakAuras.GetUnitFrame(unit) or WeakAuras.HiddenFrames end if new_frame and new_frame ~= data.frame then local id = region.id .. (region.cloneId or "") -- remove previous glow actionGlowStop(data.actions, data.frame, id) -- apply the glow to new_frame data.frame = new_frame actionGlowStart(data.actions, data.frame, id) -- update hidefunc local region = region region.active_glows_hidefunc[data.frame] = function() actionGlowStop(data.actions, data.frame, id) glow_frame_monitor[region] = nil end end end end end if type(anchor_unitframe_monitor) == "table" then for region, data in pairs(anchor_unitframe_monitor) do if region.state and region.state.unit == unit and (data.frame ~= frame) == update_frame then if not new_frame then new_frame = WeakAuras.GetUnitFrame(unit) or WeakAuras.HiddenFrames end if new_frame and new_frame ~= data.frame then Private.AnchorFrame(data.data, region, data.parent) end end end end for regionData, data_frame in pairs(Private.dyngroup_unitframe_monitor) do if regionData.region and regionData.region.state and regionData.region.state.unit == unit and (data_frame ~= frame) == update_frame then if not new_frame then new_frame = WeakAuras.GetUnitFrame(unit) or WeakAuras.HiddenFrames end if new_frame and new_frame ~= data_frame then dynamicGroupsToUpdate[regionData.parent] = true end end end for frame in pairs(dynamicGroupsToUpdate) do frame:DoPositionChildren() end end LGF.RegisterCallback("WeakAuras", "FRAME_UNIT_UPDATE", frame_monitor_callback) LGF.RegisterCallback("WeakAuras", "FRAME_UNIT_REMOVED", frame_monitor_callback) end function Private.HandleGlowAction(actions, region) if actions.glow_action and ( ( (actions.glow_frame_type == "UNITFRAME" or actions.glow_frame_type == "NAMEPLATE") and region.state.unit ) or (actions.glow_frame_type == "FRAMESELECTOR" and actions.glow_frame) ) then local glow_frame local original_glow_frame if actions.glow_frame_type == "FRAMESELECTOR" then if actions.glow_frame:sub(1, 10) == "WeakAuras:" then local frame_name = actions.glow_frame:sub(11) if regions[frame_name] then glow_frame = regions[frame_name].region end else glow_frame = Private.GetSanitizedGlobal(actions.glow_frame) end elseif actions.glow_frame_type == "UNITFRAME" and region.state.unit then glow_frame = WeakAuras.GetUnitFrame(region.state.unit) elseif actions.glow_frame_type == "NAMEPLATE" and region.state.unit then glow_frame = WeakAuras.GetUnitNameplate(region.state.unit) end if glow_frame then local id = region.id .. (region.cloneId or "") if actions.glow_action == "show" then -- remove previous glow if region.active_glows_hidefunc and region.active_glows_hidefunc[glow_frame] then region.active_glows_hidefunc[glow_frame]() end -- start glow actionGlowStart(actions, glow_frame, id) -- make unglow function & monitor unitframe changes region.active_glows_hidefunc = region.active_glows_hidefunc or {} if actions.glow_frame_type == "UNITFRAME" then glow_frame_monitor = glow_frame_monitor or {} glow_frame_monitor[region] = { actions = actions, frame = glow_frame } region.active_glows_hidefunc[glow_frame] = function() actionGlowStop(actions, glow_frame, id) glow_frame_monitor[region] = nil end else region.active_glows_hidefunc[glow_frame] = function() actionGlowStop(actions, glow_frame, id) end end elseif actions.glow_action == "hide" and region.active_glows_hidefunc and region.active_glows_hidefunc[glow_frame] then region.active_glows_hidefunc[glow_frame]() region.active_glows_hidefunc[glow_frame] = nil end end end end function Private.PerformActions(data, when, region) if (paused or WeakAuras.IsOptionsOpen()) then return; end; local actions; local formatters if(when == "start") then actions = data.actions.start; formatters = region.startFormatters elseif(when == "finish") then actions = data.actions.finish; formatters = region.finishFormatters else return; end if(actions.do_message and actions.message_type and actions.message) then local customFunc = Private.customActionsFunctions[data.id][when .. "_message"]; Private.HandleChatAction(actions.message_type, actions.message, actions.message_dest, actions.message_channel, actions.r, actions.g, actions.b, region, customFunc, when, formatters); end if (actions.stop_sound) then if (region.SoundStop) then region:SoundStop(); end end if(actions.do_sound and actions.sound) then if (region.SoundPlay) then region:SoundPlay(actions); end end if(actions.do_custom and actions.custom) then local func = Private.customActionsFunctions[data.id][when] if func then Private.ActivateAuraEnvironment(region.id, region.cloneId, region.state, region.states); xpcall(func, geterrorhandler()); Private.ActivateAuraEnvironment(nil); end end -- Apply start glow actions even if squelch_actions is true, but don't apply finish glow actions if actions.do_glow then Private.HandleGlowAction(actions, region) end -- remove all glows on finish if when == "finish" and actions.hide_all_glows and region.active_glows_hidefunc then for _, hideFunc in pairs(region.active_glows_hidefunc) do hideFunc() end wipe(region.active_glows_hidefunc) end if when == "finish" and type(anchor_unitframe_monitor) == "table" then anchor_unitframe_monitor[region] = nil end end function WeakAuras.GetData(id) return id and db.displays[id]; end local function GetTriggerSystem(data, triggernum) local triggerType = data.triggers[triggernum] and data.triggers[triggernum].trigger.type return triggerType and triggerTypes[triggerType] end local function wrapTriggerSystemFunction(functionName, mode) local func; func = function(data, triggernum, ...) if (not triggernum) then return func(data, data.triggers.activeTriggerMode or -1, ...); elseif (triggernum < 0) then local result; if (mode == "or") then result = false; for i = 1, #data.triggers do result = result or func(data, i); end elseif (mode == "and") then result = true; for i = 1, #data.triggers do result = result and func(data, i); end elseif (mode == "table") then result = {}; for i = 1, #data.triggers do local tmp = func(data, i); if (tmp) then for k, v in pairs(tmp) do result[k] = v; end end end elseif (mode == "call") then for i = 1, #data.triggers do func(data, i, ...); end elseif (mode == "firstValue") then result = nil; for i = 1, #data.triggers do local tmp = func(data, i); if (tmp) then result = tmp; break; end end elseif (mode == "nameAndIcon") then for i = 1, #data.triggers do local tmp1, tmp2 = func(data, i); if (tmp1) then return tmp1, tmp2; end end end return result; else -- triggernum >= 1 local triggerSystem = GetTriggerSystem(data, triggernum); if (not triggerSystem) then return false end return triggerSystem[functionName](data, triggernum, ...); end end return func; end Private.CanHaveDuration = wrapTriggerSystemFunction("CanHaveDuration", "firstValue"); Private.CanHaveClones = wrapTriggerSystemFunction("CanHaveClones", "or"); Private.CanHaveTooltip = wrapTriggerSystemFunction("CanHaveTooltip", "or"); -- This has to be in WeakAuras for now, because GetNameAndIcon can be called from the options WeakAuras.GetNameAndIcon = wrapTriggerSystemFunction("GetNameAndIcon", "nameAndIcon"); Private.GetTriggerDescription = wrapTriggerSystemFunction("GetTriggerDescription", "call"); local wrappedGetOverlayInfo = wrapTriggerSystemFunction("GetOverlayInfo", "table"); Private.GetAdditionalProperties = function(data, triggernum, ...) local additionalProperties = "" for i = 1, #data.triggers do local triggerSystem = GetTriggerSystem(data, i); if (triggerSystem) then local add = triggerSystem.GetAdditionalProperties(data, i) if (add and add ~= "") then if additionalProperties ~= "" then additionalProperties = additionalProperties .. "\n" end additionalProperties = additionalProperties .. add; end end end if additionalProperties ~= "" then additionalProperties = "\n\n" .. L["Additional Trigger Replacements"] .. "\n" .. additionalProperties .. "\n\n" .. L["The trigger number is optional, and uses the trigger providing dynamic information if not specified."] end return additionalProperties end function Private.GetOverlayInfo(data, triggernum) local overlayInfo; if (data.controlledChildren) then overlayInfo = {}; for index, childId in pairs(data.controlledChildren) do local childData = WeakAuras.GetData(childId); local tmp = wrappedGetOverlayInfo(childData, triggernum); if (tmp) then for k, v in pairs(tmp) do overlayInfo[k] = v; end end end else overlayInfo = wrappedGetOverlayInfo(data, triggernum); end return overlayInfo; end function Private.GetTriggerConditions(data) local conditions = {}; for i = 1, #data.triggers do local triggerSystem = GetTriggerSystem(data, i); if (triggerSystem) then conditions[i] = triggerSystem.GetTriggerConditions(data, i); conditions[i] = conditions[i] or {}; conditions[i].show = { display = L["Active"], type = "bool", test = function(state, needle) return (state and state.id and triggerState[state.id].triggers[i] or false) == (needle == 1); end } end end return conditions; end local function CreateFallbackState(id, triggernum) fallbacksStates[id] = fallbacksStates[id] or {}; fallbacksStates[id][triggernum] = fallbacksStates[id][triggernum] or {}; local states = fallbacksStates[id][triggernum]; states[""] = states[""] or {}; local state = states[""]; local data = db.displays[id]; local triggerSystem = GetTriggerSystem(data, triggernum); if (triggerSystem) then triggerSystem.CreateFallbackState(data, triggernum, state) state.trigger = data.triggers[triggernum].trigger state.triggernum = triggernum else state.show = true; state.changed = true; state.progressType = "timed"; state.duration = 0; state.expirationTime = math.huge; end state.id = id return states; end local currentTooltipRegion; local currentTooltipOwner; local function UpdateMouseoverTooltip(region) if(region == currentTooltipRegion) then Private.ShowMouseoverTooltip(currentTooltipRegion, currentTooltipOwner); end end function Private.ShowMouseoverTooltip(region, owner) currentTooltipRegion = region; currentTooltipOwner = owner; GameTooltip:SetOwner(owner, "ANCHOR_NONE"); GameTooltip:SetPoint("LEFT", owner, "RIGHT"); GameTooltip:ClearLines(); local triggerType; if (region.state) then triggerType = region.state.trigger.type; end local triggerSystem = triggerType and triggerTypes[triggerType]; if (not triggerSystem) then GameTooltip:Hide(); return; end if (triggerSystem.SetToolTip(region.state.trigger, region.state)) then GameTooltip:Show(); else GameTooltip:Hide(); end end function Private.HideTooltip() currentTooltipRegion = nil; currentTooltipOwner = nil; GameTooltip:Hide(); end do local hiddenTooltip; function WeakAuras.GetHiddenTooltip() if not(hiddenTooltip) then hiddenTooltip = CreateFrame("GameTooltip", "WeakAurasTooltip", nil, "GameTooltipTemplate"); hiddenTooltip:SetOwner(WorldFrame, "ANCHOR_NONE"); hiddenTooltip:AddFontStrings( hiddenTooltip:CreateFontString("$parentTextLeft1", nil, "GameTooltipText"), hiddenTooltip:CreateFontString("$parentTextRight1", nil, "GameTooltipText") ); end return hiddenTooltip; end end function WeakAuras.GetAuraTooltipInfo(unit, index, filter) local tooltip = WeakAuras.GetHiddenTooltip(); tooltip:ClearLines(); tooltip:SetUnitAura(unit, index, filter); local tooltipTextLine = select(5, tooltip:GetRegions()) local tooltipText = tooltipTextLine and tooltipTextLine:GetObjectType() == "FontString" and tooltipTextLine:GetText() or ""; local debuffType = "none"; local found = false; local tooltipSize = {}; if(tooltipText) then for t in tooltipText:gmatch("(%d[%d%.,]*)") do if (LARGE_NUMBER_SEPERATOR == ",") then t = t:gsub(",", ""); else t = t:gsub("%.", ""); t = t:gsub(",", "."); end tinsert(tooltipSize, tonumber(t)); end end if (#tooltipSize) then return tooltipText, debuffType, unpack(tooltipSize); else return tooltipText, debuffType, 0; end end local FrameTimes = {}; function WeakAuras.ProfileFrames(all) UpdateAddOnCPUUsage(); for name, frame in pairs(WeakAuras.frames) do local FrameTime = GetFrameCPUUsage(frame); FrameTimes[name] = FrameTimes[name] or 0; if(all or FrameTime > FrameTimes[name]) then print("|cFFFF0000"..name.."|r -", FrameTime, "-", FrameTime - FrameTimes[name]); end FrameTimes[name] = FrameTime; end end local DisplayTimes = {}; function WeakAuras.ProfileDisplays(all) UpdateAddOnCPUUsage(); for id, regionData in pairs(WeakAuras.regions) do local DisplayTime = GetFrameCPUUsage(regionData.region, true); DisplayTimes[id] = DisplayTimes[id] or 0; if(all or DisplayTime > DisplayTimes[id]) then print("|cFFFF0000"..id.."|r -", DisplayTime, "-", DisplayTime - DisplayTimes[id]); end DisplayTimes[id] = DisplayTime; end end function Private.ValueFromPath(data, path) if not data then return nil end if (#path == 0) then return data elseif(#path == 1) then return data[path[1]]; else local reducedPath = {}; for i=2,#path do reducedPath[i-1] = path[i]; end return Private.ValueFromPath(data[path[1]], reducedPath); end end function Private.ValueToPath(data, path, value) if not data then return end if(#path == 1) then data[path[1]] = value; else local reducedPath = {}; for i=2,#path do reducedPath[i-1] = path[i]; end Private.ValueToPath(data[path[1]], reducedPath, value); end end Private.frameLevels = {}; local function SetFrameLevel(id, frameLevel) if (Private.frameLevels[id] == frameLevel) then return; end if (WeakAuras.regions[id] and WeakAuras.regions[id].region) then Private.ApplyFrameLevel(WeakAuras.regions[id].region, frameLevel) end if (clones[id]) then for i,v in pairs(clones[id]) do Private.ApplyFrameLevel(v, frameLevel) end end Private.frameLevels[id] = frameLevel; end function Private.FixGroupChildrenOrderForGroup(data) local frameLevel = 5; for i=1, #data.controlledChildren do SetFrameLevel(data.controlledChildren[i], frameLevel); frameLevel = frameLevel + 4; end end local function GetFrameLevelFor(id) return Private.frameLevels[id] or 5; end function Private.ApplyFrameLevel(region, frameLevel) frameLevel = frameLevel or GetFrameLevelFor(region.id) region:SetFrameLevel(frameLevel) if region.subRegions then for index, subRegion in pairs(region.subRegions) do subRegion:SetFrameLevel(frameLevel + index + 1) end end end function WeakAuras.EnsureString(input) if (input == nil) then return ""; end return tostring(input); end -- Handle coroutines local dynFrame = {}; do -- Internal data dynFrame.frame = CreateFrame("frame"); dynFrame.update = {}; dynFrame.size = 0; -- Add an action to be resumed via OnUpdate function dynFrame.AddAction(self, name, func) if not name then name = string.format("NIL", dynFrame.size+1); end if not dynFrame.update[name] then dynFrame.update[name] = func; dynFrame.size = dynFrame.size + 1 dynFrame.frame:Show(); end end -- Remove an action from OnUpdate function dynFrame.RemoveAction(self, name) if dynFrame.update[name] then dynFrame.update[name] = nil; dynFrame.size = dynFrame.size - 1 if dynFrame.size == 0 then dynFrame.frame:Hide(); end end end -- Setup frame dynFrame.frame:Hide(); dynFrame.frame:SetScript("OnUpdate", function(self, elapsed) -- Start timing local start = debugprofilestop(); local hasData = true; -- Resume as often as possible (Limit to 16ms per frame -> 60 FPS) while (debugprofilestop() - start < 16 and hasData) do -- Stop loop without data hasData = false; -- Resume all coroutines for name, func in pairs(dynFrame.update) do -- Loop has data hasData = true; -- Resume or remove if coroutine.status(func) ~= "dead" then local ok, msg = coroutine.resume(func) if not ok then geterrorhandler()(msg .. '\n' .. debugstack(func)) end else dynFrame:RemoveAction(name); end end end end); end Private.dynFrame = dynFrame; function WeakAuras.RegisterTriggerSystem(types, triggerSystem) for _, v in ipairs(types) do triggerTypes[v] = triggerSystem; end tinsert(triggerSystems, triggerSystem); end function WeakAuras.RegisterTriggerSystemOptions(types, func) for _, v in ipairs(types) do Private.triggerTypesOptions[v] = func; end end function WeakAuras.GetTriggerStateForTrigger(id, triggernum) if (triggernum == -1) then return Private.GetGlobalConditionState(); end triggerState[id][triggernum] = triggerState[id][triggernum] or {} return triggerState[id][triggernum]; end function WeakAuras.GetActiveStates(id) return triggerState[id].activeStates end function WeakAuras.GetActiveTriggers(id) return triggerState[id].triggers end do local visibleFakeStates = {} local UpdateFakeTimesHandle local function UpdateFakeTimers() Private.PauseAllDynamicGroups() local t = GetTime() for id, triggers in pairs(triggerState) do local changed = false for triggernum, triggerData in ipairs(triggers) do for id, state in pairs(triggerData) do if state.progressType == "timed" and state.expirationTime and state.expirationTime < t and state.duration and state.duration > 0 then state.expirationTime = state.expirationTime + state.duration state.changed = true changed = true end end end if changed then Private.UpdatedTriggerState(id) end end Private.ResumeAllDynamicGroups() end function Private.SetFakeStates() if UpdateFakeTimesHandle then return end for id, states in pairs(triggerState) do local changed for triggernum in ipairs(states) do changed = Private.SetAllStatesHidden(id, triggernum) or changed end if changed then Private.UpdatedTriggerState(id) end end UpdateFakeTimesHandle = timer:ScheduleRepeatingTimer(UpdateFakeTimers, 1) end function Private.ClearFakeStates() timer:CancelTimer(UpdateFakeTimesHandle) for id in pairs(triggerState) do Private.FakeStatesFor(id, false) end end function Private.FakeStatesFor(id, visible) if visibleFakeStates[id] == visible then return visibleFakeStates[id] end if visible then visibleFakeStates[id] = true Private.UpdateFakeStatesFor(id) else visibleFakeStates[id] = false if triggerState[id] then local changed = false for triggernum, state in ipairs(triggerState[id]) do changed = Private.SetAllStatesHidden(id, triggernum) or changed end if changed then Private.UpdatedTriggerState(id) end end end return not visibleFakeStates[id] end function Private.UpdateFakeStatesFor(id) if (WeakAuras.IsOptionsOpen() and visibleFakeStates[id]) then local data = WeakAuras.GetData(id) if (data) then for triggernum, trigger in ipairs(data.triggers) do Private.SetAllStatesHidden(id, triggernum) local triggerSystem = GetTriggerSystem(data, triggernum) if triggerSystem and triggerSystem.CreateFakeStates then triggerSystem.CreateFakeStates(id, triggernum) end end Private.UpdatedTriggerState(id) if WeakAuras.GetMoverSizerId() == id then WeakAuras.SetMoverSizer(id) end end end end end local function startStopTimers(id, cloneId, triggernum, state) if (state.show) then if (state.autoHide and state.duration and state.duration > 0) then -- autohide, update timer timers[id] = timers[id] or {}; timers[id][triggernum] = timers[id][triggernum] or {}; timers[id][triggernum][cloneId] = timers[id][triggernum][cloneId] or {}; local record = timers[id][triggernum][cloneId]; if (state.expirationTime == nil) then state.expirationTime = GetTime() + state.duration; end if (record.expirationTime ~= state.expirationTime or record.state ~= state) then if (record.handle ~= nil) then timer:CancelTimer(record.handle); end record.handle = timer:ScheduleTimerFixed( function() if (state.show ~= false and state.show ~= nil) then state.show = false; state.changed = true; Private.UpdatedTriggerState(id); end end, state.expirationTime - GetTime()); record.expirationTime = state.expirationTime; record.state = state end else -- no auto hide, delete timer if (timers[id] and timers[id][triggernum] and timers[id][triggernum][cloneId]) then local record = timers[id][triggernum][cloneId]; if (record.handle) then timer:CancelTimer(record.handle); end record.handle = nil; record.expirationTime = nil; record.state = nil end end else -- not shown if(timers[id] and timers[id][triggernum] and timers[id][triggernum][cloneId]) then local record = timers[id][triggernum][cloneId]; if (record.handle) then timer:CancelTimer(record.handle); end record.handle = nil; record.expirationTime = nil; record.state = nil end end end local function ApplyStateToRegion(id, cloneId, region, parent) region:Update(); region.subRegionEvents:Notify("Update", region.state, region.states) UpdateMouseoverTooltip(region); region:Expand(); if parent and parent.ActivateChild then parent:ActivateChild(id, cloneId) end end -- Fallbacks if the states are empty local emptyState = {}; emptyState[""] = {}; local function applyToTriggerStateTriggers(stateShown, id, triggernum) if (stateShown and not triggerState[id].triggers[triggernum]) then triggerState[id].triggers[triggernum] = true; triggerState[id].triggerCount = triggerState[id].triggerCount + 1; return true; elseif (not stateShown and triggerState[id].triggers[triggernum]) then triggerState[id].triggers[triggernum] = false; triggerState[id].triggerCount = triggerState[id].triggerCount - 1; return true; end return false; end local function evaluateTriggerStateTriggers(id) local result = false; Private.ActivateAuraEnvironment(id); if WeakAuras.IsOptionsOpen() then -- While the options are open ignore the combination function return triggerState[id].triggerCount > 0 end if (triggerState[id].disjunctive == "any" and triggerState[id].triggerCount > 0) then result = true; elseif(triggerState[id].disjunctive == "all" and triggerState[id].triggerCount == triggerState[id].numTriggers) then result = true; else if (triggerState[id].disjunctive == "custom" and triggerState[id].triggerLogicFunc) then local ok, returnValue = xpcall(triggerState[id].triggerLogicFunc, geterrorhandler(), triggerState[id].triggers); result = ok and returnValue; end end Private.ActivateAuraEnvironment(nil); return result; end local function ApplyStatesToRegions(id, activeTrigger, states) -- Show new clones local data = WeakAuras.GetData(id) local parent if data and data.parent then parent = WeakAuras.GetRegion(data.parent) end if parent and parent.Suspend then parent:Suspend() end for cloneId, state in pairs(states) do if (state.show) then local region = WeakAuras.GetRegion(id, cloneId); local applyChanges = not region.toShow or state.changed or region.state ~= state region.state = state region.states = region.states or {} local needsTimerTick = false for triggernum = -1, triggerState[id].numTriggers do local triggerState if triggernum == activeTrigger then triggerState = state else local triggerStates = WeakAuras.GetTriggerStateForTrigger(id, triggernum) triggerState = triggerStates[cloneId] or triggerStates[""] or {} end applyChanges = applyChanges or region.states[triggernum] ~= triggerState or (triggerState and triggerState.changed) region.states[triggernum] = triggerState needsTimerTick = needsTimerTick or (triggerState and triggerState.show and triggerState.progressType == "timed") end region:SetTriggerProvidesTimer(needsTimerTick) if (applyChanges) then ApplyStateToRegion(id, cloneId, region, parent); Private.RunConditions(region, data.uid, not state.show) end end end if parent and parent.Resume then parent:Resume() end end function Private.UpdatedTriggerState(id) if (not triggerState[id]) then return; end local changed = false; for triggernum = 1, triggerState[id].numTriggers do triggerState[id][triggernum] = triggerState[id][triggernum] or {}; local anyStateShown = false; for cloneId, state in pairs(triggerState[id][triggernum]) do state.trigger = db.displays[id].triggers[triggernum] and db.displays[id].triggers[triggernum].trigger; state.triggernum = triggernum; state.id = id; if (state.changed) then startStopTimers(id, cloneId, triggernum, state); end anyStateShown = anyStateShown or state.show; end -- Update triggerState.triggers changed = applyToTriggerStateTriggers(anyStateShown, id, triggernum) or changed; end -- Figure out whether we should be shown or not local show = triggerState[id].show; if (changed or show == nil) then show = evaluateTriggerStateTriggers(id); end -- Figure out which subtrigger is active, and if it changed local newActiveTrigger = triggerState[id].activeTriggerMode; if (newActiveTrigger == Private.trigger_modes.first_active) then -- Mode is first active trigger, so find a active trigger for i = 1, triggerState[id].numTriggers do if (triggerState[id].triggers[i]) then newActiveTrigger = i; break; end end end local oldShow = triggerState[id].show; triggerState[id].activeTrigger = newActiveTrigger; triggerState[id].show = show; triggerState[id].fallbackStates = nil local activeTriggerState = WeakAuras.GetTriggerStateForTrigger(id, newActiveTrigger); if (not next(activeTriggerState)) then if (show) then activeTriggerState = CreateFallbackState(id, newActiveTrigger) else activeTriggerState = emptyState; end elseif (show) then local needsFallback = true; for cloneId, state in pairs(activeTriggerState) do if (state.show) then needsFallback = false; break; end end if (needsFallback) then activeTriggerState = CreateFallbackState(id, newActiveTrigger) end end triggerState[id].activeStates = activeTriggerState local region; -- Now apply if (show and not oldShow) then -- Hide => Show ApplyStatesToRegions(id, newActiveTrigger, activeTriggerState); elseif (not show and oldShow) then -- Show => Hide for cloneId, clone in pairs(clones[id]) do clone:Collapse() end WeakAuras.regions[id].region:Collapse() elseif (show and oldShow) then -- Already shown, update regions -- Hide old clones for cloneId, clone in pairs(clones[id]) do if (not activeTriggerState[cloneId] or not activeTriggerState[cloneId].show) then clone:Collapse() end end if (not activeTriggerState[""] or not activeTriggerState[""].show) then WeakAuras.regions[id].region:Collapse() end -- Show new states ApplyStatesToRegions(id, newActiveTrigger, activeTriggerState); end for triggernum = 1, triggerState[id].numTriggers do triggerState[id][triggernum] = triggerState[id][triggernum] or {}; for cloneId, state in pairs(triggerState[id][triggernum]) do if (not state.show) then triggerState[id][triggernum][cloneId] = nil; end state.changed = false; end end end function Private.RunCustomTextFunc(region, customFunc) if not customFunc then return nil end local state = region.state Private.ActivateAuraEnvironment(region.id, region.cloneId, region.state, region.states); local progress = Private.dynamic_texts.p.func(Private.dynamic_texts.p.get(state), state, 1) local dur = Private.dynamic_texts.t.func(Private.dynamic_texts.t.get(state), state, 1) local name = Private.dynamic_texts.n.func(Private.dynamic_texts.n.get(state)) local icon = Private.dynamic_texts.i.func(Private.dynamic_texts.i.get(state)) local stacks = Private.dynamic_texts.s.func(Private.dynamic_texts.s.get(state)) local expirationTime local duration if state then if state.progressType == "timed" then expirationTime = state.expirationTime duration = state.duration else expirationTime = state.total duration = state.value end end local custom = {select(2, xpcall(customFunc, geterrorhandler(), expirationTime or math.huge, duration or 0, progress, dur, name, icon, stacks))} Private.ActivateAuraEnvironment(nil) return custom end local function ReplaceValuePlaceHolders(textStr, region, customFunc, state, formatter) local regionValues = region.values; local value; if string.sub(textStr, 1, 1) == "c" then local custom if customFunc then custom = Private.RunCustomTextFunc(region, customFunc) else custom = region.values.custom end local index = tonumber(textStr:match("^c(%d+)$") or 1) if custom then value = WeakAuras.EnsureString(custom[index]) end else local variable = Private.dynamic_texts[textStr]; if (not variable) then return nil; end value = variable.get(state) if formatter then value = formatter(value, state) elseif variable.func then value = variable.func(value) end end return value or ""; end -- States: -- 0 Normal state, text is just appended to result. Can transition to percent start state 1 via % -- 1 Percent start state, entered via %. Can transition to via { to braced, via % to normal, AZaz09 to percent rest state -- 2 Percent rest state, stay in it via AZaz09, transition to normal on anything else -- 3 Braced state, } transitions to normal, everything else stay in braced state local function nextState(char, state) if state == 0 then -- Normal State if char == 37 then -- % sign return 1 -- Enter Percent state end return 0 elseif state == 1 then -- Percent Start State if char == 37 then -- % sign return 0 -- Return to normal state elseif char == 123 then -- { sign return 3 -- Enter Braced state elseif (char >= 48 and char <= 57) or (char >= 65 and char <= 90) or (char >= 97 and char <= 122) or char == 46 then -- 0-9a-zA-Z or dot character return 2 -- Enter Percent rest state end return 0 -- % followed by non alpha-numeric. Back to normal state elseif state == 2 then if (char >= 48 and char <= 57) or (char >= 65 and char <= 90) or (char >= 97 and char <= 122) or char == 46 then return 2 -- Continue in same state end if char == 37 then return 1 -- End of %, but also start of new % end return 0 -- Back to normal elseif state == 3 then if char == 125 then -- } closing brace return 0 -- Back to normal end return 3 end -- Shouldn't happen return state end local function ContainsPlaceHolders(textStr, symbolFunc) if not textStr then return false end if textStr:find("\\n") then return true end local endPos = textStr:len(); local state = 0 local currentPos = 1 local start = 1 while currentPos <= endPos do local char = string.byte(textStr, currentPos); local nextState = nextState(char, state) if state == 1 then -- Last char was a % if char == 123 then start = currentPos + 1 else start = currentPos end elseif state == 2 or state == 3 then if nextState == 0 or nextState == 1 then local symbol = string.sub(textStr, start, currentPos - 1) if symbolFunc(symbol) then return true end end end state = nextState currentPos = currentPos + 1 end if state == 2 then local symbol = string.sub(textStr, start, currentPos - 1) if symbolFunc(symbol) then return true end end return false end function Private.ContainsCustomPlaceHolder(textStr) return ContainsPlaceHolders(textStr, function(symbol) return string.match(symbol, "^c%d*$") end) end function Private.ContainsPlaceHolders(textStr, toCheck) return ContainsPlaceHolders(textStr, function(symbol) if symbol:len() == 1 and toCheck:find(symbol, 1, true) then return true end local _, last = symbol:find("^%d+%.") if not last then return false end symbol = symbol:sub(last + 1) if symbol:len() == 1 and toCheck:find(symbol, 1, true) then return true end end) end function Private.ContainsAnyPlaceHolders(textStr) return ContainsPlaceHolders(textStr, function(symbol) return true end) end local function ValueForSymbol(symbol, region, customFunc, regionState, regionStates, useHiddenStates, formatters) local triggerNum, sym = string.match(symbol, "(.+)%.(.+)") triggerNum = triggerNum and tonumber(triggerNum) if triggerNum and sym then if regionStates[triggerNum] then if (useHiddenStates or regionStates[triggerNum].show) then if regionStates[triggerNum][sym] then local value = regionStates[triggerNum][sym] if formatters[symbol] then return tostring(formatters[symbol](value, regionStates[triggerNum])) or "" else return tostring(value) or "" end else local value = ReplaceValuePlaceHolders(sym, region, customFunc, regionStates[triggerNum], formatters[symbol]); return value or "" end end end return "" elseif regionState[symbol] then if(useHiddenStates or regionState.show) then local value = regionState[symbol] if formatters[symbol] then return tostring(formatters[symbol](value, regionState) or "") or "" else return tostring(value) or "" end end else local value = (useHiddenStates or regionState.show) and ReplaceValuePlaceHolders(symbol, region, customFunc, regionState, formatters[symbol]); return value or "" end end function Private.ReplacePlaceHolders(textStr, region, customFunc, useHiddenStates, formatters) local regionValues = region.values; local regionState = region.state or {}; local regionStates = region.states or {}; if (not regionState and not regionValues) then return; end local endPos = textStr:len(); if (endPos < 2) then textStr = textStr:gsub("\\n", "\n"); return textStr; end if (endPos == 2) then if string.byte(textStr, 1) == 37 then local symbol = string.sub(textStr, 2) local value = (regionState.show or useHiddenStates) and ReplaceValuePlaceHolders(symbol, region, customFunc, regionState, formatters[symbol]); if (value) then textStr = tostring(value); end end textStr = textStr:gsub("\\n", "\n"); return textStr; end local result = "" local currentPos = 1 -- Position of the "cursor" local state = 0 local start = 1 -- Start of whatever "word" we are currently considering, doesn't include % or {} symbols while currentPos <= endPos do local char = string.byte(textStr, currentPos); if state == 0 then -- Normal State if char == 37 then -- % sign if currentPos > start then result = result .. string.sub(textStr, start, currentPos - 1) end end elseif state == 1 then -- Percent Start State if char == 123 then start = currentPos + 1 else start = currentPos end elseif state == 2 then -- Percent Rest State if (char >= 48 and char <= 57) or (char >= 65 and char <= 90) or (char >= 97 and char <= 122) or char == 46 then -- 0-9a-zA-Z or dot character else -- End of variable local symbol = string.sub(textStr, start, currentPos - 1) result = result .. ValueForSymbol(symbol, region, customFunc, regionState, regionStates, useHiddenStates, formatters) if char == 37 then -- Do nothing else start = currentPos end end elseif state == 3 then if char == 125 then -- } closing brace local symbol = string.sub(textStr, start, currentPos - 1) result = result .. ValueForSymbol(symbol, region, customFunc, regionState, regionStates, useHiddenStates, formatters) start = currentPos + 1 end end state = nextState(char, state) currentPos = currentPos + 1 end if state == 0 and currentPos > start then result = result .. string.sub(textStr, start, currentPos - 1) elseif state == 2 and currentPos > start then local symbol = string.sub(textStr, start, currentPos - 1) result = result .. ValueForSymbol(symbol, region, customFunc, regionState, regionStates, useHiddenStates, formatters) elseif state == 1 then result = result .. "%" end textStr = result:gsub("\\n", "\n"); return textStr; end function Private.ParseTextStr(textStr, symbolCallback) if not textStr then return end local endPos = textStr:len(); local currentPos = 1 -- Position of the "cursor" local state = 0 local start = 1 -- Start of whatever "word" we are currently considering, doesn't include % or {} symbols while currentPos <= endPos do local char = string.byte(textStr, currentPos); if state == 0 then -- Normal State elseif state == 1 then -- Percent Start State if char == 123 then start = currentPos + 1 else start = currentPos end elseif state == 2 then -- Percent Rest State if (char >= 48 and char <= 57) or (char >= 65 and char <= 90) or (char >= 97 and char <= 122) or char == 46 then -- 0-9a-zA-Z or dot character else -- End of variable local symbol = string.sub(textStr, start, currentPos - 1) symbolCallback(symbol) if char == 37 then -- Do nothing else start = currentPos end end elseif state == 3 then if char == 125 then -- } closing brace local symbol = string.sub(textStr, start, currentPos - 1) symbolCallback(symbol) start = currentPos + 1 end end state = nextState(char, state) currentPos = currentPos + 1 end if state == 2 and currentPos > start then local symbol = string.sub(textStr, start, currentPos - 1) symbolCallback(symbol) end end function Private.CreateFormatters(input, getter) local seenSymbols = {} local formatters = {} Private.ParseTextStr(input, function(symbol) if not seenSymbols[symbol] then local triggerNum, sym = string.match(symbol, "(.+)%.(.+)") sym = sym or symbol if sym == "c" or sym == "i" then -- Do nothing else local default = (sym == "p" or sym == "t") and "timed" or "none" local selectedFormat = getter(symbol .. "_format", default) if (Private.format_types[selectedFormat]) then formatters[symbol] = Private.format_types[selectedFormat].CreateFormatter(symbol, getter) end end end seenSymbols[symbol] = true end) return formatters end function Private.IsAuraActive(uid) local id = Private.UIDtoID(uid) local active = triggerState[id]; return active and active.show; end function WeakAuras.IsAuraActive(id) local active = triggerState[id] return active and active.show end function Private.ActiveTrigger(uid) local id = Private.UIDtoID(uid) return triggerState[id] and triggerState[id].activeTrigger end -- Attach to Cursor/Frames code -- Very simple function to convert a hsv angle to a color with -- value hardcoded to 1 and saturation hardcoded to 0.75 local function colorWheel(angle) local hh = angle / 60; local i = floor(hh); local ff = hh - i; local p = 0; local q = 0.75 * (1.0 - ff); local t = 0.75 * ff; if (i == 0) then return 0.75, t, p; elseif (i == 1) then return q, 0.75, p; elseif (i == 2) then return p, 0.75, t; elseif (i == 3) then return p, q, 0.75; elseif (i == 4) then return t, p, 0.75; else return 0.75, p, q; end end local function xPositionNextToOptions() local xOffset; local optionsFrame = WeakAuras.OptionsFrame(); local centerX = (optionsFrame:GetLeft() + optionsFrame:GetRight()) / 2; if (centerX > GetScreenWidth() / 2) then if (optionsFrame:GetLeft() > 400) then xOffset = optionsFrame:GetLeft() - 200; else xOffset = optionsFrame:GetLeft() / 2; end else if (GetScreenWidth() - optionsFrame:GetRight() > 400 ) then xOffset = optionsFrame:GetRight() + 200; else xOffset = (GetScreenWidth() + optionsFrame:GetRight()) / 2; end end return xOffset; end local mouseFrame; local function ensureMouseFrame() if (mouseFrame) then return; end mouseFrame = CreateFrame("FRAME", "WeakAurasAttachToMouseFrame", UIParent); mouseFrame.attachedVisibleFrames = {}; mouseFrame:SetWidth(1); mouseFrame:SetHeight(1); local moverFrame = CreateFrame("FRAME", "WeakAurasMousePointerFrame", mouseFrame); mouseFrame.moverFrame = moverFrame; moverFrame:SetPoint("TOPLEFT", mouseFrame, "CENTER"); moverFrame:SetWidth(32); moverFrame:SetHeight(32); moverFrame:SetFrameStrata("FULLSCREEN"); -- above settings dialog moverFrame:EnableMouse(true) moverFrame:SetScript("OnMouseDown", function() mouseFrame:SetMovable(true); mouseFrame:StartMoving() end); moverFrame:SetScript("OnMouseUp", function() mouseFrame:StopMovingOrSizing(); mouseFrame:SetMovable(false); local xOffset = mouseFrame:GetRight() - GetScreenWidth(); local yOffset = mouseFrame:GetTop() - GetScreenHeight(); db.mousePointerFrame = db.mousePointerFrame or {}; db.mousePointerFrame.xOffset = xOffset; db.mousePointerFrame.yOffset = yOffset; end); moverFrame.colorWheelAnimation = function() local angle = ((GetTime() - moverFrame.startTime) % 5) / 5 * 360; moverFrame.texture:SetVertexColor(colorWheel(angle)); end; local texture = moverFrame:CreateTexture(nil, "BACKGROUND"); moverFrame.texture = texture; texture:SetAllPoints(moverFrame); texture:SetTexture("Interface\\Cursor\\Point"); local label = moverFrame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") label:SetJustifyH("LEFT") label:SetJustifyV("TOP") label:SetPoint("TOPLEFT", moverFrame, "BOTTOMLEFT"); label:SetText("WeakAuras Anchor"); moverFrame:Hide(); mouseFrame.OptionsOpened = function() if (db.mousePointerFrame) then -- Restore from settings mouseFrame:ClearAllPoints(); mouseFrame:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", db.mousePointerFrame.xOffset, db.mousePointerFrame.yOffset); else -- Fnd a suitable position local optionsFrame = WeakAuras.OptionsFrame(); local yOffset = (optionsFrame:GetTop() + optionsFrame:GetBottom()) / 2; local xOffset = xPositionNextToOptions(); -- We use the top right, because the main frame uses the top right as the reference too mouseFrame:ClearAllPoints(); mouseFrame:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", xOffset - GetScreenWidth(), yOffset - GetScreenHeight()); end -- Change the color of the mouse cursor moverFrame.startTime = GetTime(); moverFrame:SetScript("OnUpdate", moverFrame.colorWheelAnimation); mouseFrame:SetScript("OnUpdate", nil); end mouseFrame.moveWithMouse = function() local scale = 1 / UIParent:GetEffectiveScale(); local x, y = GetCursorPosition(); mouseFrame:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x * scale, y * scale); end mouseFrame.OptionsClosed = function() moverFrame:Hide(); mouseFrame:ClearAllPoints(); mouseFrame:SetScript("OnUpdate", mouseFrame.moveWithMouse); moverFrame:SetScript("OnUpdate", nil); wipe(mouseFrame.attachedVisibleFrames); end mouseFrame.expand = function(self, id) local data = WeakAuras.GetData(id); if (data.anchorFrameType == "MOUSE") then self.attachedVisibleFrames[id] = true; self:updateVisible(); end end mouseFrame.collapse = function(self, id) self.attachedVisibleFrames[id] = nil; self:updateVisible(); end mouseFrame.rename = function(self, oldid, newid) self.attachedVisibleFrames[newid] = self.attachedVisibleFrames[oldid]; self.attachedVisibleFrames[oldid] = nil; self:updateVisible(); end mouseFrame.delete = function(self, id) self.attachedVisibleFrames[id] = nil; self:updateVisible(); end mouseFrame.anchorFrame = function(self, id, anchorFrameType) if (anchorFrameType == "MOUSE") then self.attachedVisibleFrames[id] = true; else self.attachedVisibleFrames[id] = nil; end self:updateVisible(); end mouseFrame.updateVisible = function(self) if (not WeakAuras.IsOptionsOpen()) then return; end if (next(self.attachedVisibleFrames)) then mouseFrame.moverFrame:Show(); else mouseFrame.moverFrame:Hide(); end end if (WeakAuras.IsOptionsOpen()) then mouseFrame:OptionsOpened(); else mouseFrame:OptionsClosed(); end Private.mouseFrame = mouseFrame; end local personalRessourceDisplayFrame; function Private.ensurePRDFrame() if (personalRessourceDisplayFrame) then return; end personalRessourceDisplayFrame = CreateFrame("FRAME", "WeakAurasAttachToPRD", UIParent); personalRessourceDisplayFrame:Hide(); personalRessourceDisplayFrame.attachedVisibleFrames = {}; Private.personalRessourceDisplayFrame = personalRessourceDisplayFrame; local moverFrame = CreateFrame("FRAME", "WeakAurasPRDMoverFrame", personalRessourceDisplayFrame); personalRessourceDisplayFrame.moverFrame = moverFrame; moverFrame:SetPoint("TOPLEFT", personalRessourceDisplayFrame, "TOPLEFT", -2, 2); moverFrame:SetPoint("BOTTOMRIGHT", personalRessourceDisplayFrame, "BOTTOMRIGHT", 2, -2); moverFrame:SetFrameStrata("FULLSCREEN"); -- above settings dialog moverFrame:EnableMouse(true) moverFrame:SetScript("OnMouseDown", function() personalRessourceDisplayFrame:SetMovable(true); personalRessourceDisplayFrame:StartMoving() end); moverFrame:SetScript("OnMouseUp", function() personalRessourceDisplayFrame:StopMovingOrSizing(); personalRessourceDisplayFrame:SetMovable(false); local xOffset = personalRessourceDisplayFrame:GetRight(); local yOffset = personalRessourceDisplayFrame:GetTop(); db.personalRessourceDisplayFrame = db.personalRessourceDisplayFrame or {}; local scale = UIParent:GetEffectiveScale() / personalRessourceDisplayFrame:GetEffectiveScale(); db.personalRessourceDisplayFrame.xOffset = xOffset / scale - GetScreenWidth(); db.personalRessourceDisplayFrame.yOffset = yOffset / scale - GetScreenHeight(); end); moverFrame:Hide(); local texture = moverFrame:CreateTexture(nil, "BACKGROUND"); personalRessourceDisplayFrame.texture = texture; texture:SetAllPoints(moverFrame); texture:SetTexture("Interface\\AddOns\\WeakAuras\\Media\\Textures\\PRDFrame"); local label = moverFrame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight") label:SetPoint("CENTER", moverFrame, "CENTER"); label:SetText("WeakAuras Anchor"); personalRessourceDisplayFrame:RegisterEvent('NAME_PLATE_UNIT_ADDED'); personalRessourceDisplayFrame:RegisterEvent('NAME_PLATE_UNIT_REMOVED'); personalRessourceDisplayFrame.Attach = function(self, frame, frameTL, frameBR) self:SetParent(frame); self:ClearAllPoints(); self:SetPoint("TOPLEFT", frameTL, "TOPLEFT"); self:SetPoint("BOTTOMRIGHT", frameBR, "BOTTOMRIGHT"); self:Show() end personalRessourceDisplayFrame.Detach = function(self, frame) self:ClearAllPoints(); self:Hide() self:SetParent(UIParent) end personalRessourceDisplayFrame.OptionsOpened = function() personalRessourceDisplayFrame:Detach(); personalRessourceDisplayFrame:SetScript("OnEvent", nil); personalRessourceDisplayFrame:ClearAllPoints(); personalRessourceDisplayFrame:Show() local xOffset, yOffset; if (db.personalRessourceDisplayFrame) then xOffset = db.personalRessourceDisplayFrame.xOffset; yOffset = db.personalRessourceDisplayFrame.yOffset; end -- Calculate size of self nameplate local prdWidth; local prdHeight; if (KuiNameplatesCore and KuiNameplatesCore.profile) then prdWidth = KuiNameplatesCore.profile.frame_width_personal; prdHeight = KuiNameplatesCore.profile.frame_height_personal; if (KuiNameplatesCore.profile.ignore_uiscale) then local _, screenWidth = GetPhysicalScreenSize(); local uiScale = 1; if (screenWidth) then uiScale = 768 / screenWidth; end personalRessourceDisplayFrame:SetScale(uiScale / UIParent:GetEffectiveScale()); else personalRessourceDisplayFrame:SetScale(1); end personalRessourceDisplayFrame.texture:SetTexture("Interface\\AddOns\\WeakAuras\\Media\\Textures\\PRDFrameKui"); else local namePlateVerticalScale = tonumber(GetCVar("NamePlateVerticalScale")); local zeroBasedScale = namePlateVerticalScale - 1.0; local clampedZeroBasedScale = Saturate(zeroBasedScale); local horizontalScale = tonumber(GetCVar("NamePlateHorizontalScale")); local baseNamePlateWidth = NamePlateDriverFrame.baseNamePlateWidth; prdWidth = baseNamePlateWidth * horizontalScale * Lerp(1.1, 1.0, clampedZeroBasedScale) - 24; prdHeight = 4 * namePlateVerticalScale * Lerp(1.2, 1.0, clampedZeroBasedScale) * 2 + 1; personalRessourceDisplayFrame:SetScale(1 / UIParent:GetEffectiveScale()); personalRessourceDisplayFrame.texture:SetTexture("Interface\\AddOns\\WeakAuras\\Media\\Textures\\PRDFrame"); end local scale = UIParent:GetEffectiveScale() / personalRessourceDisplayFrame:GetEffectiveScale(); if (not xOffset or not yOffset) then local optionsFrame = WeakAuras.OptionsFrame(); yOffset = optionsFrame:GetBottom() + prdHeight / scale - GetScreenHeight(); xOffset = xPositionNextToOptions() + prdWidth / 2 / scale - GetScreenWidth(); end xOffset = xOffset * scale; yOffset = yOffset * scale; personalRessourceDisplayFrame:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", xOffset, yOffset); personalRessourceDisplayFrame:SetPoint("BOTTOMLEFT", UIParent, "TOPRIGHT", xOffset - prdWidth, yOffset - prdHeight); end personalRessourceDisplayFrame.OptionsClosed = function() personalRessourceDisplayFrame:SetScale(1); local frame = C_NamePlate.GetNamePlateForUnit("player"); if (frame) then if (Plater and frame.Plater and frame.unitFrame.Plater) then personalRessourceDisplayFrame:Attach(frame, frame.unitFrame.healthBar, frame.unitFrame.powerBar); elseif (frame.kui and frame.kui.bg and frame.kui:IsShown()) then personalRessourceDisplayFrame:Attach(frame.kui, frame.kui.bg, frame.kui.bg); elseif (ElvUIPlayerNamePlateAnchor) then personalRessourceDisplayFrame:Attach(ElvUIPlayerNamePlateAnchor, ElvUIPlayerNamePlateAnchor, ElvUIPlayerNamePlateAnchor); else personalRessourceDisplayFrame:Attach(frame, frame.UnitFrame.healthBar, NamePlateDriverFrame.classNamePlatePowerBar); end else personalRessourceDisplayFrame:Detach(); personalRessourceDisplayFrame:Hide(); end personalRessourceDisplayFrame:SetScript("OnEvent", personalRessourceDisplayFrame.eventHandler); personalRessourceDisplayFrame.texture:Hide(); personalRessourceDisplayFrame.moverFrame:Hide(); wipe(personalRessourceDisplayFrame.attachedVisibleFrames); end personalRessourceDisplayFrame.eventHandler = function(self, event, nameplate) Private.StartProfileSystem("prd"); if (event == "NAME_PLATE_UNIT_ADDED") then if (UnitIsUnit(nameplate, "player")) then local frame = C_NamePlate.GetNamePlateForUnit("player"); if (frame) then if (Plater and frame.Plater and frame.unitFrame.Plater) then personalRessourceDisplayFrame:Attach(frame, frame.unitFrame.healthBar, frame.unitFrame.powerBar); elseif (frame.kui and frame.kui.bg and frame.kui:IsShown()) then personalRessourceDisplayFrame:Attach(frame.kui, KuiNameplatesPlayerAnchor, KuiNameplatesPlayerAnchor); elseif (ElvUIPlayerNamePlateAnchor) then personalRessourceDisplayFrame:Attach(ElvUIPlayerNamePlateAnchor, ElvUIPlayerNamePlateAnchor, ElvUIPlayerNamePlateAnchor); else personalRessourceDisplayFrame:Attach(frame, frame.UnitFrame.healthBar, NamePlateDriverFrame.classNamePlatePowerBar); end personalRessourceDisplayFrame:Show(); db.personalRessourceDisplayFrame = db.personalRessourceDisplayFrame or {}; else personalRessourceDisplayFrame:Detach(); personalRessourceDisplayFrame:Hide(); end end elseif (event == "NAME_PLATE_UNIT_REMOVED") then if (UnitIsUnit(nameplate, "player")) then personalRessourceDisplayFrame:Detach(); personalRessourceDisplayFrame:Hide(); end end Private.StopProfileSystem("prd"); end personalRessourceDisplayFrame.expand = function(self, id) local data = WeakAuras.GetData(id); if (data.anchorFrameType == "PRD") then self.attachedVisibleFrames[id] = true; self:updateVisible(); end end personalRessourceDisplayFrame.collapse = function(self, id) self.attachedVisibleFrames[id] = nil; self:updateVisible(); end personalRessourceDisplayFrame.rename = function(self, oldid, newid) self.attachedVisibleFrames[newid] = self.attachedVisibleFrames[oldid]; self.attachedVisibleFrames[oldid] = nil; self:updateVisible(); end personalRessourceDisplayFrame.delete = function(self, id) self.attachedVisibleFrames[id] = nil; self:updateVisible(); end personalRessourceDisplayFrame.anchorFrame = function(self, id, anchorFrameType) if (anchorFrameType == "PRD" or anchorFrameType == "NAMEPLATE") then self.attachedVisibleFrames[id] = true; else self.attachedVisibleFrames[id] = nil; end self:updateVisible(); end personalRessourceDisplayFrame.updateVisible = function(self) if (not WeakAuras.IsOptionsOpen()) then return; end if (next(self.attachedVisibleFrames)) then personalRessourceDisplayFrame.texture:Show(); personalRessourceDisplayFrame.moverFrame:Show(); personalRessourceDisplayFrame:Show(); else personalRessourceDisplayFrame.texture:Hide(); personalRessourceDisplayFrame.moverFrame:Hide(); personalRessourceDisplayFrame:Hide(); end end if (WeakAuras.IsOptionsOpen()) then personalRessourceDisplayFrame.OptionsOpened(); else personalRessourceDisplayFrame.OptionsClosed(); end Private.personalRessourceDisplayFrame = personalRessourceDisplayFrame end local postPonedAnchors = {}; local anchorTimer local function tryAnchorAgain() local delayed = postPonedAnchors; postPonedAnchors = {}; anchorTimer = nil; for id, _ in pairs(delayed) do local data = WeakAuras.GetData(id); local region = WeakAuras.GetRegion(id); if (data and region) then local parent = frame; if (data.parent and regions[data.parent]) then parent = regions[data.parent].region; end Private.AnchorFrame(data, region, parent); end end end local function postponeAnchor(id) postPonedAnchors[id] = true; if (not anchorTimer) then anchorTimer = timer:ScheduleTimer(tryAnchorAgain, 1); end end local HiddenFrames = CreateFrame("FRAME", "WeakAurasHiddenFrames") HiddenFrames:Hide() WeakAuras.HiddenFrames = HiddenFrames local function GetAnchorFrame(data, region, parent) local id = region.id local anchorFrameType = data.anchorFrameType local anchorFrameFrame = data.anchorFrameFrame if not id then return end if (personalRessourceDisplayFrame) then personalRessourceDisplayFrame:anchorFrame(id, anchorFrameType); end if (mouseFrame) then mouseFrame:anchorFrame(id, anchorFrameType); end if (anchorFrameType == "SCREEN") then return parent; end if (anchorFrameType == "PRD") then Private.ensurePRDFrame(); personalRessourceDisplayFrame:anchorFrame(id, anchorFrameType); return personalRessourceDisplayFrame; end if (anchorFrameType == "MOUSE") then ensureMouseFrame(); mouseFrame:anchorFrame(id, anchorFrameType); return mouseFrame; end if (anchorFrameType == "NAMEPLATE") then local unit = region.state.unit local frame = unit and WeakAuras.GetUnitNameplate(unit) if frame then return frame end if WeakAuras.IsOptionsOpen() then Private.ensurePRDFrame() personalRessourceDisplayFrame:anchorFrame(id, anchorFrameType) return personalRessourceDisplayFrame end end if (anchorFrameType == "UNITFRAME") then local unit = region.state.unit if unit then local frame = WeakAuras.GetUnitFrame(unit) or WeakAuras.HiddenFrames if frame then anchor_unitframe_monitor = anchor_unitframe_monitor or {} anchor_unitframe_monitor[region] = { data = data, parent = parent, frame = frame } return frame end end end if (anchorFrameType == "SELECTFRAME" and anchorFrameFrame) then if(anchorFrameFrame:sub(1, 10) == "WeakAuras:") then local frame_name = anchorFrameFrame:sub(11); if (frame_name == id) then return parent; end if(regions[frame_name]) then return regions[frame_name].region; end postponeAnchor(id); else if (Private.GetSanitizedGlobal(anchorFrameFrame)) then return Private.GetSanitizedGlobal(anchorFrameFrame); end postponeAnchor(id); return parent; end end if (anchorFrameType == "CUSTOM" and region.customAnchorFunc) then Private.StartProfileSystem("custom region anchor") Private.StartProfileAura(region.id) Private.ActivateAuraEnvironment(region.id, region.cloneId, region.state) local ok, frame = xpcall(region.customAnchorFunc, geterrorhandler()) Private.ActivateAuraEnvironment() Private.StopProfileSystem("custom region anchor") Private.StopProfileAura(region.id) if ok and frame then return frame elseif WeakAuras.IsOptionsOpen() then return parent else return HiddenFrames end end -- Fallback return parent; end local anchorFrameDeferred = {} function Private.AnchorFrame(data, region, parent) if data.anchorFrameType == "CUSTOM" and (data.regionType == "group" or data.regionType == "dynamicgroup") and not WeakAuras.IsLoginFinished() and not anchorFrameDeferred[data.id] then loginQueue[#loginQueue + 1] = {Private.AnchorFrame, {data, region, parent}} anchorFrameDeferred[data.id] = true else local anchorParent = GetAnchorFrame(data, region, parent); if not anchorParent then return end if (data.anchorFrameParent or data.anchorFrameParent == nil or data.anchorFrameType == "SCREEN" or data.anchorFrameType == "MOUSE") then local errorhandler = function(text) geterrorhandler()(L["'ERROR: Anchoring %s': \n"]:format(data.id) .. text) end xpcall(region.SetParent, errorhandler, region, anchorParent); else region:SetParent(parent or frame); end local anchorPoint = data.anchorPoint if data.parent then if data.anchorFrameType == "SCREEN" or data.anchorFrameType == "MOUSE" then anchorPoint = "CENTER" end else if data.anchorFrameType == "MOUSE" then anchorPoint = "CENTER" end end region:SetAnchor(data.selfPoint, anchorParent, anchorPoint); if(data.frameStrata == 1) then region:SetFrameStrata(region:GetParent():GetFrameStrata()); else region:SetFrameStrata(Private.frame_strata_types[data.frameStrata]); end Private.ApplyFrameLevel(region) anchorFrameDeferred[data.id] = nil end end function WeakAuras.FindUnusedId(prefix) prefix = prefix or "New" local num = 2; local id = prefix while(db.displays[id]) do id = prefix .. " " .. num; num = num + 1; end return id end function WeakAuras.SetModel(frame, model_path, model_fileId, isUnit, isDisplayInfo) if WeakAuras.IsClassic() then if isDisplayInfo then pcall(frame.SetDisplayInfo, frame, tonumber(model_path)) elseif isUnit then pcall(frame.SetUnit, frame, model_path) else pcall(frame.SetModel, frame, model_path) end else if isDisplayInfo then pcall(frame.SetDisplayInfo, frame, tonumber(model_fileId)) elseif isUnit then pcall(frame.SetUnit, frame, model_fileId) else pcall(frame.SetModel, frame, tonumber(model_fileId)) end end end function Private.IsCLEUSubevent(subevent) if Private.subevent_prefix_types[subevent] then return true else for prefix in pairs(Private.subevent_prefix_types) do if subevent:match(prefix) then local suffix = subevent:sub(#prefix + 1) if Private.subevent_suffix_types[suffix] then return true end end end end return false end -- SafeToNumber converts a string to number, but only if it fits into a unsigned 32bit integer -- The C api often takes only 32bit values, and complains if passed a value outside function WeakAuras.SafeToNumber(input) local nr = tonumber(input) return nr and (nr < 2147483648 and nr > -2147483649) and nr or nil end local textSymbols = { ["{rt1}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_1:0|t", ["{rt2}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_2:0|t ", ["{rt3}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_3:0|t ", ["{rt4}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_4:0|t ", ["{rt5}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_5:0|t ", ["{rt6}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_6:0|t ", ["{rt7}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_7:0|t ", ["{rt8}"] = "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_8:0|t " } function WeakAuras.ReplaceRaidMarkerSymbols(txt) local start = 1 while true do local firstChar = txt:find("{", start, true) if not firstChar then return txt end local lastChar = txt:find("}", firstChar, true) if not lastChar then return txt end local replace = textSymbols[txt:sub(firstChar, lastChar)] if replace then txt = txt:sub(1, firstChar - 1) .. replace .. txt:sub(lastChar + 1) start = firstChar + #replace else start = lastChar end end end function Private.ReplaceLocalizedRaidMarkers(txt) local start = 1 while true do local firstChar = txt:find("{", start, true) if not firstChar then return txt end local lastChar = txt:find("}", firstChar, true) if not lastChar then return txt end local symbol = strlower(txt:sub(firstChar + 1, lastChar - 1)) if ICON_TAG_LIST[symbol] then local replace = "rt" .. ICON_TAG_LIST[symbol] if replace then txt = txt:sub(1, firstChar) .. replace .. txt:sub(lastChar) start = firstChar + #replace else start = lastChar end else start = lastChar end end end do local trackableUnits = {} trackableUnits["player"] = true trackableUnits["target"] = true trackableUnits["focus"] = true trackableUnits["pet"] = true trackableUnits["vehicle"] = true for i = 1, 5 do trackableUnits["arena" .. i] = true trackableUnits["arenapet" .. i] = true end for i = 1, 4 do trackableUnits["party" .. i] = true trackableUnits["partypet" .. i] = true end for i = 1, MAX_BOSS_FRAMES do trackableUnits["boss" .. i] = true end for i = 1, 40 do trackableUnits["raid" .. i] = true trackableUnits["raidpet" .. i] = true trackableUnits["nameplate" .. i] = true end function WeakAuras.UntrackableUnit(unit) return not trackableUnits[unit] end end do local ownRealm = select(2, UnitFullName("player")) function WeakAuras.UnitNameWithRealm(unit) ownRealm = ownRealm or select(2, UnitFullName("player")) local name, realm = UnitFullName(unit) return name or "", realm or ownRealm or "" end end function WeakAuras.ParseNameCheck(name) local matches = { name = {}, realm = {}, full = {}, AddMatch = function(self, name, start, last) local match = strtrim(name:sub(start, last)) if (match:sub(1, 1) == "-") then self.realm[match:sub(2)] = true elseif match:find("-", 1, true) then self.full[match] = true else self.name[match] = true end end, Check = function(self, name, realm) if not name or not realm then return false end return self.name[name] or self.realm[realm] or self.full[name .. "-" .. realm] end } if not name then return end local start = 1 local last = name:find(',', start, true) while (last) do matches:AddMatch(name, start, last - 1) start = last + 1 last = name:find(',', start, true) end last = #name matches:AddMatch(name, start, last) return matches end function WeakAuras.IsAuraLoaded(id) return Private.loaded[id] end function Private.IconSources(data) local values = { [-1] = L["Dynamic Information"], [0] = L["Fallback Icon"], } for i = 1, #data.triggers do values[i] = string.format(L["Trigger %i"], i) end return values end
gpl-2.0
samuelctabor/ardupilot
libraries/AP_Scripting/examples/LED_roll.lua
26
2127
--[[ Script to control LED strips based on the roll of the aircraft. This is an example to demonstrate the LED interface for WS2812 LEDs --]] --[[ for this demo we will use a single strip with 30 LEDs --]] local num_leds = 30 --[[ use SERVOn_FUNCTION 94 for LED. We can control up to 16 separate strips of LEDs by putting them on different channels --]] local chan = SRV_Channels:find_channel(94) if not chan then gcs:send_text(6, "LEDs: channel not set") return end -- find_channel returns 0 to 15, convert to 1 to 16 chan = chan + 1 gcs:send_text(6, "LEDs: chan=" .. tostring(chan)) -- initialisation code --serialLED:set_num_neopixel(chan, num_leds) serialLED:set_num_profiled(chan, num_leds) -- constrain a value between limits function constrain(v, vmin, vmax) if v < vmin then v = vmin end if v > vmax then v = vmax end return v end --[[ Table of colors on a rainbow, red first --]] local rainbow = { { 255, 0, 0 }, { 255, 127, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 0, 255 }, { 75, 0, 130 }, { 143, 0, 255 }, } --[[ Function to set a LED to a color on a classic rainbow spectrum, with v=0 giving red --]] function set_Rainbow(chan, led, v) local num_rows = #rainbow local row = math.floor(constrain(v * (num_rows-1)+1, 1, num_rows-1)) local v0 = (row-1) / (num_rows-1) local v1 = row / (num_rows-1) local p = (v - v0) / (v1 - v0) r = math.floor(rainbow[row][1] + p * (rainbow[row+1][1] - rainbow[row][1])) g = math.floor(rainbow[row][2] + p * (rainbow[row+1][2] - rainbow[row][2])) b = math.floor(rainbow[row][3] + p * (rainbow[row+1][3] - rainbow[row][3])) serialLED:set_RGB(chan, led, r, g, b) end --[[ We will set the colour of the LEDs based on roll of the aircraft --]] function update_LEDs() local roll = constrain(ahrs:get_roll(), math.rad(-60), math.rad(60)) for led = 0, num_leds-1 do local v = constrain(0.5 + 0.5 * math.sin(roll * (led - num_leds/2) / (num_leds/2)), 0, 1) set_Rainbow(chan, led, v) end serialLED:send(chan) return update_LEDs, 20 -- run at 50Hz end return update_LEDs, 1000
gpl-3.0
deepak78/new-luci
applications/luci-app-statistics/luasrc/statistics/i18n.lua
29
2184
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance._translate( self, key, alt ) local val = self.i18n.string(key) if val ~= key then return val else return alt end end function Instance.title( self, plugin, pinst, dtype, dinst, user_title ) local title = user_title or "p=%s/pi=%s/dt=%s/di=%s" % { plugin, (pinst and #pinst > 0) and pinst or "(nil)", (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst, user_label ) local label = user_label or "dt=%s/di=%s" % { (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = source.title or self:_translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self:_translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self:_translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self:_translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
apache-2.0
m-creations/openwrt
feeds/luci/applications/luci-app-statistics/luasrc/statistics/i18n.lua
29
2184
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance._translate( self, key, alt ) local val = self.i18n.string(key) if val ~= key then return val else return alt end end function Instance.title( self, plugin, pinst, dtype, dinst, user_title ) local title = user_title or "p=%s/pi=%s/dt=%s/di=%s" % { plugin, (pinst and #pinst > 0) and pinst or "(nil)", (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst, user_label ) local label = user_label or "dt=%s/di=%s" % { (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = source.title or self:_translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self:_translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self:_translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self:_translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
gpl-2.0
airsalliance/gateway_implementation_demo
proxy_configs/authorize.lua
1
2512
local random = require 'resty.random' local cjson = require 'cjson' local ts = require 'threescale_utils' local redis = require 'resty.redis' local red = redis:new() function check_return_url(client_id, return_url) local res = ngx.location.capture("/_threescale/redirect_uri_matches", { vars = { red_url = return_url , client_id = client_id }}) return (res.status == 200) end -- returns 2 values: ok, err -- if ok == true, err is undefined -- if ok == false, err contains the errors function authorize(params) -- scope is required because the provider needs to know which plan -- is the user trying to log to local required_params = {'client_id', 'redirect_uri', 'response_type', 'scope'} if ts.required_params_present(required_params, params) and params["response_type"] == 'code' and check_return_url(params.client_id, params.redirect_uri) then redirect_to_login(params) elseif params["response_type"] ~= 'code' then return false, 'unsupported_response_type' else ngx.log(0, ts.dump(params)) return false, 'invalid_request' end ts.error("we should never be here") end -- returns a unique string for the client_id. it will be short lived function nonce(client_id) return ts.sha1_digest(tostring(random.bytes(20, true)) .. "#login:" .. client_id) end function generate_access_token(client_id) return ts.sha1_digest(tostring(random.bytes(20, true)) .. client_id) end -- redirects_to the login form of the API provider with a secret -- 'state' which will be used when the form redirects the user back to -- this server. function redirect_to_login(params) local n = nonce(params.client_id) ngx.log(0, "redirect_to_login") params.scope = params.scope ts.connect_redis(red) local pre_token = generate_access_token(params.client_id) local ok, err = red:hmset(ngx.var.service_id .. "#tmp_data:".. n, {client_id = params.client_id, redirect_uri = params.redirect_uri, plan_id = params.scope, pre_access_token = pre_token}) if not ok then ts.error(ts.dump(err)) end -- TODO: If the login_url has already the parameter state bad -- things are to happen ngx.redirect(ngx.var.login_url .. "?&scope=".. params.scope .. "&state=" .. n .. "&tok=".. pre_token) ngx.exit(ngx.HTTP_OK) end local params = ngx.req.get_uri_args() local _ok, a_err = authorize(params) if not a_ok then ngx.redirect(ngx.var.login_url .. "?&scope=" .. params.scope .. "&state=" .. (params.state or '') .. "&error=" .. a_err) end
mit
spark51/spark_robot
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
m-creations/openwrt
feeds/routing/bird-openwrt/bird4-openwrt/src/model/gen_proto.lua
7
6399
--[[ Copyright (C) 2014 - Eloi Carbó Solé (GSoC2014) BGP/Bird integration with OpenWRT and QMP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] require("luci.sys") local http = require "luci.http" local uci = require "luci.model.uci" local uciout = uci.cursor() m=Map("bird4", "Bird4 general protocol's configuration.") -- Optional parameters lists local protoptions = { {["name"]="table", ["help"]="Auxiliar table for routing", ["depends"]={"static","kernel"}}, {["name"]="import", ["help"]="Set if the protocol must import routes", ["depends"]={"kernel"}}, {["name"]="export", ["help"]="Set if the protocol must export routes", ["depends"]={"kernel"}}, {["name"]="scan_time", ["help"]="Time between scans", ["depends"]={"kernel","device"}}, {["name"]="kernel_table", ["help"]="Set which table must be used as auxiliar kernel table", ["depends"]={"kernel"}}, {["name"]="learn", ["help"]="Learn routes", ["depends"]={"kernel"}}, {["name"]="persist", ["help"]="Store routes. After a restart, routes will be still configured", ["depends"]={"kernel"}} } local routeroptions = { {["name"]="prefix",["help"]="",["depends"]={"router","special","iface","multipath","recursive"}}, {["name"]="via",["help"]="",["depends"]={"router","multipath"}}, {["name"]="attribute",["help"]="",["depends"]={"special"}}, {["name"]="iface",["help"]="",["depends"]={"iface"}}, {["name"]="ip",["help"]="",["depends"]={"recursive"}} } -- -- KERNEL PROTOCOL -- sect_kernel_protos = m:section(TypedSection, "kernel", "Kernel options", "Configuration of the kernel protocols. First Instance MUST be Primary table (no table or kernel_table fields).") sect_kernel_protos.addremove = true sect_kernel_protos.anonymous = false -- Default kernel parameters disabled = sect_kernel_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.") disabled.default=0 -- Optional parameters for _,o in ipairs(protoptions) do if o.name ~= nil then for _, d in ipairs(o.depends) do if d == "kernel" then if o.name == "learn" or o.name == "persist" then value = sect_kernel_protos:option(Flag, o.name, translate(o.name), translate(o.help)) elseif o.name == "table" then value = sect_kernel_protos:option(ListValue, o.name, translate(o.name), translate(o.help)) uciout:foreach("bird4", "table", function (s) value:value(s.name) end) value:value("") else value = sect_kernel_protos:option(Value, o.name, translate(o.name), translate(o.help)) end value.optional = true value.rmempty = true end end end end -- -- DEVICE PROTOCOL -- sect_device_protos = m:section(TypedSection, "device", "Device options", "Configuration of the device protocols.") sect_device_protos.addremove = true sect_device_protos.anonymous = false -- Default kernel parameters disabled = sect_device_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.") disabled.default=0 -- Optional parameters for _,o in ipairs(protoptions) do if o.name ~= nil then for _, d in ipairs(o.depends) do if d == "device" then value = sect_device_protos:option(Value, o.name, translate(o.name), translate(o.help)) value.optional = true value.rmempty = true end end end end -- -- STATIC PROTOCOL -- sect_static_protos = m:section(TypedSection, "static", "Static options", "Configuration of the static protocols.") sect_static_protos.addremove = true sect_static_protos.anonymous = false -- Default kernel parameters disabled = sect_static_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.") disabled.default=0 -- Optional parameters for _,o in ipairs(protoptions) do if o.name ~= nil then for _, d in ipairs(o.depends) do if d == "static" then if o.name == "table" then value = sect_static_protos:option(ListValue, o.name, translate(o.name), translate(o.help)) uciout:foreach("bird4", "table", function (s) value:value(s.name) end) value:value("") else value = sect_static_protos:option(Value, o.name, translate(o.name), translate(o.help)) end value.optional = true value.rmempty = true end end end end -- -- ROUTES FOR STATIC PROTOCOL -- sect_routes = m:section(TypedSection, "route", "Routes configuration", "Configuration of the routes used in static protocols.") sect_routes.addremove = true sect_routes.anonymous = true instance = sect_routes:option(ListValue, "instance", "Route instance", "") i = 0 uciout:foreach("bird4", "static", function (s) instance:value(s[".name"]) end) prefix = sect_routes:option(Value, "prefix", "Route prefix", "") type = sect_routes:option(ListValue, "type", "Type of route", "") type:value("router") type:value("special") type:value("iface") type:value("recursive") type:value("multipath") valueVia = sect_routes:option(Value, "via", "Via", "") valueVia.optional = false valueVia:depends("type", "router") valueVia.datatype = "ip4addr" listVia = sect_routes:option(DynamicList, "l_via", "Via", "") listVia:depends("type", "multipath") listVia.optional=false listVia.datatype = "ip4addr" attribute = sect_routes:option(Value, "attribute", "Attribute", "Types are: unreachable, prohibit and blackhole") attribute:depends("type", "special") iface = sect_routes:option(ListValue, "iface", "Interface", "") iface:depends("type", "iface") uciout:foreach("wireless", "wifi-iface", function(section) iface:value(section[".name"]) end) ip = sect_routes:option(Value, "ip", "IP address", "") ip:depends("type", "ip") ip.datatype = [[ or"ip4addr", "ip6addr" ]] function m.on_commit(self,map) luci.sys.call('/etc/init.d/bird4 stop; /etc/init.d/bird4 start') end return m
gpl-2.0
emptyrivers/WeakAuras2
WeakAurasOptions/OptionsFrames/IconPicker.lua
1
7187
if not WeakAuras.IsCorrectVersion() then return end local AddonName, OptionsPrivate = ... -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, GetSpellInfo = CreateFrame, GetSpellInfo local AceGUI = LibStub("AceGUI-3.0") local AceConfigDialog = LibStub("AceConfigDialog-3.0") local WeakAuras = WeakAuras local L = WeakAuras.L local iconPicker local spellCache = WeakAuras.spellCache local function ConstructIconPicker(frame) local group = AceGUI:Create("InlineGroup"); group.frame:SetParent(frame); group.frame:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -17, 30); -- 12 group.frame:SetPoint("TOPLEFT", frame, "TOPLEFT", 17, -50); group.frame:Hide(); group:SetLayout("fill"); local scroll = AceGUI:Create("ScrollFrame"); scroll:SetLayout("flow"); scroll.frame:SetClipsChildren(true); group:AddChild(scroll); local function iconPickerFill(subname, doSort) scroll:ReleaseChildren(); local distances = {}; local names = {}; -- Work around special numbers such as inf and nan if (tonumber(subname)) then local spellId = tonumber(subname); if (abs(spellId) < math.huge and tostring(spellId) ~= "nan") then subname = GetSpellInfo(spellId) end end if subname then subname = subname:lower(); end local usedIcons = {}; local AddButton = function(name, icon) local button = AceGUI:Create("WeakAurasIconButton"); button:SetName(name); button:SetTexture(icon); button:SetClick(function() group:Pick(icon); end); scroll:AddChild(button); usedIcons[icon] = true; end local num = 0; if(subname and subname ~= "") then for name, icons in pairs(spellCache.Get()) do if(name:lower():find(subname, 1, true)) then if icons.spells then for spellId, icon in pairs(icons.spells) do if (not usedIcons[icon]) then AddButton(name, icon) num = num + 1; if(num >= 500) then break; end end end elseif icons.achievements then for _, icon in pairs(icons.achievements) do if (not usedIcons[icon]) then AddButton(name, icon) num = num + 1; if(num >= 500) then break; end end end end end if(num >= 500) then break; end end end end local input = CreateFrame("EDITBOX", nil, group.frame, "InputBoxTemplate"); input:SetScript("OnTextChanged", function(...) iconPickerFill(input:GetText(), false); end); input:SetScript("OnEnterPressed", function(...) iconPickerFill(input:GetText(), true); end); input:SetScript("OnEscapePressed", function(...) input:SetText(""); iconPickerFill(input:GetText(), true); end); input:SetWidth(170); input:SetHeight(15); input:SetPoint("BOTTOMRIGHT", group.frame, "TOPRIGHT", -12, -5); local inputLabel = input:CreateFontString(nil, "OVERLAY", "GameFontNormal"); inputLabel:SetText(L["Search"]); inputLabel:SetJustifyH("RIGHT"); inputLabel:SetPoint("BOTTOMLEFT", input, "TOPLEFT", 0, 5); local icon = AceGUI:Create("WeakAurasIconButton"); icon.frame:Disable(); icon.frame:SetParent(group.frame); icon.frame:SetPoint("BOTTOMLEFT", group.frame, "TOPLEFT", 15, -15); local iconLabel = input:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge"); iconLabel:SetNonSpaceWrap("true"); iconLabel:SetJustifyH("LEFT"); iconLabel:SetPoint("LEFT", icon.frame, "RIGHT", 5, 0); iconLabel:SetPoint("RIGHT", input, "LEFT", -50, 0); function group.Pick(self, texturePath) local valueToPath = OptionsPrivate.Private.ValueToPath if(not self.groupIcon and self.baseObject.controlledChildren) then for index, childId in pairs(self.baseObject.controlledChildren) do local childData = WeakAuras.GetData(childId); if(childData) then valueToPath(childData, self.paths[childId], texturePath) WeakAuras.Add(childData) WeakAuras.ClearAndUpdateOptions(childData.id) WeakAuras.UpdateThumbnail(childData); end end else valueToPath(self.baseObject, self.paths[self.baseObject.id], texturePath) WeakAuras.Add(self.baseObject) WeakAuras.ClearAndUpdateOptions(self.baseObject.id) WeakAuras.UpdateThumbnail(self.baseObject) end local success = icon:SetTexture(texturePath) and texturePath; if(success) then iconLabel:SetText(texturePath); else iconLabel:SetText(); end end function group.Open(self, baseObject, paths, groupIcon) local valueFromPath = OptionsPrivate.Private.ValueFromPath self.baseObject = baseObject self.paths = paths self.groupIcon = groupIcon if(not groupIcon and baseObject.controlledChildren) then self.givenPath = {}; for index, childId in pairs(baseObject.controlledChildren) do local childData = WeakAuras.GetData(childId); if(childData) then local value = valueFromPath(childData, paths[childId]) self.givenPath[childId] = value; end end else local value = valueFromPath(self.baseObject, paths[self.baseObject.id]) self.givenPath = value end -- group:Pick(self.givenPath); frame.window = "icon"; frame:UpdateFrameVisible() input:SetText(""); end function group.Close() frame.window = "default"; frame:UpdateFrameVisible() WeakAuras.FillOptions() end function group.CancelClose() local valueToPath = OptionsPrivate.Private.ValueToPath if(not group.groupIcon and group.baseObject.controlledChildren) then for index, childId in pairs(group.baseObject.controlledChildren) do local childData = WeakAuras.GetData(childId); if(childData) then if (group.givenPath[childId]) then valueToPath(childData, group.paths[childId], group.givenPath[childId]) WeakAuras.Add(childData); WeakAuras.ClearAndUpdateOptions(childData.id) WeakAuras.UpdateThumbnail(childData); end end end else valueToPath(group.baseObject, group.paths[group.baseObject.id], group.givenPath) WeakAuras.Add(group.baseObject) WeakAuras.ClearAndUpdateOptions(group.baseObject.id) WeakAuras.UpdateThumbnail(group.baseObject) end group.Close(); end local cancel = CreateFrame("Button", nil, group.frame, "UIPanelButtonTemplate"); cancel:SetScript("OnClick", group.CancelClose); cancel:SetPoint("bottomright", frame, "bottomright", -27, 11); cancel:SetHeight(20); cancel:SetWidth(100); cancel:SetText(L["Cancel"]); local close = CreateFrame("Button", nil, group.frame, "UIPanelButtonTemplate"); close:SetScript("OnClick", group.Close); close:SetPoint("RIGHT", cancel, "LEFT", -10, 0); close:SetHeight(20); close:SetWidth(100); close:SetText(L["Okay"]); return group end function OptionsPrivate.IconPicker(frame) iconPicker = iconPicker or ConstructIconPicker(frame) return iconPicker end
gpl-2.0
cjshmyr/OpenRA
mods/d2k/maps/ordos-02b/ordos02b.lua
2
2647
--[[ 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. ]] HarkonnenBase = { HConyard, HPower1, HPower2, HBarracks, HOutpost } HarkonnenReinforcements = { easy = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" } }, normal = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" } }, hard = { { "trike", "trike" }, { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } } HarkonnenAttackPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry1.Location, HarkonnenRally2.Location }, { HarkonnenEntry2.Location, HarkonnenRally2.Location }, { HarkonnenEntry2.Location, HarkonnenRally3.Location } } HarkonnenAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(20) } HarkonnenAttackWaves = { easy = 3, normal = 6, hard = 9 } Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillOrdos) end if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") player = Player.GetPlayer("Ordos") InitObjectives(player) KillOrdos = harkonnen.AddPrimaryObjective("Kill all Ordos units.") KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.") Camera.Position = OConyard.CenterPosition Trigger.OnAllKilled(HarkonnenBase, function() Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt) end) local path = function() return Utils.Random(HarkonnenAttackPaths) end SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty]) Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
samuelctabor/ardupilot
libraries/AP_Scripting/applets/Heli_IM_COL_Tune.lua
24
5180
-- This script is a useful tool when first setting up a heli. You can use it to dial in the IM_STB_COL_2 and -- IM_STAB_COL_3 parameters in a more intuative way. It is meant for use with a transmitter that has two pots -- available. 1 Pot can be used to control the gradient of the line between the 40% and 60% curve points. Use -- this pot to adjust the sensitivity of the collective about the collective midstick. The 2nd Pot then controls -- the value of the 50% point on the curve. This can be used to set the collective position to aid with hovering -- at the midstick. -- Tested and working as of 25th Aug 2020 (Copter Dev) function update() local rcin_50 = col50_val_ch:norm_input_ignore_trim() local rcin_grad = col_grad_ch:norm_input_ignore_trim() rcin_save = save_switch_ch:get_aux_switch_pos() -- Offset starting midstick curve value to get new value -- Max = +30% , Min = -30% local im_50 = (value_im_3 + value_im_2) * 0.5 --(%) local delta_50 = rcin_50*30 im_50 = im_50 + delta_50 -- Scale rcin_grad to be between 0 and 1 rcin_grad = (rcin_grad+1)*0.5 -- Calculate delta due to gradient local grad_40 = rcin_grad * -10 --(%) local grad_60 = rcin_grad * 10 --(%) -- Calculate param values local im_40_pct = im_50+grad_40 local im_60_pct = im_50+grad_60 -- Ensure IM_STB_COL_2 < IM_STB_COL_3 if im_40_pct >= im_60_pct then im_40_pct = im_60_pct - 1 end -- Ensure IM_STB_COL_2 and IM_STB_COL_3 are withing appropriate ranges im_40_pct = min_max(math.floor(im_40_pct),1,98) im_60_pct = min_max(math.floor(im_60_pct),2,99) -- Enforce that IM_STB_COL_1 < IM_STB_COL_2 local im_0_pct = get_im_val('IM_STB_COL_1',false) if im_0_pct >= im_40_pct then -- Correct within parameter limits im_0_pct = min_max(im_40_pct - 1,0,97) -- Set correct value to prevent pre-arm warnings set_save_param('IM_STB_COL_1',im_0_pct,false) end -- Enforce that IM_STB_COL_4 > IM_STB_COL_3 im_100_pct = get_im_val('IM_STB_COL_4',false) if im_100_pct <= im_60_pct then -- Correct within parameter limits im_100_pct = min_max(im_60_pct + 1,3,100) -- Set correct value to prevent pre-arm warnings set_save_param('IM_STB_COL_4',im_100_pct,false) end -- Save params only if switch active if rcin_save < 1 then -- just set 40% and 60% parameter values set_save_param('IM_STB_COL_2',im_40_pct,false) set_save_param('IM_STB_COL_3',im_60_pct,false) else set_save_param('IM_STB_COL_1',im_0_pct,true) set_save_param('IM_STB_COL_2',im_40_pct,true) set_save_param('IM_STB_COL_3',im_60_pct,true) set_save_param('IM_STB_COL_4',im_100_pct,true) -- Set script exit condition script_status = COMPLETE end -- Reschedule foo, sched = script_cont_stop() return foo, sched end -- Get parameter value and perform checks to ensure successful function get_im_val(param_name,disp) local value = -1 value = param:get(param_name) if value >= 0 then if disp then gcs:send_text(3, string.format('LUA: %s = %i',param_name,value)) end else gcs:send_text(3, string.format('LUA: Failed get %s',param_name)) script_status = false end return value end -- Prevent parameters from being set out of range function min_max(value,min,max) if value < min then value = min end if value > max then value = max end return value end -- Standardised function for stopping or continuing function script_cont_stop() if script_status == HEALTHY then return update, 500 elseif script_status == COMPLETE then gcs:send_text(2, 'LUA: IM_COL tune complete') elseif script_status == NORC then gcs:send_text(2, 'LUA: RC channels not set') else --FAULT gcs:send_text(2, 'LUA: IM_COL setter stopped') end end -- function for setting and saving parameter function set_save_param(str,val,save) if save then -- Set and save if param:set_and_save(str,val) then gcs:send_text(2, 'LUA: params saved') else gcs:send_text(2, 'LUA: param set failed') end else -- Just set if not(param:set(str,val)) then gcs:send_text(2, 'LUA: param set failed') end end end --- -- -- Initial Setup --- --- --- -- Script status levels FAULT = 0 NORC = 1 HEALTHY = 2 COMPLETE = 3 script_status = HEALTHY -- Set RC channels to use to control im_stb_col params col50_val_ch = rc:find_channel_for_option(300) --scripting ch 1 col_grad_ch = rc:find_channel_for_option(301) --scripting ch 2 save_switch_ch = rc:find_channel_for_option(302) --scripting ch 3 if (col50_val_ch == nil or col_grad_ch == nil or save_switch_ch == nil) then script_status = NORC end -- Get im_stb_col parameter values and store value_im_2 = get_im_val('IM_STB_COL_2',true) value_im_3 = get_im_val('IM_STB_COL_3',true) -- Only continue running script if healthy foo, sched = script_cont_stop() return foo, sched
gpl-3.0
akowal/dotfiles
homedir/hammerspoon/init.lua
1
2491
hs.window.animationDuration = 0 local TRIGGER_RESIZE = {"cmd", "ctrl"} local TRIGGER_MOVE = {"cmd", "ctrl", "alt"} hs.hotkey.bind(TRIGGER_RESIZE, "c", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x f.y = screen.y f.w = screen.w f.h = screen.h win:setFrame(f) end) hs.hotkey.bind(TRIGGER_RESIZE, "r", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x + screen.w/4 f.y = screen.y f.w = screen.w - screen.w/2 f.h = screen.h win:setFrame(f) end) hs.hotkey.bind(TRIGGER_MOVE, "c", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x + screen.w / 6 f.y = screen.y + screen.h / 6 f.w = screen.w - screen.w / 3 f.h = screen.h - screen.h / 3 win:setFrame(f) end) hs.hotkey.bind(TRIGGER_RESIZE, "Left", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x f.y = screen.y f.w = screen.w / 2 f.h = screen.h win:setFrame(f) end) hs.hotkey.bind(TRIGGER_RESIZE, "Right", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x + screen.w / 2 f.y = screen.y f.w = screen.w / 2 f.h = screen.h win:setFrame(f) end) hs.hotkey.bind(TRIGGER_RESIZE, "Up", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x f.y = screen.y f.w = screen.w f.h = screen.h / 2 win:setFrame(f) end) hs.hotkey.bind(TRIGGER_RESIZE, "Down", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen():frame() win:setFullscreen(false) f.x = screen.x f.y = screen.y + screen.h / 2 f.w = screen.w f.h = screen.h / 2 win:setFrame(f) end) hs.hotkey.bind(TRIGGER_MOVE, "Left", function() local win = hs.window.focusedWindow() win:setFullscreen(false) win:moveOneScreenWest(false, true) end) hs.hotkey.bind(TRIGGER_MOVE, "Right", function() local win = hs.window.focusedWindow() win:setFullscreen(false) win:moveOneScreenEast(false, true) end)
mit
Godfather021/best
plugins/moderation.lua
1
11161
do local function check_member(extra, success, result) local data = extra.data for k,v in pairs(result.members) do if v.id ~= our_id then data[tostring(extra.msg.to.id)] = { moderators = {[tostring(v.id)] = v.username}, settings = { set_name = string.gsub(extra.msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'yes', lock_photo = 'no', lock_member = 'no', anti_flood = 'ban', welcome = 'group', sticker = 'ok', } } save_data(_config.moderation.data, data) return send_large_msg(get_receiver(extra.msg), '') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then chat_info(get_receiver(msg), check_member,{data=data, msg=msg}) else if data[tostring(msg.to.id)] then return '' end local username = msg.from.username or msg.from.print_name -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'yes', lock_photo = 'no', lock_member = 'no', anti_flood = 'ban', welcome = 'group', sticker = 'ok', } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'group id added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' This user is already admin') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' admin added') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' you are not admin!') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' admin has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' user is admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' user has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' You are not admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'admin '..member_username..' has been demoted.') end local function username_id(extra, success, result) for k,v in pairs(result.members) do if v.username == extra.username then if extra.mod_cmd == 'promote' then return promote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'demote' then return demote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'adminprom' then return admin_promote(extra.receiver, '@'..extra.username, v.id) elseif extra.mod_cmd == 'admindem' then return admin_demote(extra.receiver, '@'..extra.username, v.id) end end end send_large_msg(extra.receiver, 'No user '..extra.username..' in this group.') end local function action_by_id(extra, success, result) if success == 1 then for k,v in pairs(result.members) do if extra.matches[2] == tostring(v.id) then if extra.matches[1] == 'promote' then return promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'demote' then return demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'adminprom' then return admin_promote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) elseif extra.matches[1] == 'admindem' then return admin_demote('chat#id'..result.id, 'user#id'..extra.matches[2], tostring(v.id)) end end end send_large_msg('chat#id'..result.id, 'No user user#id'..extra.matches[2]..' in this group.') end end local function action_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' and not is_sudo(msg) then if extra.msg.text == '!promote' then return promote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!demote' then return demote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!adminprom' then return admin_promote(get_receiver(msg), member_username, member_id) elseif extra.msg.text == '!admindem' then return admin_demote(get_receiver(msg), member_username, member_id) end else return 'Use This in Your Groups.' end end function run(msg, matches) local receiver = get_receiver(msg) if is_chat_msg(msg) then if is_momod(msg) then if matches[1] == 'promote' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then chat_info(receiver, action_by_id, {msg=msg, matches=matches}) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'demote' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then demote(receiver, 'user_'..matches[2], matches[2]) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') if username == msg.from.username then return 'لا يمكنك ازالة نفسك' else chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end end elseif matches[1] == 'modlist' then local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'you are not admin.' end local message = 'group admin' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end end if is_admin(msg) then if matches[1] == 'adminprom' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then chat_info(receiver, action_by_id, {msg=msg, matches=matches}) elseif matches[2] and string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'admindem' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if matches[2] then if string.match(matches[2], '^%d+$') then admin_demote(receiver, 'user_'..matches[2], matches[2]) elseif string.match(matches[2], '^@.+$') then local username = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {mod_cmd=matches[1], receiver=receiver, username=username}) end end elseif matches[1] == 'adminlist' then local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'user has been promoted as admin.' end for k,v in pairs(data['admins']) do message = 'bot admins\n'..'- '..v..' ['..k..'] \n' end return message end end else return 'Only works on group' end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) elseif matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { patterns = { '^[!/](admindem) (%d+)$', '^[!/](admindem) (.*)$', '^[!/](admindem)$', '^[!/](adminlist)$', '^[!/](adminprom) (%d+)$', '^[!/](adminprom) (.*)$', '^[!/](adminprom)$', '^[!/](demote) (.*)$', '^[!/](demote)$', '^[!/](modlist)$', '^[!/](promote) (.*)$', '^[!/](promote)$', '^[!/](promote) (%d+)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_created)$' }, run = run } end
gpl-2.0
Eugene-Ye/fanclub
app/libs/uuid/uuid.lua
2
1873
local ffi = require "ffi" local ffi_new = ffi.new local ffi_str = ffi.string local ffi_load = ffi.load local ffi_cdef = ffi.cdef local C = ffi.C local os = ffi.os local tonumber = tonumber local setmetatable = setmetatable ffi_cdef[[ typedef unsigned char uuid_t[16]; typedef long time_t; typedef struct timeval { time_t tv_sec; time_t tv_usec; } timeval; void uuid_generate(uuid_t out); void uuid_generate_random(uuid_t out); void uuid_generate_time(uuid_t out); int uuid_generate_time_safe(uuid_t out); int uuid_parse(const char *in, uuid_t uu); void uuid_unparse(const uuid_t uu, char *out); int uuid_type(const uuid_t uu); int uuid_variant(const uuid_t uu); time_t uuid_time(const uuid_t uu, struct timeval *ret_tv); ]] local lib = os == "OSX" and C or ffi_load "uuid" local uid = ffi_new "uuid_t" local tvl = ffi_new "timeval" local buf = ffi_new("char[?]", 36) local uuid = {} local mt = {} local function unparse(id) lib.uuid_unparse(id, buf) return ffi_str(buf, 36) end local function parse(id) return lib.uuid_parse(id, uid) == 0 and uid or nil end function uuid.generate() lib.uuid_generate(uid) return unparse(uid) end function uuid.generate_random() lib.uuid_generate_random(uid) return unparse(uid) end function uuid.generate_time() lib.uuid_generate_time(uid) return unparse(uid) end function uuid.generate_time_safe() local safe = lib.uuid_generate_time_safe(uid) == 0 return unparse(uid), safe end function uuid.type(id) return lib.uuid_type(parse(id)) end function uuid.variant(id) return lib.uuid_variant(parse(id)) end function uuid.time(id) local secs = lib.uuid_time(parse(id), tvl) return tonumber(secs), tonumber(tvl.tv_usec) end mt.__call = uuid.generate return setmetatable(uuid, mt)
mit
lcheylus/haka
modules/protocol/http/test/request-modif.lua
3
1137
-- 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 http = require("protocol/http") http.install_tcp_rule(80) haka.rule { hook = http.events.request, eval = function (http, request) print("HTTP REQUEST") debug.pprint(request, nil, nil, { debug.hide_underscore, debug.hide_function }) -- We change a part of the request request.version = "2.0" -- We change an existing header request.headers["Host"] = "haka.powered.tld" -- We destroy one request.headers["User-Agent"] = nil -- We create a new one request.headers["Haka"] = "Done" -- We create a new one and we remove it request.headers["Haka2"] = "Done" request.headers["Haka2"] = nil print("HTTP MODIFIED REQUEST") debug.pprint(request, nil, nil, { debug.hide_underscore, debug.hide_function }) end } haka.rule { hook = http.events.response, eval = function (http, response) print("HTTP RESPONSE") debug.pprint(response, nil, nil, { debug.hide_underscore, debug.hide_function }) end }
mpl-2.0
ImagicTheCat/vRP
vrp/modules/audio.lua
1
2980
-- https://github.com/ImagicTheCat/vRP -- MIT license (see LICENSE or vrp/vRPShared.lua) if not vRP.modules.audio then return end local Audio = class("Audio", vRP.Extension) local lang = vRP.lang -- PRIVATE METHODS -- menu: admin local function menu_admin(self) local function m_audiosource(menu) local user = menu.user local infos = splitString(user:prompt(lang.admin.custom_audiosource.prompt(), ""), "=") local name = infos[1] local url = infos[2] if name and string.len(name) > 0 then if url and string.len(url) > 0 then local x,y,z = vRP.EXT.Base.remote.getPosition(user.source) vRP.EXT.Audio.remote._setAudioSource(-1,"vRP:admin:"..name,url,0.5,x,y,z,125) else vRP.EXT.Audio.remote._removeAudioSource(-1,"vRP:admin:"..name) end end end vRP.EXT.GUI:registerMenuBuilder("admin", function(menu) local user = menu.user if user:hasPermission("player.custom_sound") then menu:addOption(lang.admin.custom_audiosource.title(), m_audiosource) end end) end -- METHODS function Audio:__construct() vRP.Extension.__construct(self) self.cfg = module("vrp", "cfg/audio") self.reg_channels = {} -- map of id => config self:registerVoiceChannel("world", self.cfg.world_voice) end -- register VoIP channel -- all channels should be registered before any player joins the server -- -- id: channel name/id (string) -- config: --- effects: map of name => true/options ---- spatialization => { max_dist: ..., rolloff: ..., dist_model: ..., ref_dist: ...} (per peer effect) ---- biquad => { frequency: ..., Q: ..., type: ..., detune: ..., gain: ...} see WebAudioAPI BiquadFilter ----- freq = 1700, Q = 3, type = "bandpass" (idea for radio effect) ---- gain => { gain: ... } function Audio:registerVoiceChannel(id, config) if not self.reg_channels[id] then self.reg_channels[id] = config else self:error("voice channel \""..id.."\" already registered") end end -- build channels if not built, return map of name => id -- return map of id => {index, config} function Audio:getChannels() if not self.channels then self.channels = {} local list = {} for id, config in pairs(self.reg_channels) do table.insert(list, {id, config}) end table.sort(list, function(a,b) return a[1] < b[1] end) for idx, el in ipairs(list) do self.channels[el[1]] = {idx, el[2]} end end return self.channels end -- EVENT Audio.event = {} function Audio.event:playerSpawn(user, first_spawn) if first_spawn then -- connect VoIP self.remote._configureVoIP(user.source, {bitrate = self.cfg.voip_bitrate, frame_size = self.cfg.voip_frame_size, server = self.cfg.voip_server, channels = self:getChannels(), id = user.source}, self.cfg.vrp_voip, self.cfg.voip_interval, self.cfg.voip_proximity) end end function Audio.event:extensionLoad(ext) if ext == vRP.EXT.Admin then menu_admin(self) end end vRP:registerExtension(Audio)
mit
emptyrivers/WeakAuras2
WeakAuras/RegionTypes/RegionPrototype.lua
1
26130
if not WeakAuras.IsCorrectVersion() then return end local AddonName, Private = ... local WeakAuras = WeakAuras; local L = WeakAuras.L; local GetAtlasInfo = WeakAuras.IsClassic() and GetAtlasInfo or C_Texture.GetAtlasInfo WeakAuras.regionPrototype = {}; local SubRegionEventSystem = { ClearSubscribers = function(self) self.events = {} end, AddSubscriber = function(self, event, subRegion) if not subRegion[event] then print("Can't register subregion for ", event, " ", subRegion.type) return end self.events[event] = self.events[event] or {} tinsert(self.events[event], subRegion) end, RemoveSubscriber = function(self, event, subRegion) tremove(self.events[event], tIndexOf(self.events[event], subRegion)) end, Notify = function(self, event, ...) if self.events[event] then for _, subRegion in ipairs(self.events[event]) do subRegion[event](subRegion, ...) end end end } local function CreateSubRegionEventSystem() local system = {} for f, func in pairs(SubRegionEventSystem) do system[f] = func system.events = {} end return system end -- Alpha function WeakAuras.regionPrototype.AddAlphaToDefault(default) default.alpha = 1.0; end -- Adjusted Duration function WeakAuras.regionPrototype.AddAdjustedDurationToDefault(default) default.useAdjustededMax = false; default.useAdjustededMin = false; end function WeakAuras.regionPrototype.AddAdjustedDurationOptions(options, data, order) options.useAdjustededMin = { type = "toggle", width = WeakAuras.normalWidth, name = L["Set Minimum Progress"], desc = L["Values/Remaining Time below this value are displayed as no progress."], order = order }; options.adjustedMin = { type = "input", validate = WeakAuras.ValidateNumericOrPercent, width = WeakAuras.normalWidth, order = order + 0.01, name = L["Minimum"], hidden = function() return not data.useAdjustededMin end, desc = L["Enter static or relative values with %"] }; options.useAdjustedMinSpacer = { type = "description", width = WeakAuras.normalWidth, name = "", order = order + 0.02, hidden = function() return not (not data.useAdjustededMin and data.useAdjustededMax) end, }; options.useAdjustededMax = { type = "toggle", width = WeakAuras.normalWidth, name = L["Set Maximum Progress"], desc = L["Values/Remaining Time above this value are displayed as full progress."], order = order + 0.03 }; options.adjustedMax = { type = "input", width = WeakAuras.normalWidth, validate = WeakAuras.ValidateNumericOrPercent, order = order + 0.04, name = L["Maximum"], hidden = function() return not data.useAdjustededMax end, desc = L["Enter static or relative values with %"] }; options.useAdjustedMaxSpacer = { type = "description", width = WeakAuras.normalWidth, name = "", order = order + 0.05, hidden = function() return not (data.useAdjustededMin and not data.useAdjustededMax) end, }; return options; end local screenWidth, screenHeight = math.ceil(GetScreenWidth() / 20) * 20, math.ceil(GetScreenHeight() / 20) * 20; function Private.GetAnchorsForData(parentData, type) local result if not parentData.controlledChildren then if not WeakAuras.regionOptions[parentData.regionType] or not WeakAuras.regionOptions[parentData.regionType].getAnchors then return end local anchors = WeakAuras.regionOptions[parentData.regionType].getAnchors(parentData) for anchorId, anchorData in pairs(anchors) do if anchorData.type == type then result = result or {} result[anchorId] = anchorData.display end end end return result end function WeakAuras.regionPrototype:AnchorSubRegion(subRegion, anchorType, selfPoint, anchorPoint, anchorXOffset, anchorYOffset) subRegion:ClearAllPoints() if anchorType == "point" then local xOffset = anchorXOffset or 0 local yOffset = anchorYOffset or 0 subRegion:SetPoint(Private.point_types[selfPoint] and selfPoint or "CENTER", self, Private.point_types[anchorPoint] and anchorPoint or "CENTER", xOffset, yOffset) else anchorXOffset = anchorXOffset or 0 anchorYOffset = anchorYOffset or 0 subRegion:SetPoint("bottomleft", self, "bottomleft", -anchorXOffset, -anchorYOffset) subRegion:SetPoint("topright", self, "topright", anchorXOffset, anchorYOffset) end end -- Sound / Chat Message / Custom Code function WeakAuras.regionPrototype.AddProperties(properties, defaultsForRegion) properties["sound"] = { display = L["Sound"], action = "SoundPlay", type = "sound", }; properties["chat"] = { display = L["Chat Message"], action = "SendChat", type = "chat", }; properties["customcode"] = { display = L["Run Custom Code"], action = "RunCode", type = "customcode" } properties["xOffsetRelative"] = { display = L["Relative X-Offset"], setter = "SetXOffsetRelative", type = "number", softMin = -screenWidth, softMax = screenWidth, bigStep = 1 } properties["yOffsetRelative"] = { display = L["Relative Y-Offset"], setter = "SetYOffsetRelative", type = "number", softMin = -screenHeight, softMax = screenHeight, bigStep = 1 } properties["glowexternal"] = { display = L["Glow External Element"], action = "GlowExternal", type = "glowexternal" } if (defaultsForRegion and defaultsForRegion.alpha) then properties["alpha"] = { display = L["Alpha"], setter = "SetRegionAlpha", type = "number", min = 0, max = 1, bigStep = 0.01, isPercent = true } end end local function SoundRepeatStop(self) Private.StartProfileSystem("sound"); if (self.soundRepeatTimer) then WeakAuras.timer:CancelTimer(self.soundRepeatTimer); self.soundRepeatTimer = nil; end Private.StopProfileSystem("sound"); end local function SoundStop(self) Private.StartProfileSystem("sound"); if (self.soundHandle) then StopSound(self.soundHandle); end Private.StopProfileSystem("sound"); end local function SoundPlayHelper(self) Private.StartProfileSystem("sound"); local options = self.soundOptions; self.soundHandle = nil; if (not options or options.sound_type == "Stop") then Private.StopProfileSystem("sound"); return; end if (WeakAuras.IsOptionsOpen() or Private.SquelchingActions() or WeakAuras.InLoadingScreen()) then Private.StopProfileSystem("sound"); return; end if (options.sound == " custom") then if (options.sound_path) then local ok, _, handle = pcall(PlaySoundFile, options.sound_path, options.sound_channel or "Master"); if ok then self.soundHandle = handle; end end elseif (options.sound == " KitID") then if (options.sound_kit_id) then local ok, _, handle = pcall(PlaySound,options.sound_kit_id, options.sound_channel or "Master"); if ok then self.soundHandle = handle; end end else local ok, _, handle = pcall(PlaySoundFile, options.sound, options.sound_channel or "Master"); if ok then self.soundHandle = handle; end end Private.StopProfileSystem("sound"); end local function SoundPlay(self, options) if (not options or WeakAuras.IsOptionsOpen()) then return end Private.StartProfileSystem("sound"); self:SoundStop(); self:SoundRepeatStop(); self.soundOptions = options; SoundPlayHelper(self); local loop = options.do_loop or options.sound_type == "Loop"; if (loop and options.sound_repeat and options.sound_repeat < Private.maxTimerDuration) then self.soundRepeatTimer = WeakAuras.timer:ScheduleRepeatingTimer(SoundPlayHelper, options.sound_repeat, self); end Private.StopProfileSystem("sound"); end local function SendChat(self, options) if (not options or WeakAuras.IsOptionsOpen()) then return end Private.HandleChatAction(options.message_type, options.message, options.message_dest, options.message_channel, options.r, options.g, options.b, self, options.message_custom, nil, options.message_formaters); end local function RunCode(self, func) if func and not WeakAuras.IsOptionsOpen() then Private.ActivateAuraEnvironment(self.id, self.cloneId, self.state, self.states); xpcall(func, geterrorhandler()); Private.ActivateAuraEnvironment(nil); end end local function GlowExternal(self, options) if (not options or WeakAuras.IsOptionsOpen()) then return end Private.HandleGlowAction(options, self) end local function UpdatePosition(self) if (not self.anchorPoint or not self.relativeTo or not self.relativePoint) then return; end local xOffset = self.xOffset + (self.xOffsetAnim or 0) + (self.xOffsetRelative or 0) local yOffset = self.yOffset + (self.yOffsetAnim or 0) + (self.yOffsetRelative or 0) self:RealClearAllPoints(); xpcall(self.SetPoint, geterrorhandler(), self, self.anchorPoint, self.relativeTo, self.relativePoint, xOffset, yOffset); end local function ResetPosition(self) self.anchorPoint = nil; self.relativeTo = nil; self.relativePoint = nil; end local function SetAnchor(self, anchorPoint, relativeTo, relativePoint) if self.anchorPoint == anchorPoint and self.relativeTo == relativeTo and self.relativePoint == relativePoint then return end self.anchorPoint = anchorPoint; self.relativeTo = relativeTo; self.relativePoint = relativePoint; UpdatePosition(self); end local function SetOffset(self, xOffset, yOffset) if (self.xOffset == xOffset and self.yOffset == yOffset) then return; end self.xOffset = xOffset; self.yOffset = yOffset; UpdatePosition(self); end local function SetXOffset(self, xOffset) self:SetOffset(xOffset, self:GetYOffset()); end local function SetYOffset(self, yOffset) self:SetOffset(self:GetXOffset(), yOffset); end local function GetXOffset(self) return self.xOffset; end local function GetYOffset(self) return self.yOffset; end local function SetOffsetRelative(self, xOffsetRelative, yOffsetRelative) if (self.xOffsetRelative == xOffsetRelative and self.yOffsetRelative == yOffsetRelative) then return end self.xOffsetRelative = xOffsetRelative self.yOffsetRelative = yOffsetRelative UpdatePosition(self) end local function SetXOffsetRelative(self, xOffsetRelative) self:SetOffsetRelative(xOffsetRelative, self:GetYOffsetRelative()) end local function SetYOffsetRelative(self, yOffsetRelative) self:SetOffsetRelative(self:GetXOffsetRelative(), yOffsetRelative) end local function GetXOffsetRelative(self) return self.xOffsetRelative end local function GetYOffsetRelative(self) return self.yOffsetRelative end local function SetOffsetAnim(self, xOffset, yOffset) if (self.xOffsetAnim == xOffset and self.yOffsetAnim == yOffset) then return; end self.xOffsetAnim = xOffset; self.yOffsetAnim = yOffset; UpdatePosition(self); end local function SetRegionAlpha(self, alpha) if (self.alpha == alpha) then return; end self.alpha = alpha; self:SetAlpha(self.animAlpha or self.alpha or 1); self.subRegionEvents:Notify("AlphaChanged") end local function GetRegionAlpha(self) return self.animAlpha or self.alpha or 1; end local function SetAnimAlpha(self, alpha) if (self.animAlpha == alpha) then return; end self.animAlpha = alpha; if (WeakAuras.IsOptionsOpen()) then self:SetAlpha(max(self.animAlpha or self.alpha or 1, 0.5)); else self:SetAlpha(self.animAlpha or self.alpha or 1); end self.subRegionEvents:Notify("AlphaChanged") end local function SetTriggerProvidesTimer(self, timerTick) self.triggerProvidesTimer = timerTick self:UpdateTimerTick() end local function UpdateRegionHasTimerTick(self) local hasTimerTick = false if self.TimerTick then hasTimerTick = true elseif (self.subRegions) then for index, subRegion in pairs(self.subRegions) do if subRegion.TimerTick then hasTimerTick = true break; end end end self.regionHasTimer = hasTimerTick self:UpdateTimerTick() end local function TimerTickForRegion(region) Private.StartProfileSystem("timer tick") Private.StartProfileAura(region.id); if region.TimerTick then region:TimerTick(); end region.subRegionEvents:Notify("TimerTick") Private.StopProfileAura(region.id); Private.StopProfileSystem("timer tick") end local function UpdateTimerTick(self) if self.triggerProvidesTimer and self.regionHasTimer then if not self:GetScript("OnUpdate") then self:SetScript("OnUpdate", function() TimerTickForRegion(self) end); end else if self:GetScript("OnUpdate") then self:SetScript("OnUpdate", nil); end end end function WeakAuras.regionPrototype.create(region) region.SoundPlay = SoundPlay; region.SoundStop = SoundStop; region.SoundRepeatStop = SoundRepeatStop; region.SendChat = SendChat; region.RunCode = RunCode; region.GlowExternal = GlowExternal; region.SetAnchor = SetAnchor; region.SetOffset = SetOffset; region.SetXOffset = SetXOffset; region.SetYOffset = SetYOffset; region.GetXOffset = GetXOffset; region.GetYOffset = GetYOffset; region.SetOffsetRelative = SetOffsetRelative region.SetXOffsetRelative = SetXOffsetRelative region.SetYOffsetRelative = SetYOffsetRelative region.GetXOffsetRelative = GetXOffsetRelative region.GetYOffsetRelative = GetYOffsetRelative region.SetOffsetAnim = SetOffsetAnim; region.ResetPosition = ResetPosition; region.RealClearAllPoints = region.ClearAllPoints; region.ClearAllPoints = function() region:RealClearAllPoints(); region:ResetPosition(); end region.SetRegionAlpha = SetRegionAlpha; region.GetRegionAlpha = GetRegionAlpha; region.SetAnimAlpha = SetAnimAlpha; region.SetTriggerProvidesTimer = SetTriggerProvidesTimer region.UpdateRegionHasTimerTick = UpdateRegionHasTimerTick region.UpdateTimerTick = UpdateTimerTick region.subRegionEvents = CreateSubRegionEventSystem() region:SetPoint("CENTER", UIParent, "CENTER") end -- SetDurationInfo function WeakAuras.regionPrototype.modify(parent, region, data) region.subRegionEvents:ClearSubscribers() local defaultsForRegion = WeakAuras.regionTypes[data.regionType] and WeakAuras.regionTypes[data.regionType].default; if (defaultsForRegion and defaultsForRegion.alpha) then region:SetRegionAlpha(data.alpha); end if region.SetRegionAlpha then region:SetRegionAlpha(data.alpha) end local hasAdjustedMin = defaultsForRegion and defaultsForRegion.useAdjustededMin ~= nil and data.useAdjustededMin and data.adjustedMin; local hasAdjustedMax = defaultsForRegion and defaultsForRegion.useAdjustededMax ~= nil and data.useAdjustededMax and data.adjustedMax; region.adjustedMin = nil region.adjustedMinRel = nil region.adjustedMinRelPercent = nil region.adjustedMax = nil region.adjustedMaxRel = nil region.adjustedMaxRelPercent = nil if (hasAdjustedMin) then local percent = string.match(data.adjustedMin, "(%d+)%%") if percent then region.adjustedMinRelPercent = tonumber(percent) / 100 else region.adjustedMin = tonumber(data.adjustedMin); end end if (hasAdjustedMax) then local percent = string.match(data.adjustedMax, "(%d+)%%") if percent then region.adjustedMaxRelPercent = tonumber(percent) / 100 else region.adjustedMax = tonumber(data.adjustedMax) end end region:SetOffset(data.xOffset or 0, data.yOffset or 0); region:SetOffsetRelative(0, 0) region:SetOffsetAnim(0, 0); if data.anchorFrameType == "CUSTOM" and data.customAnchor then region.customAnchorFunc = WeakAuras.LoadFunction("return " .. data.customAnchor, data.id, "custom anchor") else region.customAnchorFunc = nil end if not parent or parent.regionType ~= "dynamicgroup" then if -- Don't anchor single Auras that with custom anchoring, -- these will be anchored in expand not ( data.anchorFrameType == "CUSTOM" or data.anchorFrameType == "UNITFRAME" or data.anchorFrameType == "NAMEPLATE" ) -- Group Auras that will never be expanded, so those need -- to be always anchored here or data.regionType == "dynamicgroup" or data.regionType == "group" then Private.AnchorFrame(data, region, parent); end end region.startFormatters = Private.CreateFormatters(data.actions.start.message, function(key, default) local fullKey = "message_format_" .. key if data.actions.start[fullKey] == nil then data.actions.start[fullKey] = default end return data.actions.start[fullKey] end) region.finishFormatters = Private.CreateFormatters(data.actions.finish.message, function(key, default) local fullKey = "message_format_" .. key if data.actions.finish[fullKey] == nil then data.actions.finish[fullKey] = default end return data.actions.finish[fullKey] end) end function WeakAuras.regionPrototype.modifyFinish(parent, region, data) -- Sync subRegions if region.subRegions then for index, subRegion in pairs(region.subRegions) do Private.subRegionTypes[subRegion.type].release(subRegion) end wipe(region.subRegions) end if data.subRegions then region.subRegions = region.subRegions or {} local subRegionTypes = {} for index, subRegionData in pairs(data.subRegions) do if Private.subRegionTypes[subRegionData.type] then local subRegion = Private.subRegionTypes[subRegionData.type].acquire() subRegion.type = subRegionData.type if subRegion then Private.subRegionTypes[subRegionData.type].modify(region, subRegion, data, subRegionData, not subRegionTypes[subRegionData.type]) subRegionTypes[subRegionData.type] = true end tinsert(region.subRegions, subRegion) end end end region:UpdateRegionHasTimerTick() Private.ApplyFrameLevel(region) end local function SetProgressValue(region, value, total) local adjustMin = region.adjustedMin or 0; local max = region.adjustedMax or total; region:SetValue(value - adjustMin, max - adjustMin); end local regionsForFrameTick = {} local frameForFrameTick = CreateFrame("FRAME"); WeakAuras.frames["Frame Tick Frame"] = frameForFrameTick local function FrameTick() if WeakAuras.IsOptionsOpen() then return end Private.StartProfileSystem("frame tick") for region in pairs(regionsForFrameTick) do Private.StartProfileAura(region.id); if region.FrameTick then region.FrameTick() end region.subRegionEvents:Notify("FrameTick") Private.StopProfileAura(region.id); end Private.StopProfileSystem("frame tick") end local function RegisterForFrameTick(region) -- Check for a Frame Tick function local hasFrameTick = region.FrameTick if not hasFrameTick then if (region.subRegions) then for index, subRegion in pairs(region.subRegions) do if subRegion.FrameTick then hasFrameTick = true break end end end end if not hasFrameTick then return end regionsForFrameTick[region] = true if not frameForFrameTick:GetScript("OnUpdate") then frameForFrameTick:SetScript("OnUpdate", FrameTick); end end local function UnRegisterForFrameTick(region) regionsForFrameTick[region] = nil if not next(regionsForFrameTick) then frameForFrameTick:SetScript("OnUpdate", nil) end end local function TimerTickForSetDuration(self) local duration = self.duration local adjustMin = self.adjustedMin or 0; local max if duration == 0 then max = 0 elseif self.adjustedMax then max = self.adjustedMax else max = duration end self:SetTime(max - adjustMin, self.expirationTime - adjustMin, self.inverse); end function WeakAuras.regionPrototype.AddSetDurationInfo(region) if (region.SetValue and region.SetTime) then region.generatedSetDurationInfo = true; -- WeakAuras no longer calls SetDurationInfo, but some people do that, -- In that case we also need to overwrite TimerTick region.SetDurationInfo = function(self, duration, expirationTime, customValue, inverse) self.duration = duration or 0 self.expirationTime = expirationTime; self.inverse = inverse; if customValue then SetProgressValue(region, duration, expirationTime); region.TimerTick = nil region:UpdateRegionHasTimerTick() else local adjustMin = region.adjustedMin or 0; region:SetTime((duration ~= 0 and region.adjustedMax or duration) - adjustMin, expirationTime - adjustMin, inverse); region.TimerTick = TimerTickForSetDuration region:UpdateRegionHasTimerTick() end end elseif (region.generatedSetDurationInfo) then region.generatedSetDurationInfo = nil; region.SetDurationInfo = nil; end end -- Expand/Collapse function function WeakAuras.regionPrototype.AddExpandFunction(data, region, cloneId, parent, parentRegionType) local uid = data.uid local id = data.id local inDynamicGroup = parentRegionType == "dynamicgroup"; local inGroup = parentRegionType == "group"; local startMainAnimation = function() Private.Animate("display", uid, "main", data.animation.main, region, false, nil, true, cloneId); end function region:OptionsClosed() region:EnableMouse(false) region:SetScript("OnMouseDown", nil) end function region:ClickToPick() region:EnableMouse(true) region:SetScript("OnMouseDown", function() WeakAuras.PickDisplay(region.id, nil, true) end) if region.GetFrameStrata and region:GetFrameStrata() == "TOOLTIP" then region:SetFrameStrata("HIGH") end end local hideRegion; if(inDynamicGroup) then hideRegion = function() if region.PreHide then region:PreHide() end Private.RunConditions(region, uid, true) region.subRegionEvents:Notify("PreHide") region:Hide(); if (cloneId) then Private.ReleaseClone(region.id, cloneId, data.regionType); parent:RemoveChild(id, cloneId) else parent:DeactivateChild(id, cloneId); end end else hideRegion = function() if region.PreHide then region:PreHide() end Private.RunConditions(region, uid, true) region.subRegionEvents:Notify("PreHide") region:Hide(); if (cloneId) then Private.ReleaseClone(region.id, cloneId, data.regionType); end end end if(inDynamicGroup) then function region:Collapse() if (not region.toShow) then return; end region.toShow = false; region:SetScript("OnUpdate", nil) Private.PerformActions(data, "finish", region); if (not Private.Animate("display", data.uid, "finish", data.animation.finish, region, false, hideRegion, nil, cloneId)) then hideRegion(); end if (region.SoundRepeatStop) then region:SoundRepeatStop(); end UnRegisterForFrameTick(region) end function region:Expand() if (region.toShow) then return; end region.toShow = true; if(region.PreShow) then region:PreShow(); end region.subRegionEvents:Notify("PreShow") region.justCreated = nil; Private.ApplyFrameLevel(region) region:Show(); Private.PerformActions(data, "start", region); if not(Private.Animate("display", data.uid, "start", data.animation.start, region, true, startMainAnimation, nil, cloneId)) then startMainAnimation(); end parent:ActivateChild(data.id, cloneId); RegisterForFrameTick(region) region:UpdateTimerTick() end elseif not(data.controlledChildren) then function region:Collapse() if (not region.toShow) then return; end region.toShow = false; region:SetScript("OnUpdate", nil) Private.PerformActions(data, "finish", region); if (not Private.Animate("display", data.uid, "finish", data.animation.finish, region, false, hideRegion, nil, cloneId)) then hideRegion(); end if inGroup then parent:UpdateBorder(region); end if (region.SoundRepeatStop) then region:SoundRepeatStop(); end UnRegisterForFrameTick(region) end function region:Expand() if data.anchorFrameType == "SELECTFRAME" or data.anchorFrameType == "CUSTOM" or data.anchorFrameType == "UNITFRAME" or data.anchorFrameType == "NAMEPLATE" then Private.AnchorFrame(data, region, parent); end if (region.toShow) then return; end region.toShow = true; region.justCreated = nil; if(region.PreShow) then region:PreShow(); end region.subRegionEvents:Notify("PreShow") Private.ApplyFrameLevel(region) region:Show(); Private.PerformActions(data, "start", region); if not(Private.Animate("display", data.uid, "start", data.animation.start, region, true, startMainAnimation, nil, cloneId)) then startMainAnimation(); end if inGroup then parent:UpdateBorder(region); end RegisterForFrameTick(region) region:UpdateTimerTick() end end -- Stubs that allow for polymorphism if not region.Collapse then function region:Collapse() end end if not region.Expand then function region:Expand() end end end function WeakAuras.SetTextureOrAtlas(texture, path, wrapModeH, wrapModeV) if type(path) == "string" and GetAtlasInfo(path) then texture:SetAtlas(path); else local needToClear = true if (texture.wrapModeH and texture.wrapModeH ~= wrapModeH) or (texture.wrapModeV and texture.wrapModeV ~= wrapModeV) then needToClear = true end texture.wrapModeH = wrapModeH texture.wrapModeV = wrapModeV if needToClear then texture:SetTexture(nil) end texture:SetTexture(path, wrapModeH, wrapModeV); end end
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
11
10095
--[[ 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: siitwizard.lua 3966 2008-12-29 17:39:48Z jow $ ]]-- local uci = require "luci.model.uci".cursor() -------------------- Init -------------------- -- -- Find link-local address -- LL_PREFIX = luci.ip.IPv6("fe80::/64") function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" local ipv4_pool = uci:get("siit", "ipv4", "pool") or "172.16.0.0/12" local ipv4_netsz = uci:get("siit", "ipv4", "netsize") or "24" -- -- Find IPv4 allocation pool -- local gv4_net = luci.ip.IPv4(ipv4_pool) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -------------------- View -------------------- f = SimpleForm("siitwizward", "SIIT-Wizzard", "This wizzard helps to setup SIIT (IPv4-over-IPv6) translation according to RFC2765.") f:field(DummyValue, "info_ula", "Mesh ULA address").value = ula:string() f:field(DummyValue, "ipv4_pool", "IPv4 allocation pool").value = "%s (%i hosts)" %{ gv4_net:string(), 2 ^ ( 32 - gv4_net:prefix() ) - 2 } f:field(DummyValue, "ipv4_size", "IPv4 LAN network prefix").value = "%i bit (%i hosts)" %{ ipv4_netsz, 2 ^ ( 32 - ipv4_netsz ) - 2 } mode = f:field(ListValue, "mode", "Operation mode") mode:value("client", "Client") mode:value("gateway", "Gateway") dev = f:field(ListValue, "device", "Wireless device") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IPv4 subnet") function lanip.formvalue(self, section) local val = self.map:formvalue(self:cbid(section)) local net = luci.ip.IPv4("%s/%i" %{ val, ipv4_netsz }) if net then if gv4_net:contains(net) then if not net:minhost():equal(net:host()) then self.error = { [section] = true } f.errmessage = "IPv4 address is not the first host of " .. "subnet, expected " .. net:minhost():string() end else self.error = { [section] = true } f.errmessage = "IPv4 address is not within the allocation pool" end else self.error = { [section] = true } f.errmessage = "Invalid IPv4 address given" end return val end dns = f:field(Value, "dns", "DNS server for LAN clients") dns.value = "141.1.1.1" -------------------- Control -------------------- function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false end return true end function mode.write(self, section, value) -- -- Find LAN IPv4 range -- local lan_net = luci.ip.IPv4( ( lanip:formvalue(section) or "172.16.0.1" ) .. "/" .. ipv4_netsz ) if not lan_net then return end -- -- Find wifi interface, dns server and hostname -- local device = dev:formvalue(section) local dns_server = dns:formvalue(section) or "141.1.1.1" local hostname = "siit-" .. lan_net:host():string():gsub("%.","-") -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", txpower = 10, sw_merge = 1, network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then -- wan mtu uci:set("network", "wan", "mtu", 1240) -- lan settings uci:tset("network", "lan", { mtu = 1240, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string(), proto = "static" }) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- v4 <-> siit route uci:delete_all("network", "route", function(s) return s.interface == "siit0" end) uci:section("network", "route", nil, { interface = "siit0", target = gv4_net:network():string(), netmask = gv4_net:mask():string() }) -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan settings uci:tset("network", "lan", { mtu = 1240, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) -- ipv4 <-> siit route uci:delete_all("network", "route", function(s) return s.interface == "siit0" end) -- XXX: kind of a catch all, gv4_net would be better -- but does not cover non-local v4 space uci:section("network", "route", nil, { interface = "siit0", target = "0.0.0.0", netmask = "0.0.0.0" }) end -- setup the firewall uci:delete_all("firewall", "zone", function(s) return ( s['.name'] == "siit0" or s.name == "siit0" or s.network == "siit0" or s['.name'] == wifi_device or s.name == wifi_device or s.network == wifi_device ) end) uci:delete_all("firewall", "forwarding", function(s) return ( s.src == wifi_device and s.dest == "siit0" or s.dest == wifi_device and s.src == "siit0" or s.src == "lan" and s.dest == "siit0" or s.dest == "lan" and s.src == "siit0" ) end) uci:section("firewall", "zone", "siit0", { name = "siit0", network = "siit0", input = "ACCEPT", output = "ACCEPT", forward = "ACCEPT" }) uci:section("firewall", "zone", wifi_device, { name = wifi_device, network = wifi_device, input = "ACCEPT", output = "ACCEPT", forward = "ACCEPT" }) uci:section("firewall", "forwarding", nil, { src = wifi_device, dest = "siit0" }) uci:section("firewall", "forwarding", nil, { src = "siit0", dest = wifi_device }) uci:section("firewall", "forwarding", nil, { src = "lan", dest = "siit0" }) uci:section("firewall", "forwarding", nil, { src = "siit0", dest = "lan" }) -- firewall include uci:delete_all("firewall", "include", function(s) return s.path == "/etc/firewall.user" end) uci:section("firewall", "include", nil, { path = "/etc/firewall.user" }) -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "none" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "unique-local" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) return true end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) -- txtinfo v6 & olsrd nameservice uci:foreach("olsrd", "LoadPlugin", function(s) if s.library == "olsrd_txtinfo.so.0.1" then uci:set("olsrd", s['.name'], "accept", "::1") elseif s.library == "olsrd_nameservice.so.0.3" then uci:set("olsrd", s['.name'], "name", hostname) end end) -- lan dns uci:tset("dhcp", "lan", { dhcp_option = "6," .. dns_server, start = bit.band(lan_net:minhost():add(1)[2][2], 0xFF), limit = ( 2 ^ ( 32 - lan_net:prefix() ) ) - 3 }) -- hostname uci:foreach("system", "system", function(s) uci:set("system", s['.name'], "hostname", hostname) end) uci:save("wireless") uci:save("firewall") uci:save("network") uci:save("system") uci:save("olsrd") uci:save("dhcp") end return f
gpl-2.0
iamliqiang/prosody-modules
mod_openid/mod_openid.lua
32
15176
local usermanager = require "core.usermanager" local httpserver = require "net.httpserver" local jidutil = require "util.jid" local hmac = require "hmac" local base64 = require "util.encodings".base64 local humane = require "util.serialization".serialize -- Configuration local base = "openid" local openidns = "http://specs.openid.net/auth/2.0" -- [#4.1.2] local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" }; local associations = {} local function genkey(length) -- FIXME not cryptographically secure str = {} for i = 1,length do local rand = math.random(33, 126) table.insert(str, string.char(rand)) end return table.concat(str) end local function tokvstring(dict) -- key-value encoding for a dictionary [#4.1.3] local str = "" for k,v in pairs(dict) do str = str..k..":"..v.."\n" end return str end local function newassoc(key, shared) -- TODO don't use genkey here local handle = genkey(16) associations[handle] = {} associations[handle]["key"] = key associations[handle]["shared"] = shared associations[handle]["time"] = os.time() return handle end local function split(str, sep) local splits = {} str:gsub("([^.."..sep.."]*)"..sep, function(c) table.insert(splits, c) end) return splits end local function sign(response, key) local fields = {} for _,field in pairs(split(response["openid.signed"],",")) do fields[field] = response["openid."..field] end -- [#10.1] return base64.encode(hmac.sha256(key, tokvstring(fields))) end local function urlencode(s) return (string.gsub(s, "%W", function(str) return string.format("%%%02X", string.byte(str)) end)) end local function urldecode(s) return(string.gsub(string.gsub(s, "+", " "), "%%(%x%x)", function(str) return string.char(tonumber(str,16)) end)) end local function utctime() local now = os.time() local diff = os.difftime(now, os.time(os.date("!*t", now))) return now-diff end local function nonce() -- generate a response nonce [#10.1] local random = "" for i=0,10 do random = random..string.char(math.random(33,126)) end local timestamp = os.date("%Y-%m-%dT%H:%M:%SZ", utctime()) return timestamp..random end local function query_params(query) if type(query) == "string" and #query > 0 then if query:match("=") then local params = {} for k, v in query:gmatch("&?([^=%?]+)=([^&%?]+)&?") do if k and v then params[urldecode(k)] = urldecode(v) end end return params else return urldecode(query) end end end local function split_host_port(combined) local host = combined local port = "" local cpos = string.find(combined, ":") if cpos ~= nil then host = string.sub(combined, 0, cpos-1) port = string.sub(combined, cpos+1) end return host, port end local function toquerystring(dict) -- query string encoding for a dictionary [#4.1.3] local str = "" for k,v in pairs(dict) do str = str..urlencode(k).."="..urlencode(v).."&" end return string.sub(str, 0, -1) end local function match_realm(url, realm) -- FIXME do actual match [#9.2] return true end local function handle_endpoint(method, body, request) module:log("debug", "Request at OpenID provider endpoint") local params = nil if method == "GET" then params = query_params(request.url.query) elseif method == "POST" then params = query_params(body) else -- TODO error return response_404 end module:log("debug", "Request Parameters:\n"..humane(params)) if params["openid.ns"] == openidns then -- OpenID 2.0 request [#5.1.1] if params["openid.mode"] == "associate" then -- Associate mode [#8] -- TODO implement association -- Error response [#8.2.4] local openidresponse = { ["ns"] = openidns, ["session_type"] = params["openid.session_type"], ["assoc_type"] = params["openid.assoc_type"], ["error"] = "Association not supported... yet", ["error_code"] = "unsupported-type", } local kvresponse = tokvstring(openidresponse) module:log("debug", "OpenID Response:\n"..kvresponse) return { headers = { ["Content-Type"] = "text/plain" }, body = kvresponse } elseif params["openid.mode"] == "checkid_setup" or params["openid.mode"] == "checkid_immediate" then -- Requesting authentication [#9] if not params["openid.realm"] then -- set realm to default value of return_to [#9.1] if params["openid.return_to"] then params["openid.realm"] = params["openid.return_to"] else -- neither was sent, error [#9.1] -- FIXME return proper error return response_404 end end if params["openid.return_to"] then -- Assure that the return_to url matches the realm [#9.2] if not match_realm(params["openid.return_to"], params["openid.realm"]) then -- FIXME return proper error return response_404 end -- Verify the return url [#9.2.1] -- TODO implement return url verification end if params["openid.claimed_id"] and params["openid.identity"] then -- asserting an identifier [#9.1] if params["openid.identity"] == "http://specs.openid.net/auth/2.0/identifier_select" then -- automatically select an identity [#9.1] params["openid.identity"] = params["openid.claimed_id"] end if params["openid.mode"] == "checkid_setup" then -- Check ID Setup mode -- TODO implement: NEXT STEP local head = "<title>Prosody OpenID : Login</title>" local body = string.format([[ <p>Open ID Authentication<p> <p>Identifier: <tt>%s</tt></p> <p>Realm: <tt>%s</tt></p> <p>Return: <tt>%s</tt></p> <form method="POST" action="%s"> Jabber ID: <input type="text" name="jid"/><br/> Password: <input type="password" name="password"/><br/> <input type="hidden" name="openid.return_to" value="%s"/> <input type="submit" value="Authenticate"/> </form> ]], params["openid.claimed_id"], params["openid.realm"], params["openid.return_to"], base, params["openid.return_to"]) return string.format([[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> %s </head> <body> %s </body> </html> ]], head, body) elseif params["openid.mode"] == "checkid_immediate" then -- Check ID Immediate mode [#9.3] -- TODO implement check id immediate end else -- not asserting an identifier [#9.1] -- used for extensions -- TODO implement common extensions end elseif params["openid.mode"] == "check_authentication" then module:log("debug", "OpenID Check Authentication Mode") local assoc = associations[params["openid.assoc_handle"]] module:log("debug", "Checking Association Handle: "..params["openid.assoc_handle"]) if assoc and not assoc["shared"] then module:log("debug", "Found valid association") local sig = sign(params, assoc["key"]) local is_valid = "false" if sig == params["openid.sig"] then is_valid = "true" end module:log("debug", "Signature is: "..is_valid) openidresponse = { ns = openidns, is_valid = is_valid, } -- Delete this association associations[params["openid.assoc_handle"]] = nil return { headers = { ["Content-Type"] = "text/plain" }, body = tokvstring(openidresponse), } else module:log("debug", "No valid association") -- TODO return error -- Invalidate the handle [#11.4.2.2] end else -- Some other mode -- TODO error end elseif params["password"] then -- User is authenticating local user, domain = jidutil.split(params["jid"]) module:log("debug", "Authenticating "..params["jid"].." ("..user..","..domain..") with password: "..params["password"]) local valid = usermanager.validate_credentials(domain, user, params["password"], "PLAIN") if valid then module:log("debug", "Authentication Succeeded: "..params["jid"]) if params["openid.return_to"] ~= "" then -- TODO redirect the user to return_to with the openid response -- included, need to handle the case if its a GET, that there are -- existing query parameters on the return_to URL [#10.1] local host, port = split_host_port(request.headers.host) local endpointurl = "" if port == '' then endpointurl = string.format("http://%s/%s", host, base) else endpointurl = string.format("http://%s:%s/%s", host, port, base) end local nonce = nonce() local key = genkey(32) local assoc_handle = newassoc(key) local openidresponse = { ["openid.ns"] = openidns, ["openid.mode"] = "id_res", ["openid.op_endpoint"] = endpointurl, ["openid.claimed_id"] = endpointurl.."/"..user, ["openid.identity"] = endpointurl.."/"..user, ["openid.return_to"] = params["openid.return_to"], ["openid.response_nonce"] = nonce, ["openid.assoc_handle"] = assoc_handle, ["openid.signed"] = "op_endpoint,identity,claimed_id,return_to,assoc_handle,response_nonce", -- FIXME ["openid.sig"] = nil, } openidresponse["openid.sig"] = sign(openidresponse, key) queryresponse = toquerystring(openidresponse) redirecturl = params["openid.return_to"] -- add the parameters to the return_to if redirecturl:match("?") then redirecturl = redirecturl.."&" else redirecturl = redirecturl.."?" end redirecturl = redirecturl..queryresponse module:log("debug", "Open ID Positive Assertion Response Table:\n"..humane(openidresponse)) module:log("debug", "Open ID Positive Assertion Response URL:\n"..queryresponse) module:log("debug", "Redirecting User to:\n"..redirecturl) return { status = "303 See Other", headers = { Location = redirecturl, }, body = "Redirecting to: "..redirecturl -- TODO Include a note with a hyperlink to redirect } else -- TODO Do something useful is there is no return_to end else module:log("debug", "Authentication Failed: "..params["jid"]) -- TODO let them try again end else -- Not an Open ID request, do something useful -- TODO end return response_404 end local function handle_identifier(method, body, request, id) module:log("debug", "Request at OpenID identifier") local host, port = split_host_port(request.headers.host) local user_name = "" local user_domain = "" local apos = string.find(id, "@") if apos == nil then user_name = id user_domain = host else user_name = string.sub(id, 0, apos-1) user_domain = string.sub(id, apos+1) end user, domain = jidutil.split(id) local exists = usermanager.user_exists(user_name, user_domain) if not exists then return response_404 end local endpointurl = "" if port == '' then endpointurl = string.format("http://%s/%s", host, base) else endpointurl = string.format("http://%s:%s/%s", host, port, base) end local head = string.format("<title>Prosody OpenID : %s@%s</title>", user_name, user_domain) -- OpenID HTML discovery [#7.3] head = head .. string.format('<link rel="openid2.provider" href="%s" />', endpointurl) local content = 'request.url.path: ' .. request.url.path .. '<br/>' content = content .. 'host+port: ' .. request.headers.host .. '<br/>' content = content .. 'host: ' .. tostring(host) .. '<br/>' content = content .. 'port: ' .. tostring(port) .. '<br/>' content = content .. 'user_name: ' .. user_name .. '<br/>' content = content .. 'user_domain: ' .. user_domain .. '<br/>' content = content .. 'exists: ' .. tostring(exists) .. '<br/>' local body = string.format('<p>%s</p>', content) local data = string.format([[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> %s </head> <body> %s </body> </html> ]], head, body) return data; end local function handle_request(method, body, request) module:log("debug", "Received request") -- Make sure the host is enabled local host = split_host_port(request.headers.host) if not hosts[host] then return response_404 end if request.url.path == "/"..base then -- OpenID Provider Endpoint return handle_endpoint(method, body, request) else local id = request.url.path:match("^/"..base.."/(.+)$") if id then -- OpenID Identifier return handle_identifier(method, body, request, id) else return response_404 end end end httpserver.new{ port = 5280, base = base, handler = handle_request, ssl = false}
mit
otland/forgottenserver
data/lib/core/item.lua
4
21833
function Item.getType(self) return ItemType(self:getId()) end function Item:getClassification() return self:getType():getClassification() end function Item.isContainer(self) return false end function Item.isCreature(self) return false end function Item.isMonster(self) return false end function Item.isNpc(self) return false end function Item.isPlayer(self) return false end function Item.isTeleport(self) return false end function Item.isPodium(self) return false end function Item.isTile(self) return false end function Item:isItemType() return false end do local aux = { ["Defense"] = {key = ITEM_ATTRIBUTE_DEFENSE}, ["ExtraDefense"] = {key = ITEM_ATTRIBUTE_EXTRADEFENSE}, ["Attack"] = {key = ITEM_ATTRIBUTE_ATTACK}, ["AttackSpeed"] = {key = ITEM_ATTRIBUTE_ATTACK_SPEED}, ["HitChance"] = {key = ITEM_ATTRIBUTE_HITCHANCE}, ["ShootRange"] = {key = ITEM_ATTRIBUTE_SHOOTRANGE}, ["Armor"] = {key = ITEM_ATTRIBUTE_ARMOR}, ["Duration"] = {key = ITEM_ATTRIBUTE_DURATION, cmp = function(v) return v > 0 end}, ["Text"] = {key = ITEM_ATTRIBUTE_TEXT, cmp = function(v) return v ~= "" end}, ["Date"] = {key = ITEM_ATTRIBUTE_DATE}, ["Writer"] = {key = ITEM_ATTRIBUTE_WRITER, cmp = function(v) return v ~= "" end}, ["Tier"] = {key = ITEM_ATTRIBUTE_TIER} } function setAuxFunctions() for name, def in pairs(aux) do Item["get" .. name] = function(self) local attr = self:getAttribute(def.key) if def.cmp and def.cmp(attr) then return attr elseif not def.cmp and attr and attr ~= 0 then return attr end local default = ItemType["get" .. name] return default and default(self:getType()) or nil end end end setAuxFunctions() end do StringStream = {} setmetatable(StringStream, { __call = function(self) local obj = {} return setmetatable(obj, {__index = StringStream}) end }) function StringStream.append(self, str, ...) self[#self + 1] = string.format(str, ...) end function StringStream.concat(self, sep) return table.concat(self, sep) end local function internalItemGetNameDescription(it, item, subType, addArticle) subType = subType or (item and item:getSubType() or -1) local ss = StringStream() local obj = item or it local name = obj:getName() if name ~= "" then if it:isStackable() and subType > 1 then if it:hasShowCount() then ss:append("%d ", subType) end ss:append("%s", obj:getPluralName()) else if addArticle and obj:getArticle() ~= "" then ss:append("%s ", obj:getArticle()) end ss:append("%s", obj:getName()) end else ss:append("an item of type %d", obj:getId()) end return ss:concat() end function Item:getNameDescription(subType, addArticle) return internalItemGetNameDescription(self:getType(), self, subType, addArticle) end function ItemType:getNameDescription(subType, addArticle) return internalItemGetNameDescription(self, nil, subType, addArticle) end end do -- Lua item descriptions created by Zbizu local housePriceVisible = configManager.getBoolean(configKeys.HOUSE_DOOR_SHOW_PRICE) local pricePerSQM = configManager.getNumber(configKeys.HOUSE_PRICE) local showAtkWeaponTypes = {WEAPON_CLUB, WEAPON_SWORD, WEAPON_AXE, WEAPON_DISTANCE} local showDefWeaponTypes = {WEAPON_CLUB, WEAPON_SWORD, WEAPON_AXE, WEAPON_DISTANCE, WEAPON_SHIELD} local suppressedConditionNames = { -- NOTE: these names are made up just to match dwarven ring attribute style [CONDITION_POISON] = "antidote", [CONDITION_FIRE] = "non-inflammable", [CONDITION_ENERGY] = "antistatic", [CONDITION_BLEEDING] = "antiseptic", [CONDITION_HASTE] = "heavy", [CONDITION_PARALYZE] = "slow immunity", [CONDITION_DRUNK] = "hard drinking", [CONDITION_DROWN] = "water breathing", [CONDITION_FREEZING] = "warm", [CONDITION_DAZZLED] = "dazzle immunity", [CONDITION_CURSED] = "curse immunity" } -- first argument: Item, itemType or item id local function internalItemGetDescription(item, lookDistance, subType, addArticle) -- optional, but true by default if addArticle == nil then addArticle = true end local isVirtual = false -- check if we're inspecting a real item or itemType only local itemType -- determine the kind of item data to process if tonumber(item) then -- number in function argument -- pull data from itemType instead isVirtual = true itemType = ItemType(item) if not itemType then return end -- polymorphism for item attributes (atk, def, etc) item = itemType elseif item:isItemType() then isVirtual = true itemType = item else itemType = item:getType() end -- use default values if not provided lookDistance = lookDistance or -1 subType = subType or (not isVirtual and item:getSubType() or -1) -- possibility of picking the item up (will be reused later) local isPickupable = itemType:isMovable() and itemType:isPickupable() -- has uniqueId tag local isUnique = false if not isVirtual then local uid = item:getUniqueId() if uid > 100 and uid < 0xFFFF then isUnique = true end end -- read item name with article local itemName = item:getNameDescription(subType, addArticle) -- things that will go in parenthesis "(...)" local descriptions = {} -- spell words do local spellName = itemType:getRuneSpellName() if spellName then descriptions[#descriptions + 1] = string.format('"%s"', spellName) end end -- container capacity do -- show container capacity only on non-quest containers if not isUnique then local isContainer = itemType:isContainer() if isContainer then descriptions[#descriptions + 1] = string.format("Vol:%d", itemType:getCapacity()) end end end -- actionId (will be reused) local actionId = 0 if not isVirtual then actionId = item:getActionId() end -- key do if not isVirtual and itemType:isKey() then descriptions[#descriptions + 1] = string.format("Key:%0.4d", actionId) end end -- weapon type (will be reused) local weaponType = itemType:getWeaponType() -- attack attributes do local attack = item:getAttack() -- bows and crossbows -- range, attack, hit% if itemType:isBow() then descriptions[#descriptions + 1] = string.format("Range:%d", item:getShootRange()) if attack ~= 0 then descriptions[#descriptions + 1] = string.format("Atk+%d", attack) end local hitPercent = item:getHitChance() if hitPercent ~= 0 then descriptions[#descriptions + 1] = string.format("Hit%%+%d", hitPercent) end -- melee weapons and missiles -- atk x physical +y% element elseif table.contains(showAtkWeaponTypes, weaponType) then local atkString = string.format("Atk:%d", attack) local elementDmg = itemType:getElementDamage() if elementDmg ~= 0 then atkString = string.format("%s physical %+d %s", atkString, elementDmg, getCombatName(itemType:getElementType())) end descriptions[#descriptions + 1] = atkString end end -- attack speed do local atkSpeed = item:getAttackSpeed() if atkSpeed ~= 0 then descriptions[#descriptions + 1] = string.format("AS:%0.2f/turn", 2000 / atkSpeed) end end -- defense attributes do local showDef = table.contains(showDefWeaponTypes, weaponType) local ammoType = itemType:getAmmoType() if showDef then local defense = item:getDefense() local defAttrs = {} if weaponType == WEAPON_DISTANCE then -- throwables if ammoType ~= AMMO_ARROW and ammoType ~= AMMO_BOLT then defAttrs[#defAttrs + 1] = defense end else defAttrs[#defAttrs + 1] = defense end -- extra def local xD = item:getExtraDefense() if xD ~= 0 then defAttrs[#defAttrs + 1] = string.format("%+d", xD) end if #defAttrs > 0 then descriptions[#descriptions + 1] = string.format("Def:%s", table.concat(defAttrs, " ")) end end end -- armor do local arm = item:getArmor() if arm > 0 then descriptions[#descriptions + 1] = string.format("Arm:%d", arm) end end -- abilities (will be reused) local abilities = itemType:getAbilities() -- stats: hp/mp/soul/magic level do local stats = {} -- flat buffs for stat, value in pairs(abilities.stats) do stats[stat] = {name = getStatName(stat-1)} if value ~= 0 then stats[stat].flat = value end end -- percent buffs for stat, value in pairs(abilities.statsPercent) do if value ~= 0 then stats[stat].percent = value end end -- display the buffs for _, statData in pairs(stats) do local displayValues = {} if statData.flat then displayValues[#displayValues + 1] = statData.flat end if statData.percent then displayValues[#displayValues + 1] = statData.percent end -- desired format examples: -- +5% -- +20 and 5% if #displayValues > 0 then displayValues[1] = string.format("%+d", displayValues[1]) descriptions[#descriptions + 1] = string.format("%s %s", statData.name, table.concat(displayValues, " and ")) end end end -- skill boosts do for skill, value in pairs(abilities.skills) do if value ~= 0 then descriptions[#descriptions + 1] = string.format("%s %+d", getSkillName(skill-1), value) end end end -- element magic level do for element, value in pairs(abilities.specialMagicLevel) do if value ~= 0 then descriptions[#descriptions + 1] = string.format("%s magic level %+d", getCombatName(2^(element-1)), value) end end end -- special skills do for skill, value in pairs(abilities.specialSkills) do if value ~= 0 then -- add + symbol to special skill "amount" fields if skill-1 < 6 and skill % 2 == 1 then value = string.format("%+d", value) elseif skill-1 >= 6 then -- fatal, dodge, momentum coming from the item natively -- (stats coming from tier are near tier info) value = string.format("%0.2f", value/100) end descriptions[#descriptions + 1] = string.format("%s %s%%", getSpecialSkillName(skill-1), value) end end end -- cleave -- perfect shot -- to do -- protections do local protections = {} for element, value in pairs(abilities.absorbPercent) do if value ~= 0 then protections[#protections + 1] = string.format("%s %+d%%", getCombatName(2^(element-1)), value) end end if #protections > 0 then descriptions[#descriptions + 1] = string.format("protection %s", table.concat(protections, ", ")) end end -- damage reflection -- to do -- magic shield (classic) if abilities.manaShield then descriptions[#descriptions + 1] = "magic shield" end -- magic shield capacity +flat and x% -- to do -- regeneration if abilities.manaGain > 0 or abilities.healthGain > 0 or abilities.regeneration then descriptions[#descriptions + 1] = "faster regeneration" end -- invisibility if abilities.invisible then descriptions[#descriptions + 1] = "invisibility" end -- condition immunities do local suppressions = abilities.conditionSuppressions for conditionId, conditionName in pairs(suppressedConditionNames) do if bit.band(abilities.conditionSuppressions, conditionId) ~= 0 then descriptions[#descriptions + 1] = conditionName end end end -- speed if abilities.speed ~= 0 then descriptions[#descriptions + 1] = string.format("speed %+d", math.floor(abilities.speed / 2)) end -- collecting attributes finished -- build the output text local response = {itemName} -- item group (will be reused) local itemGroup = itemType:getGroup() -- fluid type do if (itemGroup == ITEM_GROUP_FLUID or itemGroup == ITEM_GROUP_SPLASH) and subType > 0 then local subTypeName = getSubTypeName(subType) response[#response + 1] = string.format(" of %s", (subTypeName ~= '' and subTypeName or "unknown")) end end -- door check (will be reused) local isDoor = itemType:isDoor() -- door info if isDoor then if not isVirtual then local minLevelDoor = itemType:getLevelDoor() if minLevelDoor ~= 0 then if actionId >= minLevelDoor then response[#response + 1] = string.format(" for level %d", actionId - minLevelDoor) end end end end -- primary attributes parenthesis if #descriptions > 0 then response[#response + 1] = string.format(" (%s)", table.concat(descriptions, ", ")) end -- podium description if not isVirtual and itemType:isPodium() then local outfit = item:getOutfit() local hasOutfit = item:hasFlag(PODIUM_SHOW_OUTFIT) local hasMount = item:hasFlag(PODIUM_SHOW_MOUNT) if outfit then local podiumParts = {} local outfitType = Outfit(outfit.lookType) if outfitType then if hasOutfit then podiumParts[#podiumParts + 1] = string.format("%s outfit", outfitType.name) end -- search mount local mountName = getMountNameByLookType(outfit.lookMount) if mountName and hasMount then podiumParts[#podiumParts + 1] = string.format("%s mount", mountName) end else -- search mount local mountName = getMountNameByLookType(outfit.lookMount) local isEnabled = mountName and hasMount if not mountName then mountName = getMountNameByLookType(outfit.lookType) isEnabled = mountName and hasOutfit end if mountName and isEnabled then podiumParts[#podiumParts + 1] = string.format("%s mount", mountName) end end if #podiumParts > 0 then response[#response + 1] = string.format(" displaying the %s", table.concat(podiumParts, " on the ")) end end end -- charges and duration do local expireInfo = {} -- charges if itemType:hasShowCharges() then local charges = item:getCharges() expireInfo[#expireInfo + 1] = string.format("has %d charge%s left", charges, (charges ~= 1 and "s" or "")) end -- duration if itemType:hasShowDuration() then local currentDuration = item:getDuration() if isVirtual then currentDuration = currentDuration * 1000 end local maxDuration = itemType:getDuration() * 1000 if maxDuration == 0 then local transferType = itemType:getTransformEquipId() if transferType ~= 0 then transferType = ItemType(transferType) maxDuration = transferType and transferType:getDuration() * 1000 or maxDuration end end if currentDuration == maxDuration then expireInfo[#expireInfo + 1] = "is brand-new" elseif currentDuration ~= 0 then expireInfo[#expireInfo + 1] = string.format("will expire in %s", Game.getCountdownString(math.floor(currentDuration/1000), true, true)) end end if #expireInfo > 0 then response[#response + 1] = string.format(" that %s", table.concat(expireInfo, " and ")) end end -- dot after primary attributes info response[#response + 1] = "." -- empty fluid container suffix if itemGroup == ITEM_GROUP_FLUID and subType < 1 then response[#response + 1] = " It is empty." end -- house door if isDoor and not isVirtual then local tile = item:getTile() if tile then local house = tile:getHouse() if house then local houseName = house:getName() local houseOwnerName = house:getOwnerName() local isForSale = false if not houseOwnerName or houseOwnerName:len() == 0 then houseOwnerName = "Nobody" isForSale = true end response[#response + 1] = string.format(" It belongs to house '%s'. %s owns this house.", houseName, houseOwnerName) if housePriceVisible and isForSale and pricePerSQM > 0 then response[#response + 1] = string.format(" It costs %d gold coins.", pricePerSQM * house:getTileCount()) end end end end -- imbuements (to do) -- \nImbuements: (Basic Strike 2:30h, Basic Void 2:30h, Empty Slot). -- item class -- Classification: x Tier: y (0.50% Onslaught). do local classification = itemType:getClassification() local tier = isVirtual and 0 or item:getTier() or 0 if classification > 0 or tier > 0 then if classification == 0 then classification = "other" end local tierString = tier if tier > 0 then local bonusType, bonusValue = itemType:getTierBonus(tier) if bonusType ~= -1 then if bonusType > 5 then tierString = string.format("%d (%0.2f%% %s)", tier, bonusValue, getSpecialSkillName(bonusType)) else tierString = string.format("%d (%d%% %s)", tier, bonusValue, getSpecialSkillName(bonusType)) end end end response[#response + 1] = string.format("\nClassification: %s Tier: %s.", classification, tierString) end end -- item count (will be reused later) local count = isVirtual and 1 or item:getCount() -- wield info do if itemType:isRune() then local rune = Spell(itemType:getId()) if rune then local runeLevel = rune:runeLevel() local runeMagLevel = rune:runeMagicLevel() local runeVocMap = rune:vocation() local hasLevel = runeLevel > 0 local hasMLvl = runeMagLevel > 0 local hasVoc = #runeVocMap > 0 if hasLevel or hasMLvl or hasVoc then local vocAttrs = {} if not hasVoc then vocAttrs[#vocAttrs + 1] = "players" else for _, vocName in ipairs(runeVocMap) do local vocation = Vocation(vocName) if vocation and vocation:getPromotion() then vocAttrs[#vocAttrs + 1] = vocName end end end if #vocAttrs > 1 then vocAttrs[#vocAttrs - 1] = string.format("and %s", vocAttrs[#vocAttrs - 1]) end local levelInfo = {} if hasLevel then levelInfo[#levelInfo + 1] = string.format("level %d", runeLevel) end if hasMLvl then levelInfo[#levelInfo + 1] = string.format("magic level %d", runeMagLevel) end local levelStr = "" if #levelInfo > 0 then levelStr = string.format(" of %s or higher", table.concat(levelInfo, " and ")) end response[#response + 1] = string.format( "\n%s can only be used properly by %s%s.", (count > 1 and "They" or "It"), table.concat(vocAttrs, ", "), levelStr ) end end else local wieldInfo = itemType:getWieldInfo() if wieldInfo ~= 0 then local wieldAttrs = {} if bit.band(wieldInfo, WIELDINFO_PREMIUM) ~= 0 then wieldAttrs[#wieldAttrs + 1] = "premium" end local vocStr = itemType:getVocationString() if vocStr ~= '' then wieldAttrs[#wieldAttrs + 1] = vocStr else wieldAttrs[#wieldAttrs + 1] = "players" end local levelInfo = {} if bit.band(wieldInfo, WIELDINFO_LEVEL) ~= 0 then levelInfo[#levelInfo + 1] = string.format("level %d", itemType:getMinReqLevel()) end if bit.band(wieldInfo, WIELDINFO_MAGLV) ~= 0 then levelInfo[#levelInfo + 1] = string.format("magic level %d", itemType:getMinReqMagicLevel()) end if #levelInfo > 0 then wieldAttrs[#wieldAttrs + 1] = string.format("of %s or higher", table.concat(levelInfo, " and ")) end response[#response + 1] = string.format( "\n%s can only be wielded properly by %s.", (count > 1 and "They" or "It"), table.concat(wieldAttrs, " ") ) end end end if lookDistance <= 1 then local weight = item:getWeight() if isPickupable and not isUnique then response[#response + 1] = string.format("\n%s %0.2f oz.", (count == 1 or not itemType:hasShowCount()) and "It weighs" or "They weigh", weight / 100) end end -- item text if not isVirtual and itemType:hasAllowDistRead() then local text = item:getText() if text and text:len() > 0 then if lookDistance <= 4 then local writer = item:getAttribute(ITEM_ATTRIBUTE_WRITER) local writeDate = item:getAttribute(ITEM_ATTRIBUTE_DATE) local writeInfo = {} if writer and writer:len() > 0 then writeInfo[#writeInfo + 1] = string.format("\n%s wrote", writer) if writeDate and writeDate > 0 then writeInfo[#writeInfo + 1] = string.format(" on %s", os.date("%d %b %Y", writeDate)) end end if #writeInfo > 0 then response[#response + 1] = string.format("%s:\n%s", table.concat(writeInfo, ""), text) else response[#response + 1] = string.format("\nYou read: %s", text) end else response[#response + 1] = "\nYou are too far away to read it." end else response[#response + 1] = "\nNothing is written on it." end end -- item description local isBed = itemType:isBed() if lookDistance <= 1 or (not isVirtual and (isDoor or isBed)) then -- custom item description local desc = not isVirtual and item:getSpecialDescription() -- native item description if not desc or desc == "" then desc = itemType:getDescription() end -- level door description if isDoor and lookDistance <= 1 and (not desc or desc == "") and itemType:getLevelDoor() ~= 0 then desc = "Only the worthy may pass." end if desc and desc:len() > 0 then if not (isBed and desc == "Nobody is sleeping there.") then response[#response + 1] = string.format("\n%s", desc) end end end -- pickupable items with store flag if not isVirtual and isPickupable and item:isStoreItem() then response[#response + 1] = "\nThis item cannot be traded." end -- turn response into a single string return table.concat(response, "") end function Item:getDescription(lookDistance, subType, addArticle) return internalItemGetDescription(self, lookDistance, subType, addArticle) end function ItemType:getItemDescription(lookDistance, subType, addArticle) return internalItemGetDescription(self, lookDistance, subType, addArticle) end end
gpl-2.0
KNIGHTTH0R/uzz
plugins/help.lua
2
2794
do function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name,number) local plugin = "" if number then local i = 0 for name in pairsByKeys(plugins) do if plugins[name].hide then name = nil else i = i + 1 if i == tonumber(number) then plugin = plugins[name] end end end else plugin = plugins[name] if not plugin then return nil end end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do text = text..usage..'\n' end text = text..'\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n\n' end return text end -- !help command local function telegram_help() local i = 0 local text = "Plugins list:\n\n" -- Plugins names for name in pairsByKeys(plugins) do if plugins[name].hide then name = nil else i = i + 1 text = text..i..'. '..name..'\n' end end text = text..'\n'..'There are '..i..' plugins enabled.' text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all() local ret = "" for name in pairsByKeys(plugins) do if plugins[name].hide then name = nil else ret = ret .. plugin_help(name) end end return ret end local function run(msg, matches) if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all() else local text = "" if tonumber(matches[1]) then text = plugin_help(nil,matches[1]) else text = plugin_help(matches[1]) end if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin.", "!help [number]: Commands for that plugin. Type !help to get the plugin number." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
Native-Software/Krea
CoronaGameEditor/bin/Release/Lua Repository/pathfollow.lua
3
6343
--- This module is provided as it by Native-Software for use into a Krea project. -- @description Module managing the path that an object should follow -- <br>Changing the content of this file is at your own risk. -- As the software Krea uses this file to auto-generate code, it can create errors during generation if you change his content.</br> -- @copyright Native-Software 2012- All Rights Reserved. -- @author Frederic Raimondi -- @release 1.0 -- @see object module("pathfollow", package.seeall) --- -- Members of the Path follow Instance -- @class table -- @name Fields -- @field params The table params used to create the path follow instance -- @field targetObject The Object instance to move -- @field iteration The number of transition iteration -- @field rotate Indicates whether the path follow make the Corona display object rotating during the transition -- @field speed The time in milliseconds for each transition cycle -- @field path The table containing all points to reach PathFollow = {} PathFollow.__index = PathFollow local pi = math.pi local atan2 = math.atan2 local sqrt = math.sqrt --- -- @description Create a new Instance of path follow for a object -- @usage Usage: -- <ul> -- <li><code>local params = {} -- <br>params.targetObject = obj -- <br>params.path = {x1,y1,x2,y2,x3,y3,...} -- <br>params.isCyclic = true -- <br>params.speed = 5000 -- <br>params.iteration = 10 -- <br>params.removeOnComplete = true</li> -- <li>local pathF = require("pathfollow").PathFollow.create(params)</code> </li> -- </ul></br> -- @param params Lua Table containing the params -- @return Instance of PathFollow object function PathFollow.create(params) --Init attributes of instance local pathFollow = {} setmetatable(pathFollow,PathFollow) --Init attributes pathFollow.params = params pathFollow.targetObject = params.targetObject pathFollow.iteration = params.iteration pathFollow.rotate = params.rotate pathFollow.removeOnComplete = params.removeOnComplete if(pathFollow.iteration <= 0) then pathFollow.iteration = -1 end pathFollow.currentIteration = 1 pathFollow.speed = params.speed pathFollow.path = params.path pathFollow.pointsByStep = {} local totalPoints = 0 pathFollow.timeByPoint = 0 local pow = math.pow local path = pathFollow.path for i = 1,#path -1 ,1 do local currentX = path[i].x local currentY = path[i].y local nextX = path[i+1].x local nextY = path[i+1].y local nbPoints = sqrt(pow(nextY - currentY,2) + pow(nextX - currentX,2)) table.insert(pathFollow.pointsByStep,nbPoints) totalPoints = totalPoints + nbPoints end pathFollow.timeByPoint = pathFollow.speed / totalPoints pathFollow.isCyclic = params.isCyclic pathFollow.isStarted = false pathFollow.currentIndexPath = 2 pathFollow.currentDirection = "NORMAL" -- or "REVERSE" pathFollow.onCompleteTransition = function() pathFollow:goNextPoint() end return pathFollow end --- -- @description Start the object transition following the path -- @usage Usage: -- <ul> -- <li><code>pathF:start()</code></li> -- </ul></br> function PathFollow:start() if(self.isStarted == false ) then self.isStarted = true self:goNextPoint() end end --- -- @description Pause the object transition following the path -- @usage Usage: -- <ul> -- <li><code>pathF:pause()</code></li> -- </ul></br> function PathFollow:pause() if(self.isStarted == true ) then if(self.currentTransition) then transition.cancel(self.currentTransition) end self.isStarted = false end end --- -- @description Go to the next point in the transition throught the path -- @usage Usage: -- <ul> -- <li><code>pathF:goNextPoint()</code></li> -- </ul></br> function PathFollow:goNextPoint() local path = self.path local currentIndexPath = self.currentIndexPath local obj = self.targetObject.object if(path) then if(#path >= currentIndexPath and currentIndexPath >=1) then local nextX = path[currentIndexPath].x local nextY = path[currentIndexPath].y local nbPoints = nil if(self.currentDirection == "NORMAL") then nbPoints = self.pointsByStep[currentIndexPath -1] elseif(self.currentDirection == "REVERSE") then nbPoints = self.pointsByStep[self.currentIndexPath] end local timeByStep = nbPoints * self.timeByPoint if(self.currentDirection == "NORMAL") then self.currentIndexPath = self.currentIndexPath +1 elseif(self.currentDirection == "REVERSE") then self.currentIndexPath = self.currentIndexPath -1 end if(self.rotate == true) then local x1 = obj.x local y1 = obj.y local angle = atan2 (nextY - y1, nextX - x1) * 180 / pi local diff = angle - obj.rotation if (diff < -180) then diff = diff +360 end if (diff > 180) then diff = diff - 360 end angle = obj.rotation +diff self.currentTransition = transition.to(obj,{time = timeByStep,rotation = angle,x = nextX, y = nextY,onComplete = self.onCompleteTransition}) else self.currentTransition = transition.to(obj,{time = timeByStep,x = nextX, y = nextY,onComplete = self.onCompleteTransition}) end else if(self.currentIteration < self.iteration or self.iteration == -1) then if(self.isCyclic == true ) then if(self.currentDirection == "NORMAL") then self.currentDirection = "REVERSE" self.currentIndexPath = #self.path-1 elseif(self.currentDirection == "REVERSE") then self.currentDirection ="NORMAL" self.currentIndexPath = 2 obj.rotation = self.targetObject.params.rotation end else self.currentIndexPath = 2 obj:setReferencePoint(display.TopLeftReferencePoint) obj.x = self.targetObject.xOrigin obj.y = self.targetObject.yOrigin obj:setReferencePoint(display.CenterReferencePoint) end self.currentIteration = self.currentIteration+1 self:goNextPoint() else if(self.removeOnComplete == true) then if(obj.removeSelf) then obj:removeSelf() end obj = nil end end end end end --- -- @description Clean the PathFollow instance -- @usage Usage: -- <ul> -- <li><code>pathF:clean()</code></li> -- <li><code>pathF = nil</code></li> -- </ul></br> function PathFollow:clean() self:pause() self.targetObject = nil self.path = nil self.speed = nil end
gpl-2.0
lcheylus/haka
modules/protocol/http/http_utils.lua
5
6141
-- 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 module = {} module.uri = {} module.cookies = {} local _unreserved = table.dict({string.byte("-"), string.byte("."), string.byte("_"), string.byte("~")}) local str = string.char local function uri_safe_decode(uri) local uri = string.gsub(uri, '%%(%x%x)', function(p) local val = tonumber(p, 16) if (val > 47 and val < 58) or (val > 64 and val < 91) or (val > 96 and val < 123) or (table.contains(_unreserved, val)) then return str(val) else return '%' .. string.upper(p) end end) return uri end local function uri_safe_decode_split(tab) for k, v in pairs(tab) do if type(v) == 'table' then uri_safe_decode_split(v) else tab[k] = uri_safe_decode(v) end end end local _prefixes = {{'^%.%./', ''}, {'^%./', ''}, {'^/%.%./', '/'}, {'^/%.%.$', '/'}, {'^/%./', '/'}, {'^/%.$', '/'}} local function remove_dot_segments(path) local output = {} local slash = '' local nb = 0 if path:sub(1,1) == '/' then slash = '/' end while path ~= '' do local index = 0 for _, prefix in ipairs(_prefixes) do path, nb = path:gsub(prefix[1], prefix[2]) if nb > 0 then if index == 2 or index == 3 then table.remove(output, #output) end break end index = index + 1 end if nb == 0 then if path:sub(1,1) == '/' then path = path:sub(2) end local left, right = path:match('([^/]*)([/]?.*)') table.insert(output, left) path = right end end return slash .. table.concat(output, '/') end -- Uri splitter object local HttpUriSplit = class.class('HttpUriSplit') function HttpUriSplit.method:__init(uri) assert(uri, "uri parameter required") local splitted_uri = {} local core_uri local query, fragment, path, authority -- uri = core_uri [ ?query ] [ #fragment ] core_uri, query, fragment = string.match(uri, '([^#?]*)[%?]*([^#]*)[#]*(.*)') -- query (+ split params) if query and query ~= '' then self.query = query local args = {} string.gsub(self.query, '([^=&]+)(=?([^&?]*))&?', function(p, q, r) args[p] = r or true return '' end) self.args = args end -- fragment if fragment and fragment ~= '' then self.fragment = fragment end -- scheme local temp = string.gsub(core_uri, '^(%a*)://', function(p) if p ~= '' then self.scheme = p end return '' end) -- authority and path authority, path = string.match(temp, '([^/]*)([/]*.*)$') if (path and path ~= '') then self.path = path end -- authority = [ userinfo @ ] host [ : port ] if authority and authority ~= '' then self.authority = authority -- userinfo authority = string.gsub(authority, "^([^@]*)@", function(p) if p ~= '' then self.userinfo = p end return '' end) -- port authority = string.gsub(authority, ":([^:][%d]+)$", function(p) if p ~= '' then self.port = p end return '' end) -- host if authority ~= '' then self.host = authority end -- userinfo = user : password (deprecated usage) if self.userinfo then local user, pass = string.match(self.userinfo, '(.*):(.*)') if user and user ~= '' then self.user = user self.pass = pass end end end end function HttpUriSplit.method:__tostring() local uri = {} -- authority components local auth = {} -- host if self.host then -- userinfo if self.user and self.pass then table.insert(auth, self.user) table.insert(auth, ':') table.insert(auth, self.pass) table.insert(auth, '@') end table.insert(auth, self.host) --port if self.port then table.insert(auth, ':') table.insert(auth, self.port) end end -- scheme and authority if #auth > 0 then if self.scheme then table.insert(uri, self.scheme) table.insert(uri, '://') table.insert(uri, table.concat(auth)) else table.insert(uri, table.concat(auth)) end end -- path if self.path then table.insert(uri, self.path) end -- query if self.query then local query = {} for k, v in pairs(self.args) do local q = {} table.insert(q, k) table.insert(q, v) table.insert(query, table.concat(q, '=')) end if #query > 0 then table.insert(uri, '?') table.insert(uri, table.concat(query, '&')) end end -- fragment if self.fragment then table.insert(uri, '#') table.insert(uri, self.fragment) end return table.concat(uri) end function HttpUriSplit.method:normalize() assert(self) -- decode percent-encoded octets of unresserved chars -- capitalize letters in escape sequences uri_safe_decode_split(self) -- use http as default scheme if not self.scheme and self.authority then self.scheme = 'http' end -- scheme and host are not case sensitive if self.scheme then self.scheme = string.lower(self.scheme) end if self.host then self.host = string.lower(self.host) end -- remove default port if self.port and self.port == '80' then self.port = nil end -- add '/' to path if self.scheme == 'http' and (not self.path or self.path == '') then self.path = '/' end -- normalize path according to rfc 3986 if self.path then self.path = remove_dot_segments(self.path) end return self end function module.uri.split(uri) return HttpUriSplit:new(uri) end function module.uri.normalize(uri) local splitted_uri = HttpUriSplit:new(uri) splitted_uri:normalize() return tostring(splitted_uri) end -- Cookie slitter object local HttpCookiesSplit = class.class('HttpCookiesSplit') function HttpCookiesSplit.method:__init(cookie_line) if cookie_line then string.gsub(cookie_line, '([^=;]+)=([^;]*);?', function(p, q) self[p] = q return '' end) end end function HttpCookiesSplit.method:__tostring() assert(self) local cookie = {} for k, v in pairs(self) do local ck = {} table.insert(ck, k) table.insert(ck, v) table.insert(cookie, table.concat(ck, '=')) end return table.concat(cookie, ';') end function module.cookies.split(cookie_line) return HttpCookiesSplit:new(cookie_line) end return module
mpl-2.0
MmxBoy/mmxanti2
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
Crazy-Duck/junglenational
game/dota_addons/junglenational/scripts/vscripts/internal/junglenational.lua
1
10040
-- This function initializes the game mode and is called before anyone loads into the game -- It can be used to pre-initialize any values/tables that will be needed later function JungleNational:_InitJungleNational() if JungleNational._reentrantCheck then return end -- Setup rules GameRules:SetHeroRespawnEnabled( ENABLE_HERO_RESPAWN ) GameRules:SetUseUniversalShopMode( UNIVERSAL_SHOP_MODE ) GameRules:SetSameHeroSelectionEnabled( ALLOW_SAME_HERO_SELECTION ) GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME ) GameRules:SetPreGameTime( PRE_GAME_TIME) GameRules:SetPostGameTime( POST_GAME_TIME ) GameRules:SetTreeRegrowTime( TREE_REGROW_TIME ) GameRules:SetUseCustomHeroXPValues ( USE_CUSTOM_XP_VALUES ) GameRules:SetGoldPerTick(GOLD_PER_TICK) GameRules:SetGoldTickTime(GOLD_TICK_TIME) GameRules:SetRuneSpawnTime(RUNE_SPAWN_TIME) GameRules:SetUseBaseGoldBountyOnHeroes(USE_STANDARD_HERO_GOLD_BOUNTY) GameRules:SetHeroMinimapIconScale( MINIMAP_ICON_SIZE ) GameRules:SetCreepMinimapIconScale( MINIMAP_CREEP_ICON_SIZE ) GameRules:SetRuneMinimapIconScale( MINIMAP_RUNE_ICON_SIZE ) GameRules:SetFirstBloodActive( ENABLE_FIRST_BLOOD ) GameRules:SetHideKillMessageHeaders( HIDE_KILL_BANNERS ) GameRules:SetCustomGameEndDelay( GAME_END_DELAY ) GameRules:SetCustomVictoryMessageDuration( VICTORY_MESSAGE_DURATION ) GameRules:SetStartingGold( STARTING_GOLD ) if SKIP_TEAM_SETUP then GameRules:SetCustomGameSetupAutoLaunchDelay( 0 ) GameRules:LockCustomGameSetupTeamAssignment( true ) GameRules:EnableCustomGameSetupAutoLaunch( true ) else GameRules:SetCustomGameSetupAutoLaunchDelay( AUTO_LAUNCH_DELAY ) GameRules:LockCustomGameSetupTeamAssignment( LOCK_TEAM_SETUP ) GameRules:EnableCustomGameSetupAutoLaunch( ENABLE_AUTO_LAUNCH ) end -- This is multiteam configuration stuff if USE_AUTOMATIC_PLAYERS_PER_TEAM then local num = math.floor(10 / MAX_NUMBER_OF_TEAMS) local count = 0 for team,number in pairs(TEAM_COLORS) do if count >= MAX_NUMBER_OF_TEAMS then GameRules:SetCustomGameTeamMaxPlayers(team, 0) else GameRules:SetCustomGameTeamMaxPlayers(team, num) end count = count + 1 end else local count = 0 for team,number in pairs(CUSTOM_TEAM_PLAYER_COUNT) do if count >= MAX_NUMBER_OF_TEAMS then GameRules:SetCustomGameTeamMaxPlayers(team, 0) else GameRules:SetCustomGameTeamMaxPlayers(team, number) end count = count + 1 end end if USE_CUSTOM_TEAM_COLORS then for team,color in pairs(TEAM_COLORS) do SetTeamCustomHealthbarColor(team, color[1], color[2], color[3]) end end DebugPrint('[JUNGLENATIONAL] GameRules set') --InitLogFile( "log/junglenational.txt","") -- Event Hooks -- All of these events can potentially be fired by the game, though only the uncommented ones have had -- Functions supplied for them. If you are interested in the other events, you can uncomment the -- ListenToGameEvent line and add a function to handle the event ListenToGameEvent('dota_player_gained_level', Dynamic_Wrap(JungleNational, 'OnPlayerLevelUp'), self) ListenToGameEvent('dota_ability_channel_finished', Dynamic_Wrap(JungleNational, 'OnAbilityChannelFinished'), self) ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(JungleNational, 'OnPlayerLearnedAbility'), self) ListenToGameEvent('entity_killed', Dynamic_Wrap(JungleNational, '_OnEntityKilled'), self) ListenToGameEvent('player_connect_full', Dynamic_Wrap(JungleNational, '_OnConnectFull'), self) ListenToGameEvent('player_disconnect', Dynamic_Wrap(JungleNational, 'OnDisconnect'), self) ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(JungleNational, 'OnItemPurchased'), self) ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(JungleNational, 'OnItemPickedUp'), self) ListenToGameEvent('last_hit', Dynamic_Wrap(JungleNational, 'OnLastHit'), self) ListenToGameEvent('dota_non_player_used_ability', Dynamic_Wrap(JungleNational, 'OnNonPlayerUsedAbility'), self) ListenToGameEvent('player_changename', Dynamic_Wrap(JungleNational, 'OnPlayerChangedName'), self) ListenToGameEvent('dota_rune_activated_server', Dynamic_Wrap(JungleNational, 'OnRuneActivated'), self) ListenToGameEvent('dota_player_take_tower_damage', Dynamic_Wrap(JungleNational, 'OnPlayerTakeTowerDamage'), self) ListenToGameEvent('tree_cut', Dynamic_Wrap(JungleNational, 'OnTreeCut'), self) ListenToGameEvent('entity_hurt', Dynamic_Wrap(JungleNational, 'OnEntityHurt'), self) ListenToGameEvent('player_connect', Dynamic_Wrap(JungleNational, 'PlayerConnect'), self) ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(JungleNational, 'OnAbilityUsed'), self) ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(JungleNational, '_OnGameRulesStateChange'), self) ListenToGameEvent('npc_spawned', Dynamic_Wrap(JungleNational, '_OnNPCSpawned'), self) ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(JungleNational, 'OnPlayerPickHero'), self) ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(JungleNational, 'OnTeamKillCredit'), self) ListenToGameEvent("player_reconnected", Dynamic_Wrap(JungleNational, 'OnPlayerReconnect'), self) ListenToGameEvent("dota_illusions_created", Dynamic_Wrap(JungleNational, 'OnIllusionsCreated'), self) ListenToGameEvent("dota_item_combined", Dynamic_Wrap(JungleNational, 'OnItemCombined'), self) ListenToGameEvent("dota_player_begin_cast", Dynamic_Wrap(JungleNational, 'OnAbilityCastBegins'), self) ListenToGameEvent("dota_tower_kill", Dynamic_Wrap(JungleNational, 'OnTowerKill'), self) ListenToGameEvent("dota_player_selected_custom_team", Dynamic_Wrap(JungleNational, 'OnPlayerSelectedCustomTeam'), self) ListenToGameEvent("dota_npc_goal_reached", Dynamic_Wrap(JungleNational, 'OnNPCGoalReached'), self) ListenToGameEvent("player_chat", Dynamic_Wrap(JungleNational, 'OnPlayerChat'), self) --ListenToGameEvent("dota_tutorial_shop_toggled", Dynamic_Wrap(JungleNational, 'OnShopToggled'), self) --ListenToGameEvent('player_spawn', Dynamic_Wrap(JungleNational, 'OnPlayerSpawn'), self) --ListenToGameEvent('dota_unit_event', Dynamic_Wrap(JungleNational, 'OnDotaUnitEvent'), self) --ListenToGameEvent('nommed_tree', Dynamic_Wrap(JungleNational, 'OnPlayerAteTree'), self) --ListenToGameEvent('player_completed_game', Dynamic_Wrap(JungleNational, 'OnPlayerCompletedGame'), self) --ListenToGameEvent('dota_match_done', Dynamic_Wrap(JungleNational, 'OnDotaMatchDone'), self) --ListenToGameEvent('dota_combatlog', Dynamic_Wrap(JungleNational, 'OnCombatLogEvent'), self) --ListenToGameEvent('dota_player_killed', Dynamic_Wrap(JungleNational, 'OnPlayerKilled'), self) --ListenToGameEvent('player_team', Dynamic_Wrap(JungleNational, 'OnPlayerTeam'), self) --[[This block is only used for testing events handling in the event that Valve adds more in the future Convars:RegisterCommand('events_test', function() JungleNational:StartEventTest() end, "events test", 0)]] local spew = 0 if JUNGLENATIONAL_DEBUG_SPEW then spew = 1 end Convars:RegisterConvar('junglenational_spew', tostring(spew), 'Set to 1 to start spewing junglenational debug info. Set to 0 to disable.', 0) -- Change random seed local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '^0+','') math.randomseed(tonumber(timeTxt)) -- Initialized tables for tracking state self.bSeenWaitForPlayers = false self.vUserIds = {} DebugPrint('[JUNGLENATIONAL] Done loading JungleNational junglenational!\n\n') JungleNational._reentrantCheck = true JungleNational:InitJungleNational() JungleNational._reentrantCheck = false end mode = nil -- This function is called as the first player loads and sets up the JungleNational parameters function JungleNational:_CaptureJungleNational() if mode == nil then -- Set JungleNational parameters mode = GameRules:GetGameModeEntity() mode:SetRecommendedItemsDisabled( RECOMMENDED_BUILDS_DISABLED ) mode:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE ) mode:SetCustomBuybackCostEnabled( CUSTOM_BUYBACK_COST_ENABLED ) mode:SetCustomBuybackCooldownEnabled( CUSTOM_BUYBACK_COOLDOWN_ENABLED ) mode:SetBuybackEnabled( BUYBACK_ENABLED ) mode:SetTopBarTeamValuesOverride ( USE_CUSTOM_TOP_BAR_VALUES ) mode:SetTopBarTeamValuesVisible( TOP_BAR_VISIBLE ) mode:SetUseCustomHeroLevels ( USE_CUSTOM_HERO_LEVELS ) mode:SetCustomHeroMaxLevel ( MAX_LEVEL ) mode:SetCustomXPRequiredToReachNextLevel( XP_PER_LEVEL_TABLE ) mode:SetBotThinkingEnabled( USE_STANDARD_DOTA_BOT_THINKING ) mode:SetTowerBackdoorProtectionEnabled( ENABLE_TOWER_BACKDOOR_PROTECTION ) mode:SetFogOfWarDisabled(DISABLE_FOG_OF_WAR_ENTIRELY) mode:SetGoldSoundDisabled( DISABLE_GOLD_SOUNDS ) mode:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH ) mode:SetAlwaysShowPlayerInventory( SHOW_ONLY_PLAYER_INVENTORY ) mode:SetAnnouncerDisabled( DISABLE_ANNOUNCER ) if FORCE_PICKED_HERO ~= nil then mode:SetCustomGameForceHero( FORCE_PICKED_HERO ) end mode:SetFixedRespawnTime( FIXED_RESPAWN_TIME ) mode:SetFountainConstantManaRegen( FOUNTAIN_CONSTANT_MANA_REGEN ) mode:SetFountainPercentageHealthRegen( FOUNTAIN_PERCENTAGE_HEALTH_REGEN ) mode:SetFountainPercentageManaRegen( FOUNTAIN_PERCENTAGE_MANA_REGEN ) mode:SetLoseGoldOnDeath( LOSE_GOLD_ON_DEATH ) mode:SetMaximumAttackSpeed( MAXIMUM_ATTACK_SPEED ) mode:SetMinimumAttackSpeed( MINIMUM_ATTACK_SPEED ) mode:SetStashPurchasingDisabled ( DISABLE_STASH_PURCHASING ) for rune, spawn in pairs(ENABLED_RUNES) do mode:SetRuneEnabled(rune, spawn) end mode:SetUnseenFogOfWarEnabled( USE_UNSEEN_FOG_OF_WAR ) mode:SetDaynightCycleDisabled( DISABLE_DAY_NIGHT_CYCLE ) mode:SetKillingSpreeAnnouncerDisabled( DISABLE_KILLING_SPREE_ANNOUNCER ) mode:SetStickyItemDisabled( DISABLE_STICKY_ITEM ) self:OnFirstPlayerLoaded() end end
mit
project-zerus/thrift
lib/lua/TJsonProtocol.lua
42
18656
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"), you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'TProtocol' require 'libluabpack' require 'libluabitwise' TJSONProtocol = __TObject.new(TProtocolBase, { __type = 'TJSONProtocol', THRIFT_JSON_PROTOCOL_VERSION = 1, jsonContext = {}, jsonContextVal = {first = true, colon = true, ttype = 2, null = true}, jsonContextIndex = 1, hasReadByte = "" }) TTypeToString = {} TTypeToString[TType.BOOL] = "tf" TTypeToString[TType.BYTE] = "i8" TTypeToString[TType.I16] = "i16" TTypeToString[TType.I32] = "i32" TTypeToString[TType.I64] = "i64" TTypeToString[TType.DOUBLE] = "dbl" TTypeToString[TType.STRING] = "str" TTypeToString[TType.STRUCT] = "rec" TTypeToString[TType.LIST] = "lst" TTypeToString[TType.SET] = "set" TTypeToString[TType.MAP] = "map" StringToTType = { tf = TType.BOOL, i8 = TType.BYTE, i16 = TType.I16, i32 = TType.I32, i64 = TType.I64, dbl = TType.DOUBLE, str = TType.STRING, rec = TType.STRUCT, map = TType.MAP, set = TType.SET, lst = TType.LIST } JSONNode = { ObjectBegin = '{', ObjectEnd = '}', ArrayBegin = '[', ArrayEnd = ']', PairSeparator = ':', ElemSeparator = ',', Backslash = '\\', StringDelimiter = '"', ZeroChar = '0', EscapeChar = 'u', Nan = 'NaN', Infinity = 'Infinity', NegativeInfinity = '-Infinity', EscapeChars = "\"\\bfnrt", EscapePrefix = "\\u00" } EscapeCharVals = { '"', '\\', '\b', '\f', '\n', '\r', '\t' } JSONCharTable = { --0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0, 98,116,110, 0,102,114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,34, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, } -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- encoding function base64_encode(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding function base64_decode(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end function TJSONProtocol:resetContext() self.jsonContext = {} self.jsonContextVal = {first = true, colon = true, ttype = 2, null = true} self.jsonContextIndex = 1 end function TJSONProtocol:contextPush(context) self.jsonContextIndex = self.jsonContextIndex + 1 self.jsonContext[self.jsonContextIndex] = self.jsonContextVal self.jsonContextVal = context end function TJSONProtocol:contextPop() self.jsonContextVal = self.jsonContext[self.jsonContextIndex] self.jsonContextIndex = self.jsonContextIndex - 1 end function TJSONProtocol:escapeNum() if self.jsonContextVal.ttype == 1 then return self.jsonContextVal.colon else return false end end function TJSONProtocol:writeElemSeparator() if self.jsonContextVal.null then return end if self.jsonContextVal.first then self.jsonContextVal.first = false else if self.jsonContextVal.ttype == 1 then if self.jsonContextVal.colon then self.trans:write(JSONNode.PairSeparator) self.jsonContextVal.colon = false else self.trans:write(JSONNode.ElemSeparator) self.jsonContextVal.colon = true end else self.trans:write(JSONNode.ElemSeparator) end end end function TJSONProtocol:hexChar(val) val = libluabitwise.band(val, 0x0f) if val < 10 then return val + 48 else return val + 87 end end function TJSONProtocol:writeJSONEscapeChar(ch) self.trans:write(JSONNode.EscapePrefix) local outCh = hexChar(libluabitwise.shiftr(ch, 4)) local buff = libluabpack.bpack('c', outCh) self.trans:write(buff) outCh = hexChar(ch) buff = libluabpack.bpack('c', outCh) self.trans:write(buff) end function TJSONProtocol:writeJSONChar(byte) ch = string.byte(byte) if ch >= 0x30 then if ch == JSONNode.Backslash then self.trans:write(JSONNode.Backslash) self.trans:write(JSONNode.Backslash) else self.trans:write(byte) end else local outCh = JSONCharTable[ch+1] if outCh == 1 then self.trans:write(byte) elseif outCh > 1 then self.trans:write(JSONNode.Backslash) local buff = libluabpack.bpack('c', outCh) self.trans:write(buff) else self:writeJSONEscapeChar(ch) end end end function TJSONProtocol:writeJSONString(str) self:writeElemSeparator() self.trans:write(JSONNode.StringDelimiter) -- TODO escape special characters local length = string.len(str) local ii = 1 while ii <= length do self:writeJSONChar(string.sub(str, ii, ii)) ii = ii + 1 end self.trans:write(JSONNode.StringDelimiter) end function TJSONProtocol:writeJSONBase64(str) self:writeElemSeparator() self.trans:write(JSONNode.StringDelimiter) local length = string.len(str) local offset = 1 while length >= 3 do -- Encode 3 bytes at a time local bytes = base64_encode(string.sub(str, offset, offset+3)) self.trans:write(bytes) length = length - 3 offset = offset + 3 end if length > 0 then local bytes = base64_encode(string.sub(str, offset, offset+length)) self.trans:write(bytes) end self.trans:write(JSONNode.StringDelimiter) end function TJSONProtocol:writeJSONInteger(num) self:writeElemSeparator() if self:escapeNum() then self.trans:write(JSONNode.StringDelimiter) end local numstr = "" .. num numstr = string.sub(numstr, string.find(numstr, "^[+-]?%d+")) self.trans:write(numstr) if self:escapeNum() then self.trans:write(JSONNode.StringDelimiter) end end function TJSONProtocol:writeJSONDouble(dub) self:writeElemSeparator() local val = "" .. dub local prefix = string.sub(val, 1, 1) local special = false if prefix == 'N' or prefix == 'n' then val = JSONNode.Nan special = true elseif prefix == 'I' or prefix == 'i' then val = JSONNode.Infinity special = true elseif prefix == '-' then local secondByte = string.sub(val, 2, 2) if secondByte == 'I' or secondByte == 'i' then val = JSONNode.NegativeInfinity special = true end end if special or self:escapeNum() then self.trans:write(JSONNode.StringDelimiter) end self.trans:write(val) if special or self:escapeNum() then self.trans:write(JSONNode.StringDelimiter) end end function TJSONProtocol:writeJSONObjectBegin() self:writeElemSeparator() self.trans:write(JSONNode.ObjectBegin) self:contextPush({first = true, colon = true, ttype = 1, null = false}) end function TJSONProtocol:writeJSONObjectEnd() self:contextPop() self.trans:write(JSONNode.ObjectEnd) end function TJSONProtocol:writeJSONArrayBegin() self:writeElemSeparator() self.trans:write(JSONNode.ArrayBegin) self:contextPush({first = true, colon = true, ttype = 2, null = false}) end function TJSONProtocol:writeJSONArrayEnd() self:contextPop() self.trans:write(JSONNode.ArrayEnd) end function TJSONProtocol:writeMessageBegin(name, ttype, seqid) self:resetContext() self:writeJSONArrayBegin() self:writeJSONInteger(TJSONProtocol.THRIFT_JSON_PROTOCOL_VERSION) self:writeJSONString(name) self:writeJSONInteger(ttype) self:writeJSONInteger(seqid) end function TJSONProtocol:writeMessageEnd() self:writeJSONArrayEnd() end function TJSONProtocol:writeStructBegin(name) self:writeJSONObjectBegin() end function TJSONProtocol:writeStructEnd() self:writeJSONObjectEnd() end function TJSONProtocol:writeFieldBegin(name, ttype, id) self:writeJSONInteger(id) self:writeJSONObjectBegin() self:writeJSONString(TTypeToString[ttype]) end function TJSONProtocol:writeFieldEnd() self:writeJSONObjectEnd() end function TJSONProtocol:writeFieldStop() end function TJSONProtocol:writeMapBegin(ktype, vtype, size) self:writeJSONArrayBegin() self:writeJSONString(TTypeToString[ktype]) self:writeJSONString(TTypeToString[vtype]) self:writeJSONInteger(size) return self:writeJSONObjectBegin() end function TJSONProtocol:writeMapEnd() self:writeJSONObjectEnd() self:writeJSONArrayEnd() end function TJSONProtocol:writeListBegin(etype, size) self:writeJSONArrayBegin() self:writeJSONString(TTypeToString[etype]) self:writeJSONInteger(size) end function TJSONProtocol:writeListEnd() self:writeJSONArrayEnd() end function TJSONProtocol:writeSetBegin(etype, size) self:writeJSONArrayBegin() self:writeJSONString(TTypeToString[etype]) self:writeJSONInteger(size) end function TJSONProtocol:writeSetEnd() self:writeJSONArrayEnd() end function TJSONProtocol:writeBool(bool) if bool then self:writeJSONInteger(1) else self:writeJSONInteger(0) end end function TJSONProtocol:writeByte(byte) local buff = libluabpack.bpack('c', byte) local val = libluabpack.bunpack('c', buff) self:writeJSONInteger(val) end function TJSONProtocol:writeI16(i16) local buff = libluabpack.bpack('s', i16) local val = libluabpack.bunpack('s', buff) self:writeJSONInteger(val) end function TJSONProtocol:writeI32(i32) local buff = libluabpack.bpack('i', i32) local val = libluabpack.bunpack('i', buff) self:writeJSONInteger(val) end function TJSONProtocol:writeI64(i64) local buff = libluabpack.bpack('l', i64) local val = libluabpack.bunpack('l', buff) self:writeJSONInteger(tostring(val)) end function TJSONProtocol:writeDouble(dub) self:writeJSONDouble(string.format("%.16f", dub)) end function TJSONProtocol:writeString(str) self:writeJSONString(str) end function TJSONProtocol:writeBinary(str) -- Should be utf-8 self:writeJSONBase64(str) end function TJSONProtocol:readJSONSyntaxChar(ch) local ch2 = "" if self.hasReadByte ~= "" then ch2 = self.hasReadByte self.hasReadByte = "" else ch2 = self.trans:readAll(1) end if ch2 ~= ch then terror(TProtocolException:new{message = "Expected ".. ch .. ", got " .. ch2}) end end function TJSONProtocol:readElemSeparator() if self.jsonContextVal.null then return end if self.jsonContextVal.first then self.jsonContextVal.first = false else if self.jsonContextVal.ttype == 1 then if self.jsonContextVal.colon then self:readJSONSyntaxChar(JSONNode.PairSeparator) self.jsonContextVal.colon = false else self:readJSONSyntaxChar(JSONNode.ElemSeparator) self.jsonContextVal.colon = true end else self:readJSONSyntaxChar(JSONNode.ElemSeparator) end end end function TJSONProtocol:hexVal(ch) local val = string.byte(ch) if val >= 48 and val <= 57 then return val - 48 elseif val >= 97 and val <= 102 then return val - 87 else terror(TProtocolException:new{message = "Expected hex val ([0-9a-f]); got " .. ch}) end end function TJSONProtocol:readJSONEscapeChar(ch) self:readJSONSyntaxChar(JSONNode.ZeroChar) self:readJSONSyntaxChar(JSONNode.ZeroChar) local b1 = self.trans:readAll(1) local b2 = self.trans:readAll(1) return libluabitwise.shiftl(self:hexVal(b1), 4) + self:hexVal(b2) end function TJSONProtocol:readJSONString() self:readElemSeparator() self:readJSONSyntaxChar(JSONNode.StringDelimiter) local result = "" while true do local ch = self.trans:readAll(1) if ch == JSONNode.StringDelimiter then break end if ch == JSONNode.Backslash then ch = self.trans:readAll(1) if ch == JSONNode.EscapeChar then self:readJSONEscapeChar(ch) else local pos, _ = string.find(JSONNode.EscapeChars, ch) if pos == nil then terror(TProtocolException:new{message = "Expected control char, got " .. ch}) end ch = EscapeCharVals[pos] end end result = result .. ch end return result end function TJSONProtocol:readJSONBase64() local result = self:readJSONString() local length = string.len(result) local str = "" local offset = 1 while length >= 4 do local bytes = string.sub(result, offset, offset+4) str = str .. base64_decode(bytes) offset = offset + 4 length = length - 4 end if length >= 0 then str = str .. base64_decode(string.sub(result, offset, offset + length)) end return str end function TJSONProtocol:readJSONNumericChars() local result = "" while true do local ch = self.trans:readAll(1) if string.find(ch, '[-+0-9.Ee]') then result = result .. ch else self.hasReadByte = ch break end end return result end function TJSONProtocol:readJSONLongInteger() self:readElemSeparator() if self:escapeNum() then self:readJSONSyntaxChar(JSONNode.StringDelimiter) end local result = self:readJSONNumericChars() if self:escapeNum() then self:readJSONSyntaxChar(JSONNode.StringDelimiter) end return result end function TJSONProtocol:readJSONInteger() return tonumber(self:readJSONLongInteger()) end function TJSONProtocol:readJSONDouble() self:readElemSeparator() local delimiter = self.trans:readAll(1) local num = 0.0 if delimiter == JSONNode.StringDelimiter then local str = self:readJSONString() if str == JSONNode.Nan then num = 1.0 elseif str == JSONNode.Infinity then num = math.maxinteger elseif str == JSONNode.NegativeInfinity then num = math.mininteger else num = tonumber(str) end else if self:escapeNum() then self:readJSONSyntaxChar(JSONNode.StringDelimiter) end local result = self:readJSONNumericChars() num = tonumber(delimiter.. result) end return num end function TJSONProtocol:readJSONObjectBegin() self:readElemSeparator() self:readJSONSyntaxChar(JSONNode.ObjectBegin) self:contextPush({first = true, colon = true, ttype = 1, null = false}) end function TJSONProtocol:readJSONObjectEnd() self:readJSONSyntaxChar(JSONNode.ObjectEnd) self:contextPop() end function TJSONProtocol:readJSONArrayBegin() self:readElemSeparator() self:readJSONSyntaxChar(JSONNode.ArrayBegin) self:contextPush({first = true, colon = true, ttype = 2, null = false}) end function TJSONProtocol:readJSONArrayEnd() self:readJSONSyntaxChar(JSONNode.ArrayEnd) self:contextPop() end function TJSONProtocol:readMessageBegin() self:resetContext() self:readJSONArrayBegin() local version = self:readJSONInteger() if version ~= self.THRIFT_JSON_PROTOCOL_VERSION then terror(TProtocolException:new{message = "Message contained bad version."}) end local name = self:readJSONString() local ttype = self:readJSONInteger() local seqid = self:readJSONInteger() return name, ttype, seqid end function TJSONProtocol:readMessageEnd() self:readJSONArrayEnd() end function TJSONProtocol:readStructBegin() self:readJSONObjectBegin() return nil end function TJSONProtocol:readStructEnd() self:readJSONObjectEnd() end function TJSONProtocol:readFieldBegin() local ttype = TType.STOP local id = 0 local ch = self.trans:readAll(1) self.hasReadByte = ch if ch ~= JSONNode.ObjectEnd then id = self:readJSONInteger() self:readJSONObjectBegin() local typeName = self:readJSONString() ttype = StringToTType[typeName] end return nil, ttype, id end function TJSONProtocol:readFieldEnd() self:readJSONObjectEnd() end function TJSONProtocol:readMapBegin() self:readJSONArrayBegin() local typeName = self:readJSONString() local ktype = StringToTType[typeName] typeName = self:readJSONString() local vtype = StringToTType[typeName] local size = self:readJSONInteger() self:readJSONObjectBegin() return ktype, vtype, size end function TJSONProtocol:readMapEnd() self:readJSONObjectEnd() self:readJSONArrayEnd() end function TJSONProtocol:readListBegin() self:readJSONArrayBegin() local typeName = self:readJSONString() local etype = StringToTType[typeName] local size = self:readJSONInteger() return etype, size end function TJSONProtocol:readListEnd() return self:readJSONArrayEnd() end function TJSONProtocol:readSetBegin() return self:readListBegin() end function TJSONProtocol:readSetEnd() return self:readJSONArrayEnd() end function TJSONProtocol:readBool() local result = self:readJSONInteger() if result == 1 then return true else return false end end function TJSONProtocol:readByte() local result = self:readJSONInteger() if result >= 256 then terror(TProtocolException:new{message = "UnExpected Byte " .. result}) end return result end function TJSONProtocol:readI16() return self:readJSONInteger() end function TJSONProtocol:readI32() return self:readJSONInteger() end function TJSONProtocol:readI64() local long = liblualongnumber.new return long(self:readJSONLongInteger()) end function TJSONProtocol:readDouble() return self:readJSONDouble() end function TJSONProtocol:readString() return self:readJSONString() end function TJSONProtocol:readBinary() return self:readJSONBase64() end TJSONProtocolFactory = TProtocolFactory:new{ __type = 'TJSONProtocolFactory', } function TJSONProtocolFactory:getProtocol(trans) -- TODO Enforce that this must be a transport class (ie not a bool) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TJSONProtocol:new{ trans = trans } end
apache-2.0
comitservice/nodmcu
examples/telnet.lua
5
1067
print("====Wicon, a LUA console over wifi.==========") print("Author: openthings@163.com. copyright&GPL V2.") print("Last modified 2014-11-19. V0.2") print("Wicon Server starting ......") function startServer() print("Wifi AP connected. Wicon IP:") print(wifi.sta.getip()) sv=net.createServer(net.TCP, 180) sv:listen(8080, function(conn) print("Wifi console connected.") function s_output(str) if (conn~=nil) then conn:send(str) end end node.output(s_output,0) conn:on("receive", function(conn, pl) node.input(pl) if (conn==nil) then print("conn is nil.") end end) conn:on("disconnection",function(conn) node.output(nil) end) end) print("Wicon Server running at :8080") print("===Now,Using xcon_tcp logon and input LUA.====") end tmr.alarm(1000, 1, function() if wifi.sta.getip()=="0.0.0.0" then print("Connect AP, Waiting...") else startServer() tmr.stop() end end)
mit
weitjong/Urho3D
bin/Data/LuaScripts/09_MultipleViewports.lua
24
13081
-- Multiple viewports example. -- This sample demonstrates: -- - Setting up two viewports with two separate cameras -- - Adding post processing effects to a viewport's render path and toggling them require "LuaScripts/Utilities/Sample" local rearCameraNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewports for displaying the scene SetupViewports() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- 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 some mushrooms local NUM_MUSHROOMS = 240 for i = 1, NUM_MUSHROOMS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true end -- 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 NUM_BOXES = 20 for i = 1, NUM_BOXES do local boxNode = scene_: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 the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Parent the rear camera node to the front camera node and turn it 180 degrees to face backward -- Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles rearCameraNode = cameraNode:CreateChild("RearCamera") rearCameraNode:Rotate(Quaternion(180.0, Vector3(0.0, 1.0, 0.0))) local rearCamera = rearCameraNode:CreateComponent("Camera") rearCamera.farClip = 300.0 -- Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's -- "view override flags" for this. We could also disable eg. shadows or force low material quality -- if we wanted rearCamera.viewOverrideFlags = VO_DISABLE_OCCLUSION -- Set an initial position for the front camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys and mouse to move\n".. "B to toggle bloom, F to toggle FXAA\n".. "Space to toggle debug geometry\n" 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 SetupViewports() renderer.numViewports = 2 -- Set up the front camera viewport local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) -- Clone the default render path so that we do not interfere with the other viewport, then add -- bloom and FXAA post process effects to the front viewport. Render path commands can be tagged -- for example with the effect name to allow easy toggling on and off. We start with the effects -- disabled. local effectRenderPath = viewport:GetRenderPath():Clone() effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/Bloom.xml")) effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/FXAA2.xml")) -- Make the bloom mixing parameter more pronounced effectRenderPath:SetShaderParameter("BloomMix", Variant(Vector2(0.9, 0.6))) effectRenderPath:SetEnabled("Bloom", false) effectRenderPath:SetEnabled("FXAA2", false) viewport:SetRenderPath(effectRenderPath) -- Set up the rear camera viewport on top of the front view ("rear view mirror") -- The viewport index must be greater in that case, otherwise the view would be left behind local rearViewport = Viewport:new(scene_, rearCameraNode:GetComponent("Camera"), IntRect(graphics.width * 2 / 3, 32, graphics.width - 32, graphics.height / 3)) renderer:SetViewport(1, rearViewport) 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") end function MoveCamera(timeStep) -- 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 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) -- 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 -- Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected local effectRenderPath = renderer:GetViewport(0).renderPath if input:GetKeyPress(KEY_B) then effectRenderPath:ToggleEnabled("Bloom") end if input:GetKeyPress(KEY_F) then effectRenderPath:ToggleEnabled("FXAA2") end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug 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 draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion if drawDebug then renderer:DrawDebugGeometry(false) 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=\"FXAA\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"F\" />" .. " </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\">Bloom</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"B\" />" .. " </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
gtaylormb/fpga_nes
sw/scripts/cpu_asm.lua
3
6666
---------------------------------------------------------------------------------------------------- -- Script: cpu_asm.lua -- Description: CPU test. Execute externally built asm programs from the ../asm directory. Useful -- for more detailed directed tests, especially since cpu_rand doesn't cover branches, -- jumps, or subroutines. ---------------------------------------------------------------------------------------------------- dofile("../scripts/inc/nesdbg.lua") local results = {} local asmTbl = { -- trivial.asm { file = "trivial.prg", subTestTbl = { { initState = { ac = 0x00, }, resultState = { ac = 0xBB, } }, } }, -- sum_array.asm { file = "sum_array.prg", subTestTbl = { { initState = { addrs = { 0x0000, 0x0001, 0x0002, 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306 }, vals = { 0x00, 0x03, 0x07, 250, 136, 66, 45, 26, 92, 4 } }, resultState = { addrs = { 0x0004, 0x0005 }, vals = { 0x6B, 0x02 } } }, { initState = { addrs = { 0x0000, 0x0001, 0x0002, 0x0500, 0x0501, 0x0502, 0x0503, 0x0504, 0x0505, 0x0506, 0x0507, 0x0508, 0x0509, 0x050A, 0x050B, 0x050C, 0x050D, 0x050E, 0x050F, 0x0510, 0x0511, 0x0512, 0x0513, 0x0514, 0x0515, 0x0516, 0x0517, 0x0518, 0x0519, 0x051A, 0x051B, 0x051C, 0x051D, 0x051E, 0x051F, 0x0520, 0x0521, 0x0522, 0x0523, 0x0524 }, vals = { 0x00, 0x05, 0x25, 194, 141, 101, 143, 201, 253, 185, 202, 201, 3, 25, 28, 172, 12, 156, 242, 134, 184, 150, 142, 6, 245, 169, 236, 58, 242, 71, 44, 95, 63, 107, 47, 181, 238, 38, 14, 210 } }, resultState = { addrs = { 0x0004, 0x0005 }, vals = { 0x45, 0x13 } } }, } }, -- bubble8.asm { file = "bubble8.prg", subTestTbl = { { initState = { addrs = { 0x0030, 0x0031, 0x0600, 0x0601, 0x0602, 0x0603, 0x0604, 0x0605, 0x0606, 0x0607 }, vals = { 0x00, 0x06, 0x07, 223, 176, 32, 45, 194, 87, 244 } }, resultState = { addrs = { 0x0601, 0x0602, 0x0603, 0x0604, 0x0605, 0x0606, 0x0607 }, vals = { 32, 45, 87, 176, 194, 223, 244 } } }, { initState = { addrs = { 0x0030, 0x0031, 0x0500, 0x0501, 0x0502, 0x0503, 0x0504, 0x0505, 0x0506, 0x0507, 0x0508, 0x0509, 0x050A, 0x050B, 0x050C, 0x050D, 0x050E, 0x050F, 0x0510, 0x0511, 0x0512, 0x0513, 0x0514, 0x0515, 0x0516, 0x0517, 0x0518, 0x0519, 0x051A, 0x051B, 0x051C, 0x051D, 0x051E, 0x051F, 0x0520, 0x0521, 0x0522, 0x0523, 0x0524 }, vals = { 0x00, 0x05, 0x24, 141, 101, 143, 201, 253, 185, 202, 201, 3, 25, 28, 172, 12, 156, 242, 134, 184, 150, 142, 6, 245, 169, 236, 58, 242, 71, 44, 95, 63, 107, 47, 181, 238, 38, 14, 210 } }, resultState = { addrs = { 0x0501, 0x0502, 0x0503, 0x0504, 0x0505, 0x0506, 0x0507, 0x0508, 0x0509, 0x050A, 0x050B, 0x050C, 0x050D, 0x050E, 0x050F, 0x0510, 0x0511, 0x0512, 0x0513, 0x0514, 0x0515, 0x0516, 0x0517, 0x0518, 0x0519, 0x051A, 0x051B, 0x051C, 0x051D, 0x051E, 0x051F, 0x0520, 0x0521, 0x0522, 0x0523, 0x0524 }, vals = { 3, 6, 12, 14, 25, 28, 38, 44, 47, 58, 63, 71, 95, 101, 107, 134, 141, 142, 143, 150, 156, 169, 172, 181, 184, 185, 201, 201, 202, 210, 236, 238, 242, 242, 245, 253 } } }, } }, -- bubble16.asm { file = "bubble16.prg", subTestTbl = { { initState = { addrs = { 0x0030, 0x0031, 0x0600, 0x0601, 0x0602, 0x0603, 0x0604, 0x0605, 0x0606, 0x0607, 0x0608, 0x0609, 0x060A, 0x060B, 0x060C, 0x060D, 0x060E, 0x060F, 0x0610, 0x0611, 0x0612 }, vals = { 0x00, 0x06, 0x12, 90, 178, 219, 94, 23, 26, 119, 94, 105, 155, 221, 247, 105, 55, 169, 57, 228, 237 } }, resultState = { addrs = { 0x0601, 0x0602, 0x0603, 0x0604, 0x0605, 0x0606, 0x0607, 0x0608, 0x0609, 0x060A, 0x060B, 0x060C, 0x060D, 0x060E, 0x060F, 0x0610, 0x0611, 0x0612 }, vals = { 23, 26, 105, 55, 169, 57, 119, 94, 219, 94, 105, 155, 90, 178, 228, 237, 221, 247 } } }, } }, } local reportingSubTestIdx = 1 for asmIdx = 1, #asmTbl do local curAsm = asmTbl[asmIdx] print(curAsm.file .. "\n"); for subTestIdx = 1, #curAsm.subTestTbl do local curTest = curAsm.subTestTbl[subTestIdx] -- -- Set initial test state. -- if curTest.initState.ac ~= nil then SetAc(curTest.initState.ac) end if curTest.initState.addrs ~= nil then for addrIdx = 1, #curTest.initState.addrs do tempTbl = { curTest.initState.vals[addrIdx] } nesdbg.CpuMemWr(curTest.initState.addrs[addrIdx], 1, tempTbl) end end -- -- Load the ASM code and run the test. -- local startPc = nesdbg.LoadAsm(curAsm.file) SetPc(startPc) nesdbg.DbgRun() nesdbg.WaitForHlt() -- -- Check result. -- results[reportingSubTestIdx] = ScriptResult.Pass if curTest.resultState.ac ~= nil and curTest.resultState.ac ~= GetAc() then print("AC = " .. GetAc() .. ", expected " .. curTest.resultState.ac .. ".\n"); results[reportingSubTestIdx] = ScriptResult.Fail end if curTest.resultState.addrs ~= nil then for addrIdx = 1, #curTest.resultState.addrs do local val = nesdbg.CpuMemRd(curTest.resultState.addrs[addrIdx], 1) if val[1] ~= curTest.resultState.vals[addrIdx] then print("[" .. curTest.resultState.addrs[addrIdx] .. "] = " .. val[1] .. ", expected: " .. curTest.resultState.vals[addrIdx] .. "\n") results[reportingSubTestIdx] = ScriptResult.Fail break end end end print(" ") ReportSubTestResult(subTestIdx, results[reportingSubTestIdx]) reportingSubTestIdx = reportingSubTestIdx + 1 end end return ComputeOverallResult(results)
bsd-2-clause
allwenandashi/1
plugins/write.lua
2
28646
local function run(msg, matches) if #matches < 2 then return "بعد از این دستور، با قید یک فاصله کلمه یا جمله ی مورد نظر را جهت زیبا نویسی وارد کنید" end if string.len(matches[2]) > 20 then return "حداکثر حروف مجاز 20 کاراکتر انگلیسی و عدد است" end local font_base = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_" local font_hash = "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,0,1,2,3,4,5,6,7,8,9,.,_" local fonts = { "ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_", "α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴", "ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_", "Δ,Ɓ,C,D,Σ,F,G,H,I,J,Ƙ,L,Μ,∏,Θ,Ƥ,Ⴓ,Γ,Ѕ,Ƭ,Ʊ,Ʋ,Ш,Ж,Ψ,Z,λ,ϐ,ς,d,ε,ғ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_", "α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,0,9,8,7,6,5,4,3,2,1,.,_", "ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,‾", "A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴", "A̱,̱Ḇ,̱C̱,̱Ḏ,̱E̱,̱F̱,̱G̱,̱H̱,̱I̱,̱J̱,̱Ḵ,̱Ḻ,̱M̱,̱Ṉ,̱O̱,̱P̱,̱Q̱,̱Ṟ,̱S̱,̱Ṯ,̱U̱,̱V̱,̱W̱,̱X̱,̱Y̱,̱Ẕ,̱a̱,̱ḇ,̱c̱,̱ḏ,̱e̱,̱f̱,̱g̱,̱ẖ,̱i̱,̱j̱,̱ḵ,̱ḻ,̱m̱,̱ṉ,̱o̱,̱p̱,̱q̱,̱ṟ,̱s̱,̱ṯ,̱u̱,̱v̱,̱w̱,̱x̱,̱y̱,̱ẕ,̱0̱,̱9̱,̱8̱,̱7̱,̱6̱,̱5̱,̱4̱,̱3̱,̱2̱,̱1̱,̱.̱,̱_̱", "A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲", "Ā,̄B̄,̄C̄,̄D̄,̄Ē,̄F̄,̄Ḡ,̄H̄,̄Ī,̄J̄,̄K̄,̄L̄,̄M̄,̄N̄,̄Ō,̄P̄,̄Q̄,̄R̄,̄S̄,̄T̄,̄Ū,̄V̄,̄W̄,̄X̄,̄Ȳ,̄Z̄,̄ā,̄b̄,̄c̄,̄d̄,̄ē,̄f̄,̄ḡ,̄h̄,̄ī,̄j̄,̄k̄,̄l̄,̄m̄,̄n̄,̄ō,̄p̄,̄q̄,̄r̄,̄s̄,̄t̄,̄ū,̄v̄,̄w̄,̄x̄,̄ȳ,̄z̄,̄0̄,̄9̄,̄8̄,̄7̄,̄6̄,̄5̄,̄4̄,̄3̄,̄2̄,̄1̄,̄.̄,̄_̄", "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_", "@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,0,➈,➑,➐,➅,➄,➃,➌,➁,➊,.,_", "@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,0,➒,➑,➐,➏,➄,➍,➂,➁,➀,.,_", "@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,0,➒,➇,➆,➅,➄,➍,➌,➋,➀,.,_", "α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,0,➒,➑,➆,➅,➎,➍,➌,➁,➀,.,_", "ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,0,➒,➑,➐,➅,➄,➍,➂,➁,➊,.,_", "α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,0,➈,➇,➐,➅,➎,➍,➌,➁,➊,.,_", "@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,0,➒,➑,➆,➅,➄,➃,➂,➁,➀,.,_", "ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,0,➈,➇,➐,➅,➄,➃,➂,➁,➀,.,_", "ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_", "λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_", "მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_", "λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_", "Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", "Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,0,9,8,7,6,5,4,3,2,1,.,_", "ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_", "Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_", "ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,0,9,8,7,6,5,4,3,2,1,.,_", "ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_", "⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_", "ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,0,9,8,7,6,5,4,3,2,1,.,_", "4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_", "Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,0,9,8,7,6,5,4,3,2,1,.,_", "【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【0】,【9】,【8】,【7】,【6】,【5】,【4】,【3】,【2】,【1】,.,_", "[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,̲̅0̲̅,̲̅9̲̲̅,̅8̲̅,̲̅7̲̅,̲̅6̲̅,̲̅5̲̅,̲̅4̲̅,̲̅3̲̲̅,̅2̲̲̅,̅1̲̲̅̅],.,_", "[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,̺͆͆0̺͆,̺͆9̺͆,̺͆8̺̺͆͆7̺͆,̺͆6̺͆,̺͆5̺͆,̺͆4̺͆,̺͆3̺͆,̺͆2̺͆,̺͆1̺͆],.,_", "̛̭̰̃ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̛̭̰ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̭̰0̛̛̰̭̃̃,̭̰9̛̰̭̃̃,̛̭̰8̛̛̰̭̃̃,̭̰7̛̰̭̃̃,̛̭̰6̛̰̭̃̃,̛̭̰5̛̰̭̃,̛̭̰̃4̛̰̭̃,̛̭̰̃3̛̰̭̃̃,̛̭̰2̛̰̭̃̃,̛̭̰1̛̰̭̃,.,_", "a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,ะ0,ะ9,ะ8,ะ7,ะ6,ะ5,ะ4,ะ3,ะ2,ะ1ะ,.,_", "̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑0̑,̑9̑,̑8̑,̑7̑,̑6̑,̑5̑,̑4̑,̑3̑,̑2̑,̑1̑,.,_", "~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,͜͝0,͜͝9,͜͝8,͜͝7,͜͝6,͜͝5,͜͝4,͜͝3,͜͝2͜,͝1͜͝~,.,_", "̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈0̤̈,̤̈9̤̈,̤̈8̤̈,̤̈7̤̈,̤̈6̤̈,̤̈5̤̈,̤̈4̤̈,̤̈3̤̈,̤̈2̤̈̈,̤1̤̈,.,_", "≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,̮̑0̮̑,̮̑9̮̑,̮̑8̮̑,̮̑7̮̑,̮̑6̮̑,̮̑5̮̑,̮̑4̮̑,̮̑3̮̑,̮̑2̮̑,̮̑1̮̑≋,.,_", "a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮,i̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮i,̮̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,0̮̮,9̮̮,8̮̮,7̮̮,6̮̮,5̮̮,4̮̮,3̮̮,2̮̮,1̮,.,_", "A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲", "Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_", } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local result = {} i=0 for k=1,#fonts do i=i+1 local tar_font = fonts[i]:split(",") local text = matches[2] local text = text:gsub("A",tar_font[1]) local text = text:gsub("B",tar_font[2]) local text = text:gsub("C",tar_font[3]) local text = text:gsub("D",tar_font[4]) local text = text:gsub("E",tar_font[5]) local text = text:gsub("F",tar_font[6]) local text = text:gsub("G",tar_font[7]) local text = text:gsub("H",tar_font[8]) local text = text:gsub("I",tar_font[9]) local text = text:gsub("J",tar_font[10]) local text = text:gsub("K",tar_font[11]) local text = text:gsub("L",tar_font[12]) local text = text:gsub("M",tar_font[13]) local text = text:gsub("N",tar_font[14]) local text = text:gsub("O",tar_font[15]) local text = text:gsub("P",tar_font[16]) local text = text:gsub("Q",tar_font[17]) local text = text:gsub("R",tar_font[18]) local text = text:gsub("S",tar_font[19]) local text = text:gsub("T",tar_font[20]) local text = text:gsub("U",tar_font[21]) local text = text:gsub("V",tar_font[22]) local text = text:gsub("W",tar_font[23]) local text = text:gsub("X",tar_font[24]) local text = text:gsub("Y",tar_font[25]) local text = text:gsub("Z",tar_font[26]) local text = text:gsub("a",tar_font[27]) local text = text:gsub("b",tar_font[28]) local text = text:gsub("c",tar_font[29]) local text = text:gsub("d",tar_font[30]) local text = text:gsub("e",tar_font[31]) local text = text:gsub("f",tar_font[32]) local text = text:gsub("g",tar_font[33]) local text = text:gsub("h",tar_font[34]) local text = text:gsub("i",tar_font[35]) local text = text:gsub("j",tar_font[36]) local text = text:gsub("k",tar_font[37]) local text = text:gsub("l",tar_font[38]) local text = text:gsub("m",tar_font[39]) local text = text:gsub("n",tar_font[40]) local text = text:gsub("o",tar_font[41]) local text = text:gsub("p",tar_font[42]) local text = text:gsub("q",tar_font[43]) local text = text:gsub("r",tar_font[44]) local text = text:gsub("s",tar_font[45]) local text = text:gsub("t",tar_font[46]) local text = text:gsub("u",tar_font[47]) local text = text:gsub("v",tar_font[48]) local text = text:gsub("w",tar_font[49]) local text = text:gsub("x",tar_font[50]) local text = text:gsub("y",tar_font[51]) local text = text:gsub("z",tar_font[52]) local text = text:gsub("0",tar_font[53]) local text = text:gsub("9",tar_font[54]) local text = text:gsub("8",tar_font[55]) local text = text:gsub("7",tar_font[56]) local text = text:gsub("6",tar_font[57]) local text = text:gsub("5",tar_font[58]) local text = text:gsub("4",tar_font[59]) local text = text:gsub("3",tar_font[60]) local text = text:gsub("2",tar_font[61]) local text = text:gsub("1",tar_font[62]) table.insert(result, text) end local result_text = "Your Text : "..matches[2].."\nDesign With 100 Fonts :"..tostring(#fonts).."\n\n" a=0 for v=1,#result do a=a+1 result_text = result_text..a.."- "..result[a].."\n\n" end return result_text.."@worldTG" end return { description = "Fantasy Writer", usagehtm = '<tr><td align="center">write متن</td><td align="right">با استفاده از این پلاگین میتوانید متون خود را با فونت های متنوع و زیبایی طراحی کنید. حد اکثر کاراکتر های مجاز 20 عدد میباشد و فقط میتوانید از حروف انگلیسی و اعداد استفاده کنید</td></tr>', usage = {"write [text] : زیبا نویسی",}, patterns = { "^([#/!]write) (.*)", "^([#/!]write)$", }, run = run }
gpl-2.0
iamliqiang/prosody-modules
mod_register_web/mod_register_web.lua
27
5718
local captcha_options = module:get_option("captcha_options", {}); local nodeprep = require "util.encodings".stringprep.nodeprep; local usermanager = require "core.usermanager"; local http = require "net.http"; local path_sep = package.config:sub(1,1); module:depends"http"; local extra_fields = { nick = true; name = true; first = true; last = true; email = true; address = true; city = true; state = true; zip = true; phone = true; url = true; date = true; } local template_path = module:get_option_string("register_web_template", "templates"); function template(data) -- Like util.template, but deals with plain text return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end } end local function get_template(name) local fh = assert(module:load_resource(template_path..path_sep..name..".html")); local data = assert(fh:read("*a")); fh:close(); return template(data); end local function render(template, data) return tostring(template.apply(data)); end local register_tpl = get_template "register"; local success_tpl = get_template "success"; if next(captcha_options) ~= nil then local recaptcha_tpl = get_template "recaptcha"; function generate_captcha(display_options) return recaptcha_tpl.apply(setmetatable({ recaptcha_display_error = display_options and display_options.recaptcha_error and ("&error="..display_options.recaptcha_error) or ""; }, { __index = function (t, k) if captcha_options[k] then return captcha_options[k]; end module:log("error", "Missing parameter from captcha_options: %s", k); end })); end function verify_captcha(request, form, callback) http.request("https://www.google.com/recaptcha/api/verify", { body = http.formencode { privatekey = captcha_options.recaptcha_private_key; remoteip = request.conn:ip(); challenge = form.recaptcha_challenge_field; response = form.recaptcha_response_field; }; }, function (verify_result, code) local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)"); if verify_ok == "true" then callback(true); else callback(false, verify_err) end end); end else module:log("debug", "No Recaptcha options set, using fallback captcha") local random = math.random; local hmac_sha1 = require "util.hashes".hmac_sha1; local secret = require "util.uuid".generate() local ops = { '+', '-' }; local captcha_tpl = get_template "simplecaptcha"; function generate_captcha() local op = ops[random(1, #ops)]; local x, y = random(1, 9) repeat y = random(1, 9); until x ~= y; local answer; if op == '+' then answer = x + y; elseif op == '-' then if x < y then -- Avoid negative numbers x, y = y, x; end answer = x - y; end local challenge = hmac_sha1(secret, answer, true); return captcha_tpl.apply { op = op, x = x, y = y, challenge = challenge; }; end function verify_captcha(request, form, callback) if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then callback(true); else callback(false, "Captcha verification failed"); end end end function generate_page(event, display_options) local request, response = event.request, event.response; response.headers.content_type = "text/html; charset=utf-8"; return render(register_tpl, { path = request.path; hostname = module.host; notice = display_options and display_options.register_error or ""; captcha = generate_captcha(display_options); }) end function register_user(form, origin) local prepped_username = nodeprep(form.username); if not prepped_username then return nil, "Username contains forbidden characters"; end if #prepped_username == 0 then return nil, "The username field was empty"; end if usermanager.user_exists(prepped_username, module.host) then return nil, "Username already taken"; end local registering = { username = prepped_username , host = module.host, allowed = true } module:fire_event("user-registering", registering); if not registering.allowed then return nil, "Registration not allowed"; end local ok, err = usermanager.create_user(prepped_username, form.password, module.host); if ok then local extra_data = {}; for field in pairs(extra_fields) do local field_value = form[field]; if field_value and #field_value > 0 then extra_data[field] = field_value; end end if next(extra_data) ~= nil then datamanager.store(prepped_username, module.host, "account_details", extra_data); end module:fire_event("user-registered", { username = prepped_username, host = module.host, source = module.name, ip = origin.conn:ip(), }); end return ok, err; end function generate_success(event, form) return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host }); end function generate_register_response(event, form, ok, err) local message; event.response.headers.content_type = "text/html; charset=utf-8"; if ok then return generate_success(event, form); else return generate_page(event, { register_error = err }); end end function handle_form(event) local request, response = event.request, event.response; local form = http.formdecode(request.body); verify_captcha(request, form, function (ok, err) if ok then local register_ok, register_err = register_user(form, request); response:send(generate_register_response(event, form, register_ok, register_err)); else response:send(generate_page(event, { register_error = err })); end end); return true; -- Leave connection open until we respond above end module:provides("http", { route = { GET = generate_page; ["GET /"] = generate_page; POST = handle_form; ["POST /"] = handle_form; }; });
mit
ferstar/openwrt-dreambox
feeds/luci/luci/luci/contrib/luadoc/lua/luadoc/taglet/standard.lua
93
16319
------------------------------------------------------------------------------- -- @release $Id: standard.lua,v 1.39 2007/12/21 17:50:48 tomas Exp $ ------------------------------------------------------------------------------- local assert, pairs, tostring, type = assert, pairs, tostring, type local io = require "io" local posix = require "nixio.fs" local luadoc = require "luadoc" local util = require "luadoc.util" local tags = require "luadoc.taglet.standard.tags" local string = require "string" local table = require "table" module 'luadoc.taglet.standard' ------------------------------------------------------------------------------- -- Creates an iterator for an array base on a class type. -- @param t array to iterate over -- @param class name of the class to iterate over function class_iterator (t, class) return function () local i = 1 return function () while t[i] and t[i].class ~= class do i = i + 1 end local v = t[i] i = i + 1 return v end end end -- Patterns for function recognition local identifiers_list_pattern = "%s*(.-)%s*" local identifier_pattern = "[^%(%s]+" local function_patterns = { "^()%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)", "^%s*(local%s)%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)", "^()%s*("..identifier_pattern..")%s*%=%s*function%s*%("..identifiers_list_pattern.."%)", } ------------------------------------------------------------------------------- -- Checks if the line contains a function definition -- @param line string with line text -- @return function information or nil if no function definition found local function check_function (line) line = util.trim(line) local info = table.foreachi(function_patterns, function (_, pattern) local r, _, l, id, param = string.find(line, pattern) if r ~= nil then return { name = id, private = (l == "local"), param = { } --util.split("%s*,%s*", param), } end end) -- TODO: remove these assert's? if info ~= nil then assert(info.name, "function name undefined") assert(info.param, string.format("undefined parameter list for function `%s'", info.name)) end return info end ------------------------------------------------------------------------------- -- Checks if the line contains a module definition. -- @param line string with line text -- @param currentmodule module already found, if any -- @return the name of the defined module, or nil if there is no module -- definition local function check_module (line, currentmodule) line = util.trim(line) -- module"x.y" -- module'x.y' -- module[[x.y]] -- module("x.y") -- module('x.y') -- module([[x.y]]) -- module(...) local r, _, modulename = string.find(line, "^module%s*[%s\"'(%[]+([^,\"')%]]+)") if r then -- found module definition logger:debug(string.format("found module `%s'", modulename)) return modulename end return currentmodule end -- Patterns for constant recognition local constant_patterns = { "^()%s*([A-Z][A-Z0-9_]*)%s*=", "^%s*(local%s)%s*([A-Z][A-Z0-9_]*)%s*=", } ------------------------------------------------------------------------------- -- Checks if the line contains a constant definition -- @param line string with line text -- @return constant information or nil if no constant definition found local function check_constant (line) line = util.trim(line) local info = table.foreachi(constant_patterns, function (_, pattern) local r, _, l, id = string.find(line, pattern) if r ~= nil then return { name = id, private = (l == "local"), } end end) -- TODO: remove these assert's? if info ~= nil then assert(info.name, "constant name undefined") end return info end ------------------------------------------------------------------------------- -- Extracts summary information from a description. The first sentence of each -- doc comment should be a summary sentence, containing a concise but complete -- description of the item. It is important to write crisp and informative -- initial sentences that can stand on their own -- @param description text with item description -- @return summary string or nil if description is nil local function parse_summary (description) -- summary is never nil... description = description or "" -- append an " " at the end to make the pattern work in all cases description = description.." " -- read until the first period followed by a space or tab local summary = string.match(description, "(.-%.)[%s\t]") -- if pattern did not find the first sentence, summary is the whole description summary = summary or description return summary end ------------------------------------------------------------------------------- -- @param f file handle -- @param line current line being parsed -- @param modulename module already found, if any -- @return current line -- @return code block -- @return modulename if found local function parse_code (f, line, modulename) local code = {} while line ~= nil do if string.find(line, "^[\t ]*%-%-%-") then -- reached another luadoc block, end this parsing return line, code, modulename else -- look for a module definition modulename = check_module(line, modulename) table.insert(code, line) line = f:read() end end -- reached end of file return line, code, modulename end ------------------------------------------------------------------------------- -- Parses the information inside a block comment -- @param block block with comment field -- @return block parameter local function parse_comment (block, first_line, modulename) -- get the first non-empty line of code local code = table.foreachi(block.code, function(_, line) if not util.line_empty(line) then -- `local' declarations are ignored in two cases: -- when the `nolocals' option is turned on; and -- when the first block of a file is parsed (this is -- necessary to avoid confusion between the top -- local declarations and the `module' definition. if (options.nolocals or first_line) and line:find"^%s*local" then return end return line end end) -- parse first line of code if code ~= nil then local func_info = check_function(code) local module_name = check_module(code) local const_info = check_constant(code) if func_info then block.class = "function" block.name = func_info.name block.param = func_info.param block.private = func_info.private elseif const_info then block.class = "constant" block.name = const_info.name block.private = const_info.private elseif module_name then block.class = "module" block.name = module_name block.param = {} else block.param = {} end else -- TODO: comment without any code. Does this means we are dealing -- with a file comment? end -- parse @ tags local currenttag = "description" local currenttext table.foreachi(block.comment, function (_, line) line = util.trim_comment(line) local r, _, tag, text = string.find(line, "@([_%w%.]+)%s+(.*)") if r ~= nil then -- found new tag, add previous one, and start a new one -- TODO: what to do with invalid tags? issue an error? or log a warning? tags.handle(currenttag, block, currenttext) currenttag = tag currenttext = text else currenttext = util.concat(currenttext, line) assert(string.sub(currenttext, 1, 1) ~= " ", string.format("`%s', `%s'", currenttext, line)) end end) tags.handle(currenttag, block, currenttext) -- extracts summary information from the description block.summary = parse_summary(block.description) assert(string.sub(block.description, 1, 1) ~= " ", string.format("`%s'", block.description)) if block.name and block.class == "module" then modulename = block.name end return block, modulename end ------------------------------------------------------------------------------- -- Parses a block of comment, started with ---. Read until the next block of -- comment. -- @param f file handle -- @param line being parsed -- @param modulename module already found, if any -- @return line -- @return block parsed -- @return modulename if found local function parse_block (f, line, modulename, first) local block = { comment = {}, code = {}, } while line ~= nil do if string.find(line, "^[\t ]*%-%-") == nil then -- reached end of comment, read the code below it -- TODO: allow empty lines line, block.code, modulename = parse_code(f, line, modulename) -- parse information in block comment block, modulename = parse_comment(block, first, modulename) return line, block, modulename else table.insert(block.comment, line) line = f:read() end end -- reached end of file -- parse information in block comment block, modulename = parse_comment(block, first, modulename) return line, block, modulename end ------------------------------------------------------------------------------- -- Parses a file documented following luadoc format. -- @param filepath full path of file to parse -- @param doc table with documentation -- @return table with documentation function parse_file (filepath, doc, handle, prev_line, prev_block, prev_modname) local blocks = { prev_block } local modulename = prev_modname -- read each line local f = handle or io.open(filepath, "r") local i = 1 local line = prev_line or f:read() local first = true while line ~= nil do if string.find(line, "^[\t ]*%-%-%-") then -- reached a luadoc block local block, newmodname line, block, newmodname = parse_block(f, line, modulename, first) if modulename and newmodname and newmodname ~= modulename then doc = parse_file( nil, doc, f, line, block, newmodname ) else table.insert(blocks, block) modulename = newmodname end else -- look for a module definition local newmodname = check_module(line, modulename) if modulename and newmodname and newmodname ~= modulename then parse_file( nil, doc, f ) else modulename = newmodname end -- TODO: keep beginning of file somewhere line = f:read() end first = false i = i + 1 end if not handle then f:close() end if filepath then -- store blocks in file hierarchy assert(doc.files[filepath] == nil, string.format("doc for file `%s' already defined", filepath)) table.insert(doc.files, filepath) doc.files[filepath] = { type = "file", name = filepath, doc = blocks, -- functions = class_iterator(blocks, "function"), -- tables = class_iterator(blocks, "table"), } -- local first = doc.files[filepath].doc[1] if first and modulename then doc.files[filepath].author = first.author doc.files[filepath].copyright = first.copyright doc.files[filepath].description = first.description doc.files[filepath].release = first.release doc.files[filepath].summary = first.summary end end -- if module definition is found, store in module hierarchy if modulename ~= nil then if modulename == "..." then assert( filepath, "Can't determine name for virtual module from filepatch" ) modulename = string.gsub (filepath, "%.lua$", "") modulename = string.gsub (modulename, "/", ".") end if doc.modules[modulename] ~= nil then -- module is already defined, just add the blocks table.foreachi(blocks, function (_, v) table.insert(doc.modules[modulename].doc, v) end) else -- TODO: put this in a different module table.insert(doc.modules, modulename) doc.modules[modulename] = { type = "module", name = modulename, doc = blocks, -- functions = class_iterator(blocks, "function"), -- tables = class_iterator(blocks, "table"), author = first and first.author, copyright = first and first.copyright, description = "", release = first and first.release, summary = "", } -- find module description for m in class_iterator(blocks, "module")() do doc.modules[modulename].description = util.concat( doc.modules[modulename].description, m.description) doc.modules[modulename].summary = util.concat( doc.modules[modulename].summary, m.summary) if m.author then doc.modules[modulename].author = m.author end if m.copyright then doc.modules[modulename].copyright = m.copyright end if m.release then doc.modules[modulename].release = m.release end if m.name then doc.modules[modulename].name = m.name end end doc.modules[modulename].description = doc.modules[modulename].description or (first and first.description) or "" doc.modules[modulename].summary = doc.modules[modulename].summary or (first and first.summary) or "" end -- make functions table doc.modules[modulename].functions = {} for f in class_iterator(blocks, "function")() do if f and f.name then table.insert(doc.modules[modulename].functions, f.name) doc.modules[modulename].functions[f.name] = f end end -- make tables table doc.modules[modulename].tables = {} for t in class_iterator(blocks, "table")() do if t and t.name then table.insert(doc.modules[modulename].tables, t.name) doc.modules[modulename].tables[t.name] = t end end -- make constants table doc.modules[modulename].constants = {} for c in class_iterator(blocks, "constant")() do if c and c.name then table.insert(doc.modules[modulename].constants, c.name) doc.modules[modulename].constants[c.name] = c end end end if filepath then -- make functions table doc.files[filepath].functions = {} for f in class_iterator(blocks, "function")() do if f and f.name then table.insert(doc.files[filepath].functions, f.name) doc.files[filepath].functions[f.name] = f end end -- make tables table doc.files[filepath].tables = {} for t in class_iterator(blocks, "table")() do if t and t.name then table.insert(doc.files[filepath].tables, t.name) doc.files[filepath].tables[t.name] = t end end end return doc end ------------------------------------------------------------------------------- -- Checks if the file is terminated by ".lua" or ".luadoc" and calls the -- function that does the actual parsing -- @param filepath full path of the file to parse -- @param doc table with documentation -- @return table with documentation -- @see parse_file function file (filepath, doc) local patterns = { "%.lua$", "%.luadoc$" } local valid = table.foreachi(patterns, function (_, pattern) if string.find(filepath, pattern) ~= nil then return true end end) if valid then logger:info(string.format("processing file `%s'", filepath)) doc = parse_file(filepath, doc) end return doc end ------------------------------------------------------------------------------- -- Recursively iterates through a directory, parsing each file -- @param path directory to search -- @param doc table with documentation -- @return table with documentation function directory (path, doc) for f in posix.dir(path) do local fullpath = path .. "/" .. f local attr = posix.stat(fullpath) assert(attr, string.format("error stating file `%s'", fullpath)) if attr.type == "reg" then doc = file(fullpath, doc) elseif attr.type == "dir" and f ~= "." and f ~= ".." then doc = directory(fullpath, doc) end end return doc end -- Recursively sorts the documentation table local function recsort (tab) table.sort (tab) -- sort list of functions by name alphabetically for f, doc in pairs(tab) do if doc.functions then table.sort(doc.functions) end if doc.tables then table.sort(doc.tables) end end end ------------------------------------------------------------------------------- function start (files, doc) assert(files, "file list not specified") -- Create an empty document, or use the given one doc = doc or { files = {}, modules = {}, } assert(doc.files, "undefined `files' field") assert(doc.modules, "undefined `modules' field") table.foreachi(files, function (_, path) local attr = posix.stat(path) assert(attr, string.format("error stating path `%s'", path)) if attr.type == "reg" then doc = file(path, doc) elseif attr.type == "dir" then doc = directory(path, doc) end end) -- order arrays alphabetically recsort(doc.files) recsort(doc.modules) return doc end
gpl-2.0
paulmarsy/Console
Libraries/nmap/App/nselib/data/psexec/drives.lua
8
1334
---This configuration file pulls info about a given harddrive -- Any variable in the 'config' table in smb-psexec.nse can be overriden in the -- 'overrides' table. Most of them are not really recommended, such as the host, -- key, etc. overrides = {} --overrides.timeout = 40 modules = {} local mod mod = {} mod.upload = false mod.name = "Drive type" mod.program = "fsutil" mod.args = "fsinfo drivetype $drive" mod.req_args = {"drive"} mod.maxtime = 1 table.insert(modules, mod) mod = {} mod.upload = false mod.name = "Drive info" mod.program = "fsutil" mod.args = "fsinfo ntfsinfo $drive" mod.req_args = {"drive"} mod.replace = {{" :",":"}} mod.maxtime = 1 table.insert(modules, mod) mod = {} mod.upload = false mod.name = "Drive type" mod.program = "fsutil" mod.args = "fsinfo statistics $drive" mod.req_args = {"drive"} mod.replace = {{" :",":"}} mod.maxtime = 1 table.insert(modules, mod) mod = {} mod.upload = false mod.name = "Drive quota" mod.program = "fsutil" mod.args = "quota query $drive" mod.req_args = {"drive"} mod.maxtime = 1 table.insert(modules, mod)
mit
Murfalo/game-off-2016
startup.lua
1
2356
---- -- startup.lua -- -- This file contains numerous routines used when starting the game. This is -- to help prevent main.lua from becoming too confusing. ---- local Keymap = require "xl.Keymap" local Gamestate = require "hump.gamestate" local DebugMenu = require "state.DebugMenu" local ObjChar = require "objects.ObjChar" local InventoryMenu = require "state.InventoryMenu" local startup = { window = {} } ---- -- Perform basic checks to ensure the graphics card has support for everything we need. -- Fail with asserts if it doesn't. ---- function startup.sanityCheck() -- local function sancheck(s,m) assert(love.graphics.isSupported(s), "Your graphics card doesn't support " .. m) end -- sancheck("canvas", "Framebuffers.") -- sancheck("shader", "shaders") -- sancheck("subtractive", "the subtractive blend mode.") -- sancheck("npot", "non-power-of-two textures.") end function startup.takeScreenshot() local fname = string.format("%s/Screenshot %s.png", love.filesystem.getUserDirectory(), os.date("%Y-%m-%d_%H.%M.%S")) love.graphics.newScreenshot():encode("temp.png") util.moveFile("temp.png", fname) xl.AddMessage(string.format("Screenshot saved to '%s'",fname)) end function startup.getCursor() -- Will want to eventually replace cursor with custom image -- Just setVisible false and draw custom sprite at position of mouse in love.draw love.mouse.setVisible(true) love.mouse.setGrabbed(true) end function startup.GotoDebugMenu( ) Gamestate.push( DebugMenu ) end function startup.ToggleFullscreen( ) local fs = not love.window.getFullscreen() love.window.setFullscreen( fs, "normal" ) end function startup.dothings() -- print out graphics card information local _, version, vendor, device = love.graphics.getRendererInfo() print( "OpenGL Version: " .. version .. "\nGPU: " .. device ) -- otherwise sprites look weird love.graphics.setDefaultFilter("nearest", "nearest") -- default log level Log.setLevel("debug") xl.DScreen.toggle() -- screenshot function Keymap.pressed("screenshot", startup.takeScreenshot) -- debug menu Keymap.pressed("debug", startup.GotoDebugMenu) Keymap.pressed("fullscreen", startup.ToggleFullscreen) love.physics.setMeter(32) -- register Gamestate functions Gamestate.registerEvents({"focus", "mousefocus", "quit", "textinput", "threaderror", "visible"}) end return startup
mit
emptyrivers/WeakAuras2
WeakAurasOptions/AceGUI-Widgets/AceGUIWidget-WeakAurasImportButton.lua
1
6311
if not WeakAuras.IsCorrectVersion() then return end local Type, Version = "WeakAurasImportButton", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end local L = WeakAuras.L; local function Hide_Tooltip() GameTooltip:Hide(); end local function Show_Tooltip(owner, line1, line2) GameTooltip:SetOwner(owner, "ANCHOR_NONE"); GameTooltip:SetPoint("LEFT", owner, "RIGHT"); GameTooltip:ClearLines(); GameTooltip:AddLine(line1); GameTooltip:AddLine(line2, 1, 1, 1, 1); GameTooltip:Show(); end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetWidth(380); self:SetHeight(18); end, ["SetTitle"] = function(self, title) self.title:SetText(title); end, ["GetTitle"] = function(self) return self.title:GetText(); end, ["SetDescription"] = function(self, desc) self.frame.description = desc; end, ["SetIcon"] = function(self, iconPath) if(iconPath) then local icon = self.frame:CreateTexture(); icon:SetTexture(iconPath); icon:SetPoint("RIGHT", self.frame, "RIGHT"); icon:SetPoint("BOTTOM", self.frame, "BOTTOM"); icon:SetWidth(16); icon:SetHeight(16); self.title:SetPoint("RIGHT", icon, "LEFT"); end end, -- ["SetChecked"] = function(self, value) -- print("SetChecked", self.title:GetText(), value); -- self.checkbox:SetChecked(value); -- print("After SetChecked", self.checkbox:GetChecked(), self:GetChecked()); -- end, -- ["GetChecked"] = function(self) -- local checked = self.checkbox:GetChecked(); -- print("GetChecked", self.title:GetText(), checked); -- return checked; -- end, ["SetClick"] = function(self, func) self.checkbox:SetScript("OnClick", func); end, ["Expand"] = function(self, reloadTooltip) self.expand:Enable(); self.expand.expanded = true; self.expand:SetNormalTexture("Interface\\BUTTONS\\UI-MinusButton-Up.blp"); self.expand:SetPushedTexture("Interface\\BUTTONS\\UI-MinusButton-Down.blp"); self.expand.title = L["Collapse"]; self.expand:SetScript("OnClick", function() self:Collapse(true) end); self.expand.func(); if(reloadTooltip) then Hide_Tooltip(); Show_Tooltip(self.frame, self.expand.title, nil); end end, ["Collapse"] = function(self, reloadTooltip) self.expand:Enable(); self.expand.expanded = nil; self.expand:SetNormalTexture("Interface\\BUTTONS\\UI-PlusButton-Up.blp"); self.expand:SetPushedTexture("Interface\\BUTTONS\\UI-PlusButton-Down.blp"); self.expand.title = L["Expand"]; self.expand:SetScript("OnClick", function() self:Expand(true) end); self.expand.func(); if(reloadTooltip) then Hide_Tooltip(); Show_Tooltip(self.frame, self.expand.title, nil); end end, ["SetOnExpandCollapse"] = function(self, func) self.expand.func = func; end, ["GetExpanded"] = function(self) return self.expand.expanded; end, ["DisableExpand"] = function(self) self.expand:Disable(); self.expand.disabled = true; self.expand.expanded = false; self.expand:SetNormalTexture("Interface\\BUTTONS\\UI-PlusButton-Disabled.blp"); end, ["EnableExpand"] = function(self) self.expand.disabled = false; if(self:GetExpanded()) then self:Expand(); else self:Collapse(); end end, ["SetExpandVisible"] = function(self, value) if(value) then self.expand:Show(); else self.expand:Hide(); end end, ["SetLevel"] = function(self, level) self.checkbox:SetPoint("left", self.frame, "left", level * 16, 0); end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local name = "WeakAurasImportButton"..AceGUI:GetNextWidgetNum(Type); local button = CreateFrame("BUTTON", name, UIParent, "OptionsListButtonTemplate"); button:SetHeight(18); button:SetWidth(380); button.dgroup = nil; local background = button:CreateTexture(nil, "BACKGROUND"); button.background = background; background:SetTexture("Interface\\BUTTONS\\UI-Listbox-Highlight2.blp"); background:SetBlendMode("ADD"); background:SetVertexColor(0.5, 0.5, 0.5, 0.25); background:SetAllPoints(button); local expand = CreateFrame("BUTTON", nil, button); button.expand = expand; expand.expanded = true; expand.disabled = true; expand.func = function() end; expand:SetNormalTexture("Interface\\BUTTONS\\UI-PlusButton-Disabled.blp"); expand:Disable(); expand:SetWidth(16); expand:SetHeight(16); expand:SetPoint("BOTTOM", button, "BOTTOM"); expand:SetPoint("LEFT", button, "LEFT"); expand:SetHighlightTexture("Interface\\BUTTONS\\UI-Panel-MinimizeButton-Highlight.blp"); expand.title = L["Disabled"]; expand:SetScript("OnEnter", function() Show_Tooltip(button, expand.title, nil) end); expand:SetScript("OnLeave", Hide_Tooltip); local checkbox = CreateFrame("CheckButton", nil, button, "ChatConfigCheckButtonTemplate"); button.checkbox = checkbox; checkbox:EnableMouse(false); checkbox:SetWidth(18); checkbox:SetHeight(18); checkbox:SetPoint("BOTTOM", button, "BOTTOM"); checkbox:SetPoint("LEFT", button, "LEFT", 16); local title = button:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge"); button.title = title; title:SetHeight(14); title:SetJustifyH("LEFT"); title:SetPoint("LEFT", checkbox, "RIGHT", 2, 0); title:SetPoint("RIGHT", button, "RIGHT"); button.description = ""; button:SetScript("OnEnter", function() Show_Tooltip(button, title:GetText(), button.description) end); button:SetScript("OnLeave", Hide_Tooltip); button:SetScript("OnClick", function() checkbox:Click() end); local widget = { frame = button, title = title, checkbox = checkbox, expand = expand, background = background, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
gpl-2.0
Murfalo/game-off-2016
extra.lua
1
4063
---- -- extra.lua -- -- This file holds a bunch of miscellaneous utility functions that use other -- libraries. Unlike util.lua, these functions are tied much more directly -- to the game itself. ---- local Scene = require "xl.Scene" local anim8 = require "anim8" local Gamestate = require "hump.gamestate" local MaxMessageTime = 2 local Messages = {} local font_cache = {} local DEFAULT_FONT = "assets/fonts/DejaVuSans.ttf" local xl = { Sprite = require "xl.Sprite", DScreen = require "xl.DScreen", } function xl.AddMessage(msg) table.insert(Messages, {msg = msg, time = love.timer.getTime()}) end function xl.DrawMessages() local loveGraphics = love.graphics local font = xl.getFont() loveGraphics.setFont( font ) local y = loveGraphics.getHeight() - 5 for i=#Messages,1,-1 do y = y - font:getHeight() local ratio = (love.timer.getTime() - Messages[i].time) / MaxMessageTime if ratio >= 1 then table.remove(Messages, i) else local alpha = 255 * math.min(1 - ratio + 0.25, 1) loveGraphics.setColor(240,240,240,alpha) loveGraphics.printf(Messages[i].msg, 5, y, 9900, "left") end end end function xl.SHOW_HITBOX (hbox) local loveGraphics = love.graphics local node local drawFunc = function() local floor = math.floor local ok, shape = pcall(hbox.getShape, hbox) if not ok then lume.trace() Game.scene:remove( node ) else local bx,by = hbox:getBody():getPosition() loveGraphics.push() loveGraphics.translate( bx, by + 16 ) loveGraphics.rotate(hbox:getBody():getAngle()) loveGraphics.setColor(50, 200, 50) local ty = shape:getType() if ty == "chain" or ty == "edge" then loveGraphics.line( shape:getPoints() ) elseif ty == "polygon" then love.graphics.polygon( "fill", shape:getPoints() ) elseif ty == "circle" then local x,y = shape:getPoint() local r = shape:getRadius() loveGraphics.circle( "fill", x, y, r, 20 ) end loveGraphics.setColor(255, 255, 255) loveGraphics.pop() end end node = Scene.wrapNode({draw = drawFunc}, 9900) Game.scene:insert(node) return node end function xl.newGrid( frameWidth, frameHeight, ... ) frameWidth = tonumber(frameWidth) frameHeight = tonumber(frameHeight) local args = {...} if type(args[1]) == "string" then args[1] = love.graphics.newImage( args[1] ) end if type(args[1]) == "userdata" then local img = args[1] args[1] = img:getWidth() table.insert(args, 2, img:getHeight()) end return anim8.newGrid(frameWidth, frameHeight, unpack(args)) end function xl.newSprite(image, frameWidth, frameHeight, border, z) if type(image) == "string" then image = love.graphics.newImage( image ) end local grid = anim8.newGrid(frameWidth, frameHeight, image:getWidth(), image:getHeight(), 0, 0, border or 0) local spr = xl.Sprite(image, 0, 0, z or 0) spr.grid = grid return spr, grid end -- Returns: scale, scissorX, scissorY, scissorW, scissorH, offsetX, offsetY function xl.calculateViewport(sizes, winW, winH, scaleInterval, screenFlex ) local gameW,gameH = sizes.w, sizes.h local screenW,screenH = winW + screenFlex, winH + screenFlex local scale = math.min(screenW / gameW, screenH / gameH) scale = math.floor(scale * scaleInterval) / scaleInterval local scissorW, scissorH = gameW * scale, gameH * scale local scissorX, scissorY = (winW - scissorW) / 2, (winH - scissorH) / 2 local offsetX, offsetY = scissorX / scale, scissorY / scale return scale, scissorX, scissorY, scissorW, scissorH, offsetX, offsetY end function xl.getFont( size ) size = size or 12 if not font_cache[size] then local font = love.graphics.newFont(DEFAULT_FONT, size) font_cache[size] = font end return font_cache[size] end function xl.pushState( state, ... ) Gamestate.push( state, ... ) end function xl.switchState( state, ... ) Gamestate.switch( state, ... ) end function xl.inRect( pos,quad ) if pos.x > quad[1] and pos.y > quad[2] and pos.x < quad[3] and pos.y < quad[4] then return true end return false end -- disable xl.SHOW_HITBOX -- xl.SHOW_HITBOX = function () end return xl
mit
xordspar0/synthein
src/world/world.lua
1
5543
local Missile = require("world/missile") local Particles = require("world/particles") local Shot = require("world/shot") local Structure = require("world/structure") local PhysicsReferences = require("world/physicsReferences") local World = class() World.objectTypes = { structure = Structure, shot = Shot, missile = Missile, particles = Particles } -- The world object contains all of the state information about the game world -- and is responsible for updating and drawing everything in the game world. function World:__create(playerHostility) self.physics = love.physics.newWorld() self.physics:setCallbacks(World.beginContact, World.endContact, World.preSolve, World.postSolve) self.objects = {} local generalHostility = {} generalHostility[0] = false --corepartless structures generalHostility[-1] = true --pirates generalHostility[-2] = false --civilians generalHostility[-3] = true --Empire generalHostility[-4] = true --Federation self.events = {create = {}} local teamHostility = {playerHostility = playerHostility, general = generalHostility} function teamHostility:test(team, otherTeam) local max = math.max(team, otherTeam) local min = math.min(team, otherTeam) if min > 0 then return self.playerHostility[team][otherTeam] elseif max > 0 then return self.general[min] elseif max > -3 then return self.general[max] else return team ~= otherTeam end end self.info = {events = self.events, physics = self.physics, teamHostility = teamHostility} self.borders = nil end function World.beginContact(fixtureA, fixtureB, coll) --print("beginContact") local aCategory = fixtureA:getFilterData() local bCategory = fixtureB:getFilterData() local partCategory = PhysicsReferences.getCategory("general") local sqV, aL, bL if aCategory == partCategory and bCategory == partCategory then local x, y = coll:getPositions() local bodyA = fixtureA:getBody() local bodyB = fixtureB:getBody() local aVX, aVY, bVX, bVY if x and y then aVX, aVY = bodyA:getLinearVelocityFromWorldPoint(x, y) bVX, bVY = bodyB:getLinearVelocityFromWorldPoint(x, y) local dVX = aVX - bVX local dVY = aVY - bVY sqV = (dVX * dVX) + (dVY * dVY) else sqV = 0 end aL = {aVX, aVY} bL = {bVX, bVY} end local objectA = fixtureA:getUserData() local objectB = fixtureB:getUserData() if aCategory <= bCategory then objectA:collision(fixtureA, fixtureB, sqV, aL) end if bCategory <= aCategory then objectB:collision(fixtureB, fixtureA, sqV, bL) end end function World.endContact(fixtureA, fixtureB, coll) --print("endContact") local aCategory = fixtureA:getFilterData() local bCategory = fixtureB:getFilterData() local objectA = fixtureA:getUserData() local objectB = fixtureB:getUserData() if aCategory <= bCategory and objectA.endCollision then objectA:endCollision(fixtureA, fixtureB) end if bCategory <= aCategory and objectB.endCollision then objectB:endCollision(fixtureB, fixtureA) end end function World.preSolve(fixtureA, fixtureB, coll) --print("preSolve") local objectA = fixtureA:getUserData() local objectB = fixtureB:getUserData() if objectA.isDestroyed or objectB.isDestroyed then coll:setEnabled(false) end end function World.postSolve() --(fixtureA, fixtureB, coll, normalimpulse, tangentimpulse) --print("postSolve") end function World:addObject(object, objectKey) table.insert(self.objects, object) end World.callbackData = {objects = {}} --Get the structure and part under at the location. --Also return the side of the part that is closed if there is a part. function World:getObject(locationX, locationY) local objects = {} local callback = function(fixture) if not fixture:isSensor() then local body = fixture:getBody() local object = {body:getUserData()} table.insert(objects, object) end return true end local a = locationX local b = locationY self.physics:queryBoundingBox(a, b, a, b, callback) for _, object in ipairs(objects) do if object[1] then return unpack(object) end end return nil end function World:getObjects() return self.objects end function World:update(dt) self.physics:update(dt) local nextBorders = {0, 0, 0, 0} for i, object in ipairs(self.objects) do if object.isDestroyed == false then local objectX, objectY = object:getLocation():getXY() if object:type() == "structure" and object.corePart and object.corePart:getTeam() > 0 then if objectX < nextBorders[1] then nextBorders[1] = objectX elseif objectX > nextBorders[3]then nextBorders[3] = objectX end if objectY < nextBorders[2] then nextBorders[2] = objectY elseif objectY > nextBorders[4] then nextBorders[4] = objectY end end object:update(dt) if (self.borders and (objectX < self.borders[1] or objectY < self.borders[2] or objectX > self.borders[3] or objectY > self.borders[4])) then object:destroy() end end if object.isDestroyed == true then table.remove(self.objects, i) end end self.borders = nextBorders self.borders[1] = self.borders[1] - 10000 self.borders[2] = self.borders[2] - 10000 self.borders[3] = self.borders[3] + 10000 self.borders[4] = self.borders[4] + 10000 for _, object in ipairs(self.events.create) do local objectClass = World.objectTypes[object[1]] local newObject = objectClass(self.info, object[2], object[3]) table.insert(self.objects, newObject) end self.events.create = {} end return World
gpl-3.0
MmxBoy/Metal-bot
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
m-creations/openwrt
feeds/luci/build/luadoc/luadoc/taglet/standard/tags.lua
46
5543
------------------------------------------------------------------------------- -- Handlers for several tags -- @release $Id: tags.lua,v 1.8 2007/09/05 12:39:09 tomas Exp $ ------------------------------------------------------------------------------- local luadoc = require "luadoc" local util = require "luadoc.util" local string = require "string" local table = require "table" local assert, type, tostring, tonumber = assert, type, tostring, tonumber module "luadoc.taglet.standard.tags" ------------------------------------------------------------------------------- local function author (tag, block, text) block[tag] = block[tag] or {} if not text then luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping") return end table.insert (block[tag], text) end ------------------------------------------------------------------------------- -- Set the class of a comment block. Classes can be "module", "function", -- "table". The first two classes are automatic, extracted from the source code local function class (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function cstyle (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function sort (tag, block, text) block[tag] = tonumber(text) or 0 end ------------------------------------------------------------------------------- local function copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function field (tag, block, text) if block["class"] ~= "table" then luadoc.logger:warn("documenting `field' for block that is not a `table'") end block[tag] = block[tag] or {} local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") assert(name, "field name not defined") table.insert(block[tag], name) block[tag][name] = desc end ------------------------------------------------------------------------------- -- Set the name of the comment block. If the block already has a name, issue -- an error and do not change the previous value local function name (tag, block, text) if block[tag] and block[tag] ~= text then luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text)) end block[tag] = text end ------------------------------------------------------------------------------- -- Processes a parameter documentation. -- @param tag String with the name of the tag (it must be "param" always). -- @param block Table with previous information about the block. -- @param text String with the current line beeing processed. local function param (tag, block, text) block[tag] = block[tag] or {} -- TODO: make this pattern more flexible, accepting empty descriptions local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") if not name then luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping") return end local i = table.foreachi(block[tag], function (i, v) if v == name then return i end end) if i == nil then luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name)) table.insert(block[tag], name) end block[tag][name] = desc end ------------------------------------------------------------------------------- local function release (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function ret (tag, block, text) tag = "ret" if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- -- @see ret local function see (tag, block, text) -- see is always an array block[tag] = block[tag] or {} -- remove trailing "." text = string.gsub(text, "(.*)%.$", "%1") local s = util.split("%s*,%s*", text) table.foreachi(s, function (_, v) table.insert(block[tag], v) end) end ------------------------------------------------------------------------------- -- @see ret local function usage (tag, block, text) if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- local handlers = {} handlers["author"] = author handlers["class"] = class handlers["cstyle"] = cstyle handlers["copyright"] = copyright handlers["description"] = description handlers["field"] = field handlers["name"] = name handlers["param"] = param handlers["release"] = release handlers["return"] = ret handlers["see"] = see handlers["sort"] = sort handlers["usage"] = usage ------------------------------------------------------------------------------- function handle (tag, block, text) if not handlers[tag] then luadoc.logger:error(string.format("undefined handler for tag `%s'", tag)) return end if text then text = text:gsub("`([^\n]-)`", "<code>%1</code>") text = text:gsub("`(.-)`", "<pre>%1</pre>") end -- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag)) return handlers[tag](tag, block, text) end
gpl-2.0
MmxBoy/mmxanti2
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
ferstar/openwrt-dreambox
feeds/luci/luci/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/exec.lua
4
2717
--[[ Luci configuration model for statistics - collectd exec plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: exec.lua 6060 2010-04-13 20:42:26Z jow $ ]]-- m = Map("luci_statistics", translate("Exec Plugin Configuration"), translate( "The exec plugin starts external commands to read values " .. "from or to notify external processes when certain threshold " .. "values have been reached." )) -- collectd_exec config section s = m:section( NamedSection, "collectd_exec", "luci_statistics" ) -- collectd_exec.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_exec_input config section (Exec directives) exec = m:section( TypedSection, "collectd_exec_input", translate("Add command for reading values"), translate( "Here you can define external commands which will be " .. "started by collectd in order to read certain values. " .. "The values will be read from stdout." )) exec.addremove = true exec.anonymous = true -- collectd_exec_input.cmdline exec_cmdline = exec:option( Value, "cmdline" ) exec_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_exec_input.cmdline exec_cmduser = exec:option( Value, "cmduser" ) exec_cmduser.default = "nobody" exec_cmduser.rmempty = true exec_cmduser.optional = true -- collectd_exec_input.cmdline exec_cmdgroup = exec:option( Value, "cmdgroup" ) exec_cmdgroup.default = "nogroup" exec_cmdgroup.rmempty = true exec_cmdgroup.optional = true -- collectd_exec_notify config section (NotifyExec directives) notify = m:section( TypedSection, "collectd_exec_notify", translate("Add notification command"), translate( "Here you can define external commands which will be " .. "started by collectd when certain threshold values have " .. "been reached. The values leading to invokation will be " .. "feeded to the the called programs stdin." )) notify.addremove = true notify.anonymous = true -- collectd_notify_input.cmdline notify_cmdline = notify:option( Value, "cmdline" ) notify_cmdline.default = "/usr/bin/stat-dhcpusers" -- collectd_notify_input.cmdline notify_cmduser = notify:option( Value, "cmduser" ) notify_cmduser.default = "nobody" notify_cmduser.rmempty = true notify_cmduser.optional = true -- collectd_notify_input.cmdline notify_cmdgroup = notify:option( Value, "cmdgroup" ) notify_cmdgroup.default = "nogroup" notify_cmdgroup.rmempty = true notify_cmdgroup.optional = true return m
gpl-2.0
jiankers/Atlas
lib/proxy/balance.lua
41
2807
--[[ $%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%$ --]] module("proxy.balance", package.seeall) function idle_failsafe_rw() local backend_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] if conns.cur_idle_connections > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.type == proxy.BACKEND_TYPE_RW then backend_ndx = i break end end return backend_ndx end function idle_ro() local max_conns = -1 local max_conns_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] -- pick a slave which has some idling connections if s.type == proxy.BACKEND_TYPE_RO and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and conns.cur_idle_connections > 0 then if max_conns == -1 or s.connected_clients < max_conns then max_conns = s.connected_clients max_conns_ndx = i end end end return max_conns_ndx end function cycle_read_ro() local backends = proxy.global.backends local rwsplit = proxy.global.config.rwsplit local max_weight = rwsplit.max_weight local cur_weight = rwsplit.cur_weight local next_ndx = rwsplit.next_ndx local ndx_num = rwsplit.ndx_num local ndx = 0 for i = 1, ndx_num do --ÿ¸öquery×î¶àÂÖѯndx_num´Î local s = backends[next_ndx] if s.type == proxy.BACKEND_TYPE_RO and s.weight >= cur_weight and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.pool.users[proxy.connection.client.username].cur_idle_connections > 0 then ndx = next_ndx end if next_ndx == ndx_num then --ÂÖѯÍêÁË×îºóÒ»¸öndx£¬È¨Öµ¼õÒ» cur_weight = cur_weight - 1 if cur_weight == 0 then cur_weight = max_weight end next_ndx = 1 else --·ñÔòÖ¸Ïòϸöndx next_ndx = next_ndx + 1 end if ndx ~= 0 then break end end rwsplit.cur_weight = cur_weight rwsplit.next_ndx = next_ndx return ndx end
gpl-2.0
Ennea/eUI
eActionBars/libs/LibKeyBound-1.0/Locale-esES.lua
2
2368
--[[ LibKeyBound-1.0 localization file Spanish by StiviS --]] if (GetLocale() ~= "esES") then return end local REVISION = 90000 + tonumber(string.match("$Revision: 92 $", "%d+")) if (LibKeyBoundLocale10 and REVISION <= LibKeyBoundLocale10.REVISION) then return end LibKeyBoundLocale10 = { REVISION = REVISION; Enabled = 'Modo Atajos activado'; Disabled = 'Modo Atajos desactivado'; ClearTip = format('Pulsa %s para limpiar todos los atajos', GetBindingText('ESCAPE', 'KEY_')); NoKeysBoundTip = 'No existen atajos'; ClearedBindings = 'Eliminados todos los atajos de %s'; BoundKey = 'Establecer %s a %s'; UnboundKey = 'Quitado atajo %s de %s'; CannotBindInCombat = 'No se pueden atajar teclas en combate'; CombatBindingsEnabled = 'Saliendo de combate, modo de Atajos de Teclado activado'; CombatBindingsDisabled = 'Entrando en combate, modo de Atajos de Teclado desactivado'; BindingsHelp = "Sitúese en un botón, entonces pulse una tecla para establecer su atajo. Para limpiar el Atajo del botón actual, pulse %s."; -- This is the short display version you see on the Button ["Alt"] = "A", ["Ctrl"] = "C", ["Shift"] = "S", ["NumPad"] = "N", ["Backspace"] = "BS", ["Button1"] = "B1", ["Button2"] = "B2", ["Button3"] = "B3", ["Button4"] = "B4", ["Button5"] = "B5", ["Button6"] = "B6", ["Button7"] = "B7", ["Button8"] = "B8", ["Button9"] = "B9", ["Button10"] = "B10", ["Button11"] = "B11", ["Button12"] = "B12", ["Button13"] = "B13", ["Button14"] = "B14", ["Button15"] = "B15", ["Button16"] = "B16", ["Button17"] = "B17", ["Button18"] = "B18", ["Button19"] = "B19", ["Button20"] = "B20", ["Button21"] = "B21", ["Button22"] = "B22", ["Button23"] = "B23", ["Button24"] = "B24", ["Button25"] = "B25", ["Button26"] = "B26", ["Button27"] = "B27", ["Button28"] = "B28", ["Button29"] = "B29", ["Button30"] = "B30", ["Button31"] = "B31", ["Capslock"] = "Cp", ["Clear"] = "Cl", ["Delete"] = "Del", ["End"] = "Fin", ["Home"] = "Ini", ["Insert"] = "Ins", ["Mouse Wheel Down"] = "AW", ["Mouse Wheel Up"] = "RW", ["Num Lock"] = "NL", ["Page Down"] = "AP", ["Page Up"] = "RP", ["Scroll Lock"] = "SL", ["Spacebar"] = "Sp", ["Tab"] = "Tb", ["Down Arrow"] = "Ar", ["Left Arrow"] = "Ab", ["Right Arrow"] = "Iz", ["Up Arrow"] = "De", } setmetatable(LibKeyBoundLocale10, {__index = LibKeyBoundBaseLocale10})
mit
Oxygem/Oxycore
modules/admin/get/users.lua
1
1624
-- Oxypanel Core/Admin -- File: get/users.lua -- Desc: add/edit/list users local template, database, request, user, users = oxy.template, luawa.database, luawa.request, luawa.user, oxy.users --groups local groups = database:select('user_groups', '*') template:set('groups', groups) --add user? if request.get.action == 'add' then if not user:checkPermission('AddUser') then return template:error('You don\'t have permission to do that') end return template:wrap('admin', 'users/add') --edit elseif request.get.action == 'edit' then if not user:checkPermission('EditUser') then return template:error('You don\'t have permission to do that') end if not request.get.id then return template:error('You must specify a group ID') end template:set('user', users:get(request.get.id)) return template:wrap('admin', 'users/edit') end --default: list users --permission? if not user:checkPermission('ViewUser') then return template:error('You don\'t have permission to do that') end --filters local wheres = {} --group if request.get.group then for k, v in pairs(groups) do if tonumber(v.id) == tonumber(request.get.group) then template:set('page_title_meta', 'in group ' .. v.name) break end end wheres.group = (type(request.get.group) == 'string' and request.get.group ~= '') and request.get.group or nil end --id if request.get.id then wheres.id = request.get.id end --get users local users = database:select('user', '*', wheres) template:set('page_title', 'Users') template:set('users', users) template:wrap('admin', 'users/list')
mit
osgcc/ryzom
ryzom/common/data_common/r2/r2_core_user_component_manager.lua
3
52500
r2_core = {} r2_core.UserComponentsPath = "./examples/user_components/" r2_core.UserComponentTable = {} r2_core.UserComponentManager = {} local userComponentManager = r2_core.UserComponentManager userComponentManager.CurrentExportList = {} userComponentManager.InstanceIds = {} userComponentManager.Texts = {} userComponentManager.PlotItems = {} userComponentManager.Positions = {} userComponentManager.CurrentDesc = "" userComponentManager.IsInitialized = false userComponentManager.InitialComponentToLoad = 0 -------------------------------------------------------------------------------------------------- -- Methods called when the holder specific ui buttons are pressed function r2_core:doNothing(x, y, z) end function r2_core:testIsExportable(entityId) local holder = r2:getInstanceFromId(r2_core.CurrentHolderId) assert(holder) local k, v = next(holder.Components, nil) local entity = r2:getInstanceFromId(entityId) while k do if entity.ParentInstance:isKindOf("NpcGrpFeature") and entity.ParentInstance.InstanceId == v.InstanceId then return false end if v.InstanceId == entityId then return false end k, v = next(holder.Components, k) end return true end local function getIndex(id, tbl) local k, v = next(tbl, nil) while k do if v.InstanceId and v.InstanceId == id then return k end k, v = next(tbl, k) end return -1 end function r2_core:addEntityToExporter(instanceId) local entityId = instanceId local tmpInstance = r2:getInstanceFromId(entityId) if tmpInstance:isKindOf("Npc") and tmpInstance.ParentInstance:isKindOf("NpcGrpFeature") then entityId = tmpInstance.ParentInstance.InstanceId end local entity = r2:getInstanceFromId(entityId) assert(entity) local parent = entity.ParentInstance local parentId = parent.InstanceId r2_core.UserComponentManager:replacePosition(entityId) if parent:isKindOf("DefaultFeature") then local index = getIndex(entityId, parent.Components) r2.requestMoveNode(parentId, "Components", index, r2_core.CurrentHolderId, "Components", -1) elseif parent:isKindOf("Act") then local index = getIndex(entityId, parent.Features) r2.requestMoveNode(r2:getCurrentAct().InstanceId, "Features", index, r2_core.CurrentHolderId, "Components", -1) end local container = getUI("ui:interface:r2ed_scenario") local tree = container:find("content_tree_list") tree:forceRebuild() end function r2_core:testCanPickUserComponentElement(instanceId) local instance = r2:getInstanceFromId(instanceId) assert(instance) local parent = instance.ParentInstance local holder = r2:getInstanceFromId(r2_core.CurrentHolderId) assert(holder) if parent:isKindOf("NpcGrpFeature") and holder.InstanceId == parent.ParentInstance.InstanceId then return true end if holder.InstanceId == parent.InstanceId then return true end return false end function r2_core:removeUserComponentElement(instanceId) local holder = r2:getInstanceFromId(r2_core.CurrentHolderId) assert(holder) local index = getIndex(instanceId, holder.Components) local entity = r2:getInstanceFromId(instanceId) assert(entity) local currentAct = r2:getCurrentAct() if entity:isKindOf("Region") or entity:isKindOf("Road") or entity:isBotObject() then local refPosition = r2.Scenario.Acts[0].Position r2_core.UserComponentManager:restorePosition(instanceId, refPosition) r2.requestMoveNode(r2_core.CurrentHolderId, "Components", index, r2.Scenario.Acts[0].Features[0].InstanceId, "Components", -1) elseif entity:isKindOf("Npc") then local refPosition = currentAct.Position if entity.ParentInstance:isKindOf("NpcGrpFeature") then local grpId = entity.ParentInstance.InstanceId local grpIndex = getIndex(grpId, holder.Components) r2_core.UserComponentManager:restorePosition(grpId, refPosition) r2.requestMoveNode(r2_core.CurrentHolderId, "Components", grpIndex, currentAct.InstanceId, "Features", -1) else r2_core.UserComponentManager:restorePosition(instanceId, refPosition) r2.requestMoveNode(r2_core.CurrentHolderId, "Components", index, currentAct.Features[0].InstanceId, "Components", -1) --getCurrentAct().Features[0].Components end else local refPosition = currentAct.Position r2_core.UserComponentManager:restorePosition(instanceId, refPosition) r2.requestMoveNode(r2_core.CurrentHolderId, "Components", index, currentAct.InstanceId, "Features", -1) --getCurrentAct().Features end local container = getUI("ui:interface:r2ed_scenario") local tree = container:find("content_tree_list") tree:forceRebuild() end -------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------- -- Debug local printDebug printDebug = function(tbl) local k,v = next(tbl, nil) while k do if type(v) == "table" then debugInfo(k .. " : TABLE") printDebug(v) else debugInfo(k .. " = " ..tostring(v)) end k,v = next(tbl, k) end end local foundInTable = function(tbl, key) local k, v = next(tbl, nil) while k do if (k == key) then return true end k,v = next(tbl, k) end return false end local insertExistingId = function(tblSearch, tblInsert, clientid) local k, v = next(tblSearch, nil) while k do if (k == clientid) then tblInsert[clientid] = v end k, v = next(tblSearch, k) end end local checkLinkedId = function(instanceIdTbl, refIdTbl) local k, v = next(refIdTbl, nil) while k do local key, value = next(instanceIdTbl, nil) while key do if key == k and value ~= v then refIdTbl[k] = value end key, value = next(instanceIdTbl, key) end k, v = next(refIdTbl, k) end end local countIds = function(tbl) local count = 0 local k, v = next(tbl, nil) while k do count = count + 1 k, v = next(tbl, k) end return count end local countUCIds countUCIds = function(tbl) local count = 0 local k, v = next(tbl, nil) while k do if type(v) ~= "table" and type(v) ~= "userdata" then if k == "InstanceId" or string.find(tostring(v), "UserComponent_") ~= nil or string.find(tostring(v), "UserText_") ~= nil or string.find(tostring(v), "UserItem_") ~= nil then count = count + 1 end elseif type(v) == "table" then count = count + countUCIds(v) end k, v = next(tbl, k) end return count end local findUserSlotIn = function(str) local currentSlot = r2.getUserSlot() .."_" if string.find(str, currentSlot) ~= nil then return true end return false end -------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------- function userComponentManager:init() --init usercomponent table & retrieves entries from file if not empty r2_core.UserComponentTable = {} local userComponentTableOk = loadfile("save/r2_core_user_component_table.lua") if userComponentTableOk then userComponentTableOk() end --doFile on previously loaded user component files local ucTable = r2_core.UserComponentTable self.InitialComponentToLoad = table.getn(ucTable) local k, v = next(ucTable, nil) while k do --local fun = loadfile(v[2]) r2.loadUserComponentFile(v[2]) --if not fun then -- debugInfo("Couldn't load file '"..v[2].."' while initializing UserComponentManager.") --else -- local ok, msg = pcall(fun) -- if not ok then -- debugInfo("Error while loading component '"..filename.."' err: "..msg) -- end -- debugInfo("Component '" ..v[2].."' loaded.") --end k, v = next(ucTable, k) end if r2_core.UserComponentManager.IsInitialized == false and r2_core.UserComponentManager.InitialComponentToLoad == 0 then r2_core.UserComponentManager.IsInitialized = true end end function userComponentManager:isInitialized() return self.IsInitialized end -------------------------------------------------------------------------------------------------------------------- -- Gets all the InstanceIds and the references to InstanceIds and store them separately. -- Each refId is unique and is renamed from client1_XX to userComponent_XX. -- Returns a table containing all the instanceIds and refIds. -- function userComponentManager:getRefIdTableFrom(argTbl) local refIdTbl = {} local instanceIdTbl = {} local plotItemTbl = {} local nbInstance = 0 local nbText = 0 local nbItems = 0 local addTextToUCManager = function(instanceId) local key, value = next(r2.Scenario.Texts.Texts, nil) while key do if value.InstanceId == instanceId then userComponentManager.Texts[instanceIdTbl[instanceId]] = value.Text return end key, value = next(r2.Scenario.Texts.Texts, key) end end local addItemToUCManager = function(instanceId) local key, value = next(r2.Scenario.PlotItems, nil) debugInfo("Adding '" ..instanceId.."' to manager item table") while key do if value.InstanceId == instanceId then --copy the full plot item into manager's table userComponentManager.PlotItems[plotItemTbl[instanceId]] = value return end key, value = next(r2.Scenario.PlotItems, key) end end -- Doesn't insert the value if it's already in the table. parseInstanceTable = function(tbl) --parsing string properties local key,val = next(tbl, nil) while key do if (type(val) ~= "userdata") then -- If the property is a real InstanceId if (key == "InstanceId") then -- If the instanceId is not already in the instanceIdTbl then add it as a key, with its usercomponent -- translation as value. if not foundInTable(instanceIdTbl, tostring(val)) then nbInstance = nbInstance + 1 instanceIdTbl[val] = "UserComponent_"..nbInstance end -- else if the instanceid found is a reference to another InstanceId --elseif (string.find(tostring(val), "Client1_") ~= nil) then elseif findUserSlotIn(tostring(val)) then --if exporting a dialog, rename specifically the refId pointing to the said text (stored in r2.Scenario.Texts) if key == "Says" then if not foundInTable(instanceIdTbl, tostring(val)) then nbText = nbText + 1 instanceIdTbl[val] = "UserText_" ..nbText addTextToUCManager(val) end --else if plotItem XXXXXX elseif string.find(key, "Item") ~= nil then if not foundInTable(plotItemTbl, tostring(val)) then nbItems = nbItems + 1 plotItemTbl[val] = "UserItem_" ..nbItems addItemToUCManager(val) end elseif not foundInTable(refIdTbl, tostring(val)) then if foundInTable(instanceIdTbl, tostring(val)) then --a refid pointing to an instanceid present in the component itself (zone...) insertExistingId(instanceIdTbl, refIdTbl, tostring(val)) else refIdTbl[val] = "Not exported" end end end end key,val = next(tbl, key) end --parsing userdatas key, val = next(tbl, nil) while key do if (type(val) == "userdata") then parseInstanceTable(val) end if (type(val) == "table") then --inspect(val) assert(nil) end key, val = next(tbl, key) end end local i = 1 --printDebug(argTbl) local nbExportedInstances = table.getn(argTbl) local k, v = next(argTbl, nil) while k do local tmpInstance = r2:getInstanceFromId(v) if tmpInstance ~= nil then parseInstanceTable(tmpInstance) end k, v = next(argTbl, k) end checkLinkedId(instanceIdTbl, refIdTbl) userComponentManager.InstanceIds = instanceIdTbl local refIdTable = { RefIds = refIdTbl, InstanceIds = instanceIdTbl, PlotItemsId = plotItemTbl } return refIdTable end -------------------------------------------------------------------------------------------------------------------- local generatePreCode = function(fName) local userComponentBody = "" local writePlotItemBlock = function(plotItem, ucId, index) --file:write("\t{\n") local str = "\t{\n" local k, v = next(plotItem, nil) while k do if k == "InstanceId" then --file:write("\t\t[" ..string.format("%q", k).. "]\t=\t" ..string.format("%q", ucId).. ",\n") str = str .."\t\t[" ..string.format("%q", k).. "]\t=\t" ..string.format("%q", ucId).. ",\n" elseif type(v) == "string" then --file:write("\t\t[" ..string.format("%q", k).. "]\t=\t" ..string.format("%q", v).. ",\n") str = str .."\t\t[" ..string.format("%q", k).. "]\t=\t" ..string.format("%q", v).. ",\n" else --file:write("\t\t[" ..string.format("%q", k).. "]\t=\t" ..tostring(v).. ",\n") str = str .."\t\t[" ..string.format("%q", k).. "]\t=\t" ..tostring(v).. ",\n" end k, v = next(plotItem, k) end --file:write("\t},\n") str = str .."\t},\n" return str end local featureName = fName if featureName == nil or featureName == "" then featureName = "UnnamedComponent" end local str = "" -- "-- <Creation_Header>\n" --.."-- r2_core.CurrentFeatureName='" ..featureName.. "'\n" --.."-- </Creation_Header>\n\n\n" str = "r2.Features."..featureName.. " = {}\n\n" .."local feature = r2.Features." ..featureName.."\n\n" .."feature.Name=\"".. featureName.."\"\n\n" .."feature.Description=\"A user exported feature.\"\n" .."feature.Components = {}\n\n" --file:write(str) userComponentBody = userComponentBody .. str do local count = 0 --file:write("feature.PlotItems = \n{\n") userComponentBody = userComponentBody .."feature.PlotItems = \n{\n" local k, v = next(userComponentManager.PlotItems, nil) while k do count = count + 1 userComponentBody = userComponentBody..writePlotItemBlock(v, k, count) k, v = next(userComponentManager.PlotItems, k) end --file:write("}\n\n") userComponentBody = userComponentBody .."}\n\n" end -- component.createComponent str = "feature.createUserComponent = function(x, y)\n\t" .."local comp = r2.newComponent('UserComponentHolder')\n\t" .."assert(comp)\n\n\t" .."comp.Base = \"palette.entities.botobjects.user_event\"\n\t" .."comp.Name = r2:genInstanceName(ucstring('"..featureName.."')):toUtf8()\n\t" .."comp.Position.x = x\n\t" .."comp.Position.y = y\n\t" .."comp.Position.z = r2:snapZToGround(x, y)\n\n\t" .."comp.Description = '" ..userComponentManager.CurrentDesc.. "'\n\n\t" --file:write(str) userComponentBody = userComponentBody .. str do --file:write("comp.Texts = \n\t{\n") userComponentBody = userComponentBody .."comp.Texts = \n\t{\n" local key, value = next(userComponentManager.Texts, nil) while key do --file:write("\t\t[" ..string.format("%q", key).. "]\t=\t[[" ..value.. "]],\n") userComponentBody = userComponentBody .. "\t\t[" ..string.format("%q", key).. "]\t=\t[[" ..value.. "]],\n" key, value = next(userComponentManager.Texts, key) end --file:write("\t}\n\n\t") userComponentBody = userComponentBody .. "\t}\n\n\t" end str = "comp.Components = {}\n\t" .."local tmpComponents = {}\n\t" userComponentBody = userComponentBody..str --file:write(str) return userComponentBody end -------------------------------------------------------------------------------------------------------------------- local generatePostCode = function(fName) local featureName = fName if featureName == nil or featureName == "" then featureName = "UserFeature" end local str = "" str = str .."r2_core.UserComponentManager:insertAll(feature, comp, tmpComponents)\n\n\t" .."comp._Seed = os.time()\n\n\t" .."return comp\n" .."end\n\n\n" -- ! component.CreateComponent .."\n\nr2.Features[\""..featureName.."\"] = feature" .."\n -- !"..featureName.." user exported\\o/ \n\n\n" return str --file:write(str) end ------------------------------------------------------------------------------------------------------------------- -- Generates the LUA code corresponding to the selected instances. -- filename: file in which the code will be written. -- argTbl: contains all the instanceIds selected for export. -- instanceIdTbl: hashtable containing all clientIds (key) and their matching user component id (value). This table -- is returned by the getRefIdTableFrom method. -- refPosition: reference coordinates chosen by the user on export. function userComponentManager:componentToFile(filename, featureName, argTbl, refIdTbl, refPosition) local instanceIdTbl = refIdTbl.InstanceIds local plotItemsTbl = refIdTbl.PlotItemsId local body = "" local function writeTab(file, nb) local i = nb while i > 0 do file:write("\t") i = i - 1 end end local function writeTabInString(str, nb) local tmp = str local i = nb while i > 0 do tmp = tmp..("\t") i = i - 1 end return tmp end --local function writeDataToFile(file, tbl, nbTab, isTopLevel) local function writeDataToString(str, tbl, nbTab, isTopLevel) local userComponentBody = str local key,val = next(tbl, nil) while key do --writing all properties except userdatas if type(val) ~= "userdata" then --writeTab(file, nbTab) userComponentBody = writeTabInString(userComponentBody, nbTab) if isTopLevel == true and key == "InheritPos" then --file:write("InheritPos = 1,\n") userComponentBody = userComponentBody .. "InheritPos = 1,\n" else if type(key) == "number" then --file:write("[" ..tostring(key + 1).. "] = ") userComponentBody = userComponentBody .. "[" ..tostring(key + 1).. "] = " else --file:write(tostring(key) .. " = ") end userComponentBody = userComponentBody .. tostring(key).. " = " end -- String/number value if type(val) == "number" then --file:write(val..",\n") userComponentBody = userComponentBody..tostring(val)..", \n" else local str = val if key == "InstanceId" or findUserSlotIn(val) then str = instanceIdTbl[val] end if str == nil then str = plotItemsTbl[val] end if str == nil then str = "" end --when finding a instanceId which is referring to a non exported entity --file:write(string.format("%q", str) ..",\n") userComponentBody = userComponentBody .. string.format("%q", str) ..",\n" end end end key,val = next(tbl, key) end --writing userdatas key, val = next(tbl, key) while key do if type(val) == "userdata" then --writeTab(file, nbTab) userComponentBody = writeTabInString(userComponentBody, nbTab) if type(key) ~= "number" then --file:write(tostring(key) .. " = ") userComponentBody = userComponentBody ..tostring(key).. " = " end --file:write("\n") userComponentBody = userComponentBody .."\n" --writeTab(file, nbTab) userComponentBody = writeTabInString(userComponentBody, nbTab) --file:write("{\n") userComponentBody = userComponentBody .."{\n" userComponentBody = writeDataToString(userComponentBody, val, nbTab + 1, false) --writeTab(file, nbTab) userComponentBody = writeTabInString(userComponentBody, nbTab) --file:write("},\n") userComponentBody = userComponentBody .."}, \n" end key,val = next(tbl, key) end return userComponentBody end -- -- Write a code block for each component of the user feature. local function writeComponentBlocks(str, tbl) local userComponentBody = str local i = 1 local nbInstanceIds = table.getn(tbl) while i <= nbInstanceIds do local tmpInstance = r2:getInstanceFromId(tbl[i]) if (tmpInstance == nil) then debugInfo("Cannot export entity with intanceId= " ..tostring(tbl[i])) assert(tmpInstance) else local compName = "uComp" ..i --+ 1 --file:write("do\n\t\t") userComponentBody = userComponentBody .. "do\n\t\t" --file:write("local " ..compName.. " = \n\t\t{\n") userComponentBody = userComponentBody .. "local " ..compName.. " = \n\t\t{\n" --writeDataToFile(file, tmpInstance, 3, true) userComponentBody = writeDataToString(userComponentBody, tmpInstance, 3, true) --file:write("\t\t} --!" ..compName.. " \n\n\t\t") userComponentBody = userComponentBody .."\t\t} --!" ..compName.. " \n\n\t\t" --file:write("table.insert(tmpComponents, "..compName.. ")\n\t") userComponentBody = userComponentBody .."table.insert(tmpComponents, "..compName.. ")\n\t" --file:write("end\n\n\t") userComponentBody = userComponentBody .."end\n\n\t" end i = i + 1 end return userComponentBody end --f = io.open(filename, "w") --assert(f) body = body..generatePreCode(featureName) body = writeComponentBlocks(body, argTbl) body = body .. generatePostCode(featureName) --f:close() --return res local headerInfo = {} table.insert(headerInfo, {CurrentFeatureName = featureName}) r2.saveUserComponent(filename, headerInfo, body) end ------------------------------------------------------------------------------------------------------------------- -- Builds a table containing all user component ids (key) with their new instance id (ClientId_n) on import. -- tmpComponents: contains all the user feature components, in which all instance ids are user component ids. -- currentMaxId: max entity id in the current act (on user feature import). local function generateReverseIdTable(tmpComponents, texts, currentMaxId) function findpattern(text, pattern, start) return string.sub(text, string.find(text, pattern, start)) end local function findMaxId(component, maxId, maxPlotItemId) local maxIdLocal = maxId local maxItemId = maxPlotItemId local key, value = next(component, nil) while key do if type(value) ~= "table" then if key == "InstanceId" or string.find(tostring(value), "UserComponent_") ~= nil then local tmpId = tonumber(findpattern(tostring(value), "%d+")) if tmpId and tmpId > maxIdLocal then maxIdLocal = tmpId end end if string.find(tostring(value), "UserItem_") ~= nil then local tmpItemId = tonumber(findpattern(tostring(value), "%d+")) if tmpItemId and tmpItemId > maxItemId then maxItemId = tmpItemId end end end key, value = next(component, key) end --maxIdLocal = maxIdLocal + maxItemId key, value = next(component, nil) while key do if type(value) == "table" then local tmpId, tmpItemId = findMaxId(value, maxIdLocal, maxItemId) if tmpId and tmpId > maxIdLocal then maxIdLocal = tmpId end if tmpItemId and tmpItemId > maxItemId then maxItemId = tmpItemId end end key, value = next(component, key) end return maxIdLocal, maxItemId end local reverseIdTable = {} local maxId, maxPlotItemId = findMaxId(tmpComponents, 0, 0) local i = 1 local id = 0 while i <= maxId do id = i + currentMaxId local ucName = "UserComponent_" ..i --reverseIdTable[ucName] = "Client1_" ..id reverseIdTable[ucName] = tostring(r2.getUserSlot()).."_"..id i = i + 1 end local j = 1 while j <= maxPlotItemId do id = i + currentMaxId local ucName = "UserItem_" ..j --reverseIdTable[ucName] = "Client1_" ..id reverseIdTable[ucName] = tostring(r2.getUserSlot()).."_"..id j = j + 1 i = i + 1 end --register component texts when a dialog has been exported if texts ~= nil then key, value = next(texts, nil) while key do local id = r2.registerText(tostring(value)) reverseIdTable[key] = id.InstanceId key, value = next(texts, key) end end return reverseIdTable end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:reattributeClientId(tbl, reverseIdTable) local key, value = next(tbl, nil) while key do if (type(value) ~= "userdata") then if key == "InstanceId" or string.find(tostring(value), "UserComponent_") ~= nil or string.find(tostring(value), "UserText_") ~= nil or string.find(tostring(value), "UserItem_") ~= nil then local id = reverseIdTable[value] assert(id) tbl[key] = id end end key,value = next(tbl, key) end key, value = next(tbl, nil) while key do if type(value) ~= "string" and type(value) ~= "number" then userComponentManager:reattributeClientId(value, reverseIdTable) end key, value = next(tbl, key) end return tbl end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:insertPlotItem(plotItem, reverseIdTable) local function isAlreadyUsed(plotItem) local k, v = next(r2.Scenario.PlotItems, nil) while k do if v.SheetId and v.SheetId == plotItem.SheetId then reverseIdTable[plotItem.InstanceId] = v.InstanceId return true end k, v = next(r2.Scenario.PlotItems, k) end userComponentManager:reattributeClientId(plotItem, reverseIdTable) return false end if isAlreadyUsed(plotItem) == false then --insert plot item in scenario r2.requestInsertNode(r2.Scenario.InstanceId, "PlotItems", -1, "", plotItem) --r2:setCookie(newItem.InstanceId, "SelfCreate", true) --TODO = delete plotItem from pitem table in scenario so that it cannot be used twice return true end return false end -------------------------------------------------------------------------------------------------------------------- -- insertAll is called in the generated userFeature upon instanciation. -- Inserts all userComponents into the userFeature's components table after having renamed all -- userComponentIds into clientIds. -- function userComponentManager:insertAll(feature, comp, tmpComponents) local texts = comp.Texts local items = feature.PlotItems local components = comp.Components local currentMaxId = r2.getMaxId() local reverseIdTable = generateReverseIdTable(tmpComponents, texts, currentMaxId) local range = 0 local nbItems = 0 local k, v = next(items, nil) while k do local inserted = self:insertPlotItem(v, reverseIdTable) if inserted == true then nbItems = nbItems + 1 end k, v = next(items, k) end local key, value = next(tmpComponents, nil) while key do range= range + countUCIds(value) + 3 userComponentManager:reattributeClientId(value, reverseIdTable) table.insert(components , value) key, value = next(tmpComponents, key) end r2.reserveIdRange(range + nbItems) end --------------------------------------------------------------------------------------------------------------------- -- register the forms needed by the manager (save form, missing ids warning form). -- Called along with the other features registerForms method. function userComponentManager.registerForms() local fileListXML = [[ <group id="tb_enclosing" sizeref="wh" w="-16" h="0" x="16" y="0" posref="TL TL"> <instance template="inner_thin_border" inherit_gc_alpha="true"/> </group> <group id="enclosing" sizeref="w" w="-10" h="196" x="5" y="-5" posref="TL TL"> <group id="file_list" type="list" active="true" x="16" y="0" posref="TL TL" sizeref="w" child_resize_h="true" max_sizeref="h" max_h="0" > </group> <ctrl style="skin_scroll" id="scroll_bar" align="T" target="file_list" /> </group> <group id="gap" posref="BL TL" posparent="enclosing" w="1" h="6" /> ]] function getComponentNameFromFile(filename) local prefixedFilename = r2_core.UserComponentsPath..filename local f = io.open(prefixedFilename,"r") assert(f) f:read("*line") f:read("*line") f:read("*line") f:read("*line") f:read("*line") local line = f:read("*line") if string.find(line, "CurrentFeatureName") == nil then messageBox("Unable to load a component from this file. Please select another file.") return "No components found" end f:close() local luaString = string.sub(line, 3) loadstring(luaString)() local componentName = CurrentFeatureName CurrentFeatureName = "" return componentName end local function getComponentFiles(searchPath) local files = getPathContent(searchPath) local componentFiles = {} for k, v in pairs(files) do local prefixedFilename = r2_core.UserComponentsPath..nlfile.getFilename(v) local f = io.open(prefixedFilename,"r") assert(f) local header = r2.getFileHeader(prefixedFilename) --TODO : accès fichier md5 --local line = f:read("*line") --if line == "-- <Creation_Header>" then if header.CurrentFeatureName then table.insert(componentFiles, v) end end return componentFiles end function r2_core.setCurrSelectedFile(filename, formAttr) local formInstance = r2.CurrentForm.Env.FormInstance --inspect(formInstance) if formInstance.LastFileButton then formInstance.LastFileButton.pushed = false end getUICaller().pushed = true formInstance.LastFileButton = getUICaller() r2.CurrentForm.Env.FormInstance[formAttr] = filename if r2.CurrentForm.Env.FormInstance["ComponentName"] then r2.CurrentForm.Env.FormInstance["ComponentName"] = getComponentNameFromFile(filename) end r2.CurrentForm.Env.updateAll() local eb = r2.CurrentForm:find("eb") setCaptureKeyboard(eb) eb:setSelectionAll() end function r2.setCurrSelectedComponent(compName) local formInstance = r2.CurrentForm.Env.FormInstance if formInstance.LastFileButton then formInstance.LastFileButton.pushed = false end getUICaller().pushed = true formInstance.LastFileButton = getUICaller() r2.CurrentForm.Env.FormInstance.ComponentName = compName r2.CurrentForm.Env.updateAll() local eb = r2.CurrentForm:find("eb") setCaptureKeyboard(eb) eb:setSelectionAll() end -- called at init to fill the file list local function showFileList(formInstance) local fileGroupList = r2.CurrentForm:find('file_list') r2.CurrentForm.Env.FormInstance["ComponentFileName"] = "UserComponent1.lua" r2.CurrentForm.Env.FormInstance["Name"] = "UserComponent1" r2.CurrentForm.Env.updateAll() --local searchPath = select(config.R2ScenariiPath, "save") local searchPath = r2_core.UserComponentsPath --local files = getPathContent(searchPath) local files = getComponentFiles(searchPath) table.sort(files) fileGroupList:clear() for k, v in pairs(files) do if string.lower(nlfile.getExtension(v)) == "lua" then local shortFilename = nlfile.getFilename(v) local entry = createGroupInstance("r2ed_filelist_entry", "", { id = tostring(k), text = shortFilename, params_l="r2_core.setCurrSelectedFile('" .. shortFilename .. "', 'ComponentFileName')" }) fileGroupList:addChild(entry) end end setCaptureKeyboard(r2.CurrentForm:find("eb")) end --called at init to fill load form local function showUserComponentFileList(formInstance) local fileGroupList = r2.CurrentForm:find('file_list') --local searchPath = select(config.R2ScenariiPath, "save") local searchPath = r2_core.UserComponentsPath local files = getPathContent(searchPath) table.sort(files) local defaultValue = "" fileGroupList:clear() for k, v in pairs(files) do if string.lower(nlfile.getExtension(v)) == "lua" then local shortFilename = nlfile.getFilename(v) if defaultValue == "" then defaultValue = shortFilename end local entry = createGroupInstance("r2ed_filelist_entry", "", { id = tostring(k), text = shortFilename, params_l="r2_core.setCurrSelectedFile('" .. shortFilename .. "', 'FileName')" }) fileGroupList:addChild(entry) end end setCaptureKeyboard(r2.CurrentForm:find("eb")) end --called at init to fill Unload Form local function showUserComponentList(formInstance) local fileGroupList = r2.CurrentForm:find('file_list') local featureNameTable = r2.FeatureTree.getUserComponentList() for k, v in pairs(featureNameTable) do local entry = createGroupInstance("r2ed_filelist_entry", "", {id = tostring(v), text=tostring(v), params_l="r2.setCurrSelectedComponent('"..tostring(v).."')" }) fileGroupList:addChild(entry) end setCaptureKeyboard(r2.CurrentForm:find("eb")) end local function showMissingComponents() local formUI = r2:getForm("MissingIdsForm") local text = "The following objects are referenced in exported objects but will not be exported:\n" local k, v = next(formUI.Env.FormInstance.Value, nil) while k do text = text .."# " ..v.."\n" k, v = next(formUI.Env.FormInstance.Value, k) end text = text .."Continue anyway?" formUI:find('name_list').hardtext = text formUI.Env:updateAll() formUI.Env.updateSize() formUI:updateCoords() formUI:center() formUI:updateCoords() end r2.Forms.MissingIdsForm = { Caption = "uiR2EdMissingRefsWarning", PropertySheetHeader = [[ <view type="text" id="name_list" multi_line="true" sizeref="w" w="-36" x="4" y="-2" posref="TL TL" global_color="true" fontsize="14" shadow="true" hardtext=""/> ]], Prop = { {Name="Value", Type="Table", Visible=false} }, onShow = showMissingComponents } r2.Forms.SaveUserComponent = { Caption = "uiR2EDExportUserComponent", PropertySheetHeader = fileListXML, Prop = { {Name="Name", Type="String", Category="uiR2EDRollout_Save", ValidateOnEnter = true }, {Name="ComponentFileName", Type="String", Category="uiR2EDRollout_Save"}, {Name="ComponentName", Type="Table", Visible = false} }, onShow = showFileList } r2.Forms.LoadUserComponent = { Caption = "uiR2EDExportLoadUserComponent", PropertySheetHeader = fileListXML, Prop = { {Name="FileName", Type="String", Category="uiR2EDRollout_Load", ValidateOnEnter = true }, {Name="ComponentName", Type="String", Category="uiR2EDRollout_Load", WidgetStyle="StaticText"}, }, onShow = showUserComponentFileList } r2.Forms.UnloadUserComponent = { Caption = "uiR2EDExportUnloadUserComponent", PropertySheetHeader = fileListXML, Prop = { {Name="ComponentName", Type="String", Category="uiR2EDRollout_Unload", ValidateOnEnter = true }, }, onShow = showUserComponentList } end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:buildCurrentExportList(holder) table.clear(self.CurrentExportList) local components = holder.Components local k, v = next(components, nil) while k do if v and v.InstanceId then table.insert(self.CurrentExportList, v.InstanceId) end k, v = next(components, k) end end -------------------------------------------------------------------------------------------------------------------- -- Tbl is a table containing all the instanceIds selected for export. function userComponentManager:export(list, refX, refY, refZ) --local exportList = self.CurrentExportList local exportList = list assert(exportList) --builds a table containing all instanceIds and their corresponding userComponentId local refIdTable = userComponentManager:getRefIdTableFrom(exportList) local missingIds = refIdTable.RefIds local missingIdsCount = 0 --XXXXXX --TODO = reattribute UC ids for plotitems + container -- User component filename confirmation local function onFileOk(form) if (form.ComponentFileName ~= nil and type(form.ComponentFileName) == "string" and form.RefPosition ~= nil) then if form.ComponentFileName == "" or string.len(form.ComponentFileName) < 2 then messageBox(i18n.get("uiR2EDInvalidName")) return end if string.find(form.ComponentFileName, '\.lua', -4) == nil then form.ComponentFileName = form.ComponentFileName .. ".lua" end local refPosition = form.RefPosition local filename = form.ComponentFileName local prefixedFilename = r2_core.UserComponentsPath..filename local featureName = form.Name userComponentManager:computeAllPositions(exportList, refPosition, refIdTable.InstanceIds) userComponentManager:componentToFile(prefixedFilename, featureName, exportList, refIdTable, refPosition) userComponentManager:clear() --the component is automatically loaded on receive save callback --r2.loadUserComponentFile(prefixedFilename) end end local function onFileCancel(form) end -- Position confirmation local function posOk(x, y, z) debugInfo(string.format("Validate export with reference position (%d, %d, %d)", x, y, z)) local refPosition = {} refPosition["x"] = x refPosition["y"] = y refPosition["z"] = z refPosition["InstanceId"] = "" refPosition["Class"] = "Position" r2:doForm("SaveUserComponent", {RefPosition=refPosition}, onFileOk, onFileCancel) end local function posCancel() debugInfo("Export canceled.") end -- Export confirmation when missing some ids local function confirmExport() debugInfo("Export confirmed.") r2:choosePos("", posOk, posCancel, "") end local function cancelExport() debugInfo("Export canceled.") end local missingTbl = {} local key, value = next(missingIds, nil) while key do if value == "Not exported" then local tmpInstance = r2:getInstanceFromId(key) if tmpInstance ~= nil then missingIdsCount = missingIdsCount + 1 table.insert(missingTbl, tmpInstance.Name) debugInfo("Object named '" ..tmpInstance.Name .."' is referenced in an exported object but will not be exported.") end end key, value = next(missingIds, key) end if missingIdsCount ~= 0 then debugInfo(tostring(missingIdsCount) .." object(s) referenced but not exported. Continue anyway?y/n") r2:doForm("MissingIdsForm", {Value=missingTbl}, confirmExport, cancelExport) else --r2:choosePos("", posOk, posCancel, "") posOk(refX, refY, refZ) end end -- !export -------------------------------------------------------------------------------------------------------------------- function userComponentManager:getCurrentExportList() return userComponentManager.CurrentExportList end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:isInExportList(target) local targetId = target.InstanceId local k, v = next(self.CurrentExportList, nil) while k do if v == targetId then return true end -- test if not a son of an already exported element local currParent = target.ParentInstance while currParent ~= nil do if currParent.InstanceId == v then return true end currParent = currParent.ParentInstance end k, v = next(self.CurrentExportList, k) end return false end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:getCurrentExportList() return userComponentManager.CurrentExportList end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:isInExportList(target) local targetId = target.InstanceId local k, v = next(self.CurrentExportList, nil) while k do if v == targetId then return true end -- test if not a son of an already exported element local currParent = target.ParentInstance while currParent ~= nil do if currParent.InstanceId == v then return true end currParent = currParent.ParentInstance end k, v = next(self.CurrentExportList, k) end return false end --------------------------------------------------------------------------------------------------------------------- function userComponentManager:addToExportList(instanceId) local instance = r2:getInstanceFromId(instanceId) if instance == nil then debugInfo("UserComponentManager:AddToExportList : no instance") return false end table.insert(self.CurrentExportList, instanceId) return true end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:clear() table.clear(userComponentManager.InstanceIds) table.clear(userComponentManager.Texts) table.clear(userComponentManager.PlotItems) table.clear(userComponentManager.Positions) table.clear(userComponentManager.CurrentExportList) userComponentManager.CurrentExportList = {} userComponentManager.CurrentDesc = "" debugInfo("UserComponentManager tables cleared.") end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:computeAllPositions(argTbl, refPosition, refIdTable) local function buildPosition(instance, isTopLevel, refPosition) local position = {} if not instance.Position then return nil end if instance ~= nil and (instance.InheritPos == 0 or isTopLevel == true) then position["x"] = r2.getWorldPos(instance).x - refPosition["x"] position["y"] = r2.getWorldPos(instance).y - refPosition["y"] position["z"] = 0 else position["x"] = instance.Position.x position["y"] = instance.Position.y position["z"] = instance.Position.z end position["InstanceId"] = refIdTable[instance.Position.InstanceId] position["Class"] = "Position" return position end local function computePositions(instance, isTopLevel, refPosition) assert(instance) local localRefPos = nil localRefPos = buildPosition(instance, isTopLevel, refPosition) if localRefPos ~= nil and not userComponentManager.Positions[instance.Position.InstanceId] then userComponentManager.Positions[instance.Position.InstanceId] = localRefPos elseif localRefPos == nil then localRefPos = refPosition end local key, value = next(instance, nil) while key do if type(value) == "userdata" then local subInstance = value computePositions(subInstance, false, localRefPos) end key, value = next(instance, key) end end if argTbl == nil then else local i = 1 local nbExportedInstances = table.getn(argTbl) while i <= nbExportedInstances do local tmpInstance = r2:getInstanceFromId(argTbl[i]) if tmpInstance ~= nil then computePositions(tmpInstance, true, refPosition) end i = i + 1 end end end --------------------------------------------------------------------------------------------------------------- function userComponentManager:removeIdFromExportList(id) local exportList = self.CurrentExportList assert(exportList) local k, v = next(exportList, nil) while k do if v == id then break end k, v = next(exportList, k) end if k ~= nil then table.remove(exportList,k) if table.getn(exportList) == 0 then self.CurrentExportList = {} end debugInfo(tostring(v) .." removed from exportList") end end -------------------------------------------------------------------------------------------------------------- function userComponentManager:registerUserComponentData(fileName) local function checkEntry(entry) local ucTable = r2_core.UserComponentTable local k, v = next(ucTable, nil) while k do if v[1] == entry[1] and self:isInitialized() == true then messageBox("A UserComponent called '"..entry[1].."' is already loaded. Unload it before loading another component with the same name.") return false end if v[2] == entry[2] and self:isInitialized() == true then messageBox("This file has already been loaded.") return false end k, v = next(ucTable, k) end return true end local f = io.open(fileName,"r") assert(f) f:read("*line") f:read("*line") f:read("*line") f:read("*line") f:read("*line") local line = f:read("*line") f:close() local luaString = string.sub(line, 3) loadstring(luaString)() local currentFeatureName = tostring(CurrentFeatureName) local entry = { currentFeatureName, fileName } if checkEntry(entry) == false then return end table.insert(r2_core.UserComponentTable, entry) local userComponentTable = r2_core.UserComponentTable local userComponentTableFile = io.open("save/r2_core_user_component_table.lua", "w") userComponentTableFile:write("r2_core.UserComponentTable = \n{\n") local k, v = next(userComponentTable , nil) while k do if v then userComponentTableFile:write("\t{") userComponentTableFile:write(string.format("%q", v[1]) ..", ") userComponentTableFile:write(string.format("%q", v[2]) ..", ") userComponentTableFile:write("},\n") end k, v = next(userComponentTable, k) end userComponentTableFile:write("} --!UserComponentTable") userComponentTableFile:close() end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:unregisterComponent(featureName) local userComponentTable = r2_core.UserComponentTable local k, v = next(userComponentTable, nil) while k do if v[1] == featureName then break end k, v = next(userComponentTable, k) end if k ~= nil then table.remove(userComponentTable,k) if table.getn(userComponentTable) == 0 then r2_core.UserComponentTable = {} end debugInfo(tostring(v[1]) .." removed from loaded usercomponent table.") end local userComponentTableFile = io.open("save/r2_core_user_component_table.lua", "w") userComponentTableFile:write("r2_core.UserComponentTable = \n{\n") local k, v = next(userComponentTable , nil) while k do if v then userComponentTableFile:write("\t{") userComponentTableFile:write(string.format("%q", v[1]) ..", ") userComponentTableFile:write(string.format("%q", v[2]) ..", ") userComponentTableFile:write("},\n") end k, v = next(userComponentTable, k) end userComponentTableFile:write("} --!UserComponentTable") userComponentTableFile:close() end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:unloadUserComponent() local function checkFeatureName(name) local tbl = r2_core.UserComponentTable local k, v = next(tbl, nil) while k do if v[1] == name then return true end k, v = next(tbl, k) end return false end local function onChoiceOk(form) local featureName = form.ComponentName if featureName == "" or checkFeatureName(featureName) == false then messageBox("This User Component is not loaded.") return end userComponentManager:unregisterComponent(featureName) r2.FeatureTree.removeUCFromTree(featureName) local featureGroupList = r2:getForm("UnloadUserComponent"):find('file_list'):clear() --inspect(featureGroupList) --local featureNode = featureGroupList:getRootNode():getNodeFromId(featureName) --featureNode:getFather():deleteChild(featureNode) end local function onChoiceCancel() local featureGroupList = r2:getForm("UnloadUserComponent"):find('file_list'):clear() end r2:doForm("UnloadUserComponent", {}, onChoiceOk, onChoiceCancel) end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:loadUserComponent(fileName, body, header) --TODO : loading md5 --local ok = loadfile(fileName) local ok = loadstring(body) if not ok then messageBox("UserComponentManager: Couldn't load file '" ..fileName.."'.") return false end ok() assert(header["CurrentFeatureName"]) local currentFeatureName = header["CurrentFeatureName"] local userFeature = r2.Features[currentFeatureName] local componentId, component = next(userFeature.Components, nil) while (component ~= nil) do debugInfo("Registering user component " .. component.Name) r2.registerComponent(component) local class = r2.Classes[component.Name] class.NameToProp = {} for k, prop in pairs(class.Prop) do if prop.Name == nil then debugInfo("Found a property in class " .. tostring(class.Name) .. " with no field 'Name'") end class.NameToProp[prop.Name] = prop end assert(class) r2.Subclass(class) r2.registerGenerator(class) componentId, component = next(userFeature.Components, componentId) end r2.FeatureTree.addUserComponentNode(currentFeatureName) if self.IsInitialized == false then self.InitialComponentToLoad = self.InitialComponentToLoad - 1 else userComponentManager:registerUserComponentData(fileName) end end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:loadUserComponentFile() local function onChoiceOk(form) local filename = form.FileName local prefixedFilename = r2_core.UserComponentsPath..filename r2.loadUserComponentFile(prefixedFilename) end local function onChoiceCancel() end r2:doForm("LoadUserComponent", {}, onChoiceOk, onChoiceCancel) end --------------------------------------------------------------------------------------------------------------- function userComponentManager:computeNewPosition(instanceId, refPosition) local function buildPosition(instance, isTopLevel, refPosition) --local position = {} local position = r2.newComponent("Position") if not instance.Position then return nil end if instance ~= nil and (instance.InheritPos == 0 or isTopLevel == true) then position["x"] = r2.getWorldPos(instance).x - refPosition["x"] position["y"] = r2.getWorldPos(instance).y - refPosition["y"] position["z"] = r2:snapZToGround(r2.getWorldPos(instance).x, r2.getWorldPos(instance).y) - refPosition["z"] else position["x"] = instance.Position.x position["y"] = instance.Position.y position["z"] = instance.Position.z end --position["InstanceId"] = instance.Position.InstanceId --position["Class"] = "Position" return position end local function computePositions(instance, isTopLevel, refPosition) assert(instance) local localRefPos = nil localRefPos = buildPosition(instance, isTopLevel, refPosition) if localRefPos ~= nil and not userComponentManager.Positions[instance.Position.InstanceId] then userComponentManager.Positions[instance.Position.InstanceId] = localRefPos elseif localRefPos == nil then localRefPos = refPosition end local key, value = next(instance, nil) while key do if type(value) == "userdata" then local subInstance = value computePositions(subInstance, false, localRefPos) end key, value = next(instance, key) end end local tmpInstance = r2:getInstanceFromId(instanceId) if tmpInstance ~= nil then computePositions(tmpInstance, true, refPosition) end --table.clear(userComponentManager.Positions) end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:insertNewPosition(instanceId) local instance = r2:getInstanceFromId(instanceId) local newPosition = userComponentManager.Positions[instance.Position.InstanceId] if not newPosition then debugInfo("Can't retrieve new position for '"..tostring(instance.Position.InstanceId)) assert(0) end r2.requestSetNode(instanceId, "Position", newPosition) end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:replacePosition(instanceId) local currentHolder = r2:getInstanceFromId(r2_core.CurrentHolderId) assert(currentHolder) local refPosition = currentHolder.Position self:computeNewPosition(instanceId, refPosition) self:insertNewPosition(instanceId) end -------------------------------------------------------------------------------------------------------------------- function userComponentManager:restorePosition(instanceId, refPosition) local instance = r2:getInstanceFromId(instanceId) local newPosition = r2.newComponent("Position") if not instance.Position then return nil end if instance ~= nil then newPosition["x"] = r2.getWorldPos(instance).x - refPosition["x"] newPosition["y"] = r2.getWorldPos(instance).y - refPosition["y"] newPosition["z"] = r2:snapZToGround(r2.getWorldPos(instance).x, r2.getWorldPos(instance).y) - refPosition["z"] end r2.requestSetNode(instanceId, "Position", newPosition) end -------------------------------------------------------------------------------------------------------------------- function r2.loadUserComponentCallback(filename, body, header) r2_core.UserComponentManager:loadUserComponent(filename, body, header) if r2_core.UserComponentManager.IsInitialized == false and r2_core.UserComponentManager.InitialComponentToLoad == 0 then debugInfo("# UserComponentManager init done.") r2_core.UserComponentManager.IsInitialized = true end end -------------------------------------------------------------------------------------------------------------------- function r2.displayModifiedUserComponentFileError() messageBox("You cannot load a UserComponent file which has been externally modified") end
agpl-3.0
vzaramel/kong
kong/dao/postgres/query_builder.lua
1
5822
local _M = {} local constants = require "kong.constants" local pgmoon = require "pgmoon" local pg = pgmoon.new({}); local function escape_literal(s) return pg:escape_literal(s) end local function escape_identifier(s) return pg:escape_identifier(s) end local function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end local function select_fragment(table_name, select_columns) if select_columns then assert(type(select_columns) == "table", "select_columns must be a table") select_columns = table.concat(select_columns, ", ") else select_columns = "*" end return string.format("SELECT %s FROM %s", select_columns, escape_identifier(table_name)) end local function insert_fragment(table_name, insert_values) local values, columns = {}, {} for column, value in pairs(insert_values) do table.insert(values, escape_literal(value)) table.insert(columns, escape_identifier(column)) end local columns_names_str = table.concat(columns, ", ") local values_str = table.concat(values, ", ") return string.format("INSERT INTO %s(%s) VALUES(%s)", escape_identifier(table_name), columns_names_str, values_str) end local function update_fragment(table_name, update_values) local values, update_columns = {}, {} for column, value in pairs(update_values) do table.insert(update_columns, escape_identifier(column)) table.insert(values, string.format("%s = %s", escape_identifier(column), escape_literal(value))) end values = table.concat(values, ", ") return string.format("UPDATE %s SET %s", escape_identifier(table_name), values) end local function delete_fragment(table_name) return string.format("DELETE FROM %s", escape_identifier(table_name)) end local function where_fragment(where_t, no_filtering_check) if not where_t then where_t = {} end assert(type(where_t) == "table", "where_t must be a table") if next(where_t) == nil then if not no_filtering_check then return "" else error("where_t must contain keys") end end local where_parts = {} for column, value in pairs(where_t) do -- don't pass database_null_ids if value ~= constants.DATABASE_NULL_ID then table.insert(where_parts, string.format("%s = %s", escape_identifier(column), escape_literal(value))) end end where_parts = table.concat(where_parts, " AND ") return string.format("WHERE %s", where_parts) end local function paging_fragment(options) local paging_str = '' if not options then return paging_str end if options.paging_state then paging_str = 'OFFSET '.. options.paging_state end if options.page_size then paging_str = paging_str .. ' LIMIT '.. options.page_size end return trim(paging_str) end -- Generate a SELECT query with an optional WHERE instruction. -- If building a WHERE instruction, we need some additional informations about the table. -- @param `table_name` Name of the table -- @param `select_columns` A list of columns to retrieve -- @return `query` The SELECT query function _M.select(table_name, where_t, select_columns, options) assert(type(table_name) == "string", "table_name must be a string") local select_str = select_fragment(table_name, select_columns) local where_str = where_fragment(where_t) local paging_str = paging_fragment(options) return trim(string.format("%s %s %s", select_str, where_str, paging_str)) end -- Generate an INSERT query. -- @param `table_name` Name of the table -- @param `insert_values` A columns/values table of values to insert -- @return `query` The INSERT query function _M.insert(table_name, insert_values) assert(type(table_name) == "string", "table_name must be a string") assert(type(insert_values) == "table", "insert_values must be a table") assert(next(insert_values) ~= nil, "insert_values cannot be empty") return insert_fragment(table_name, insert_values) end -- Generate an UPDATE query with update values (SET part) and a mandatory WHERE instruction. -- @param `table_name` Name of the table -- @param `update_values` A columns/values table of values to update -- @param `where_t` A columns/values table to select the row to update -- @return `query` The UPDATE query function _M.update(table_name, update_values, where_t) assert(type(table_name) == "string", "table_name must be a string") assert(type(update_values) == "table", "update_values must be a table") assert(next(update_values) ~= nil, "update_values cannot be empty") local update_str, update_columns = update_fragment(table_name, update_values) local where_str, where_columns = where_fragment(where_t, true) -- concat columns from SET and WHERE parts of the query local columns = {} if update_columns then columns = update_columns end if where_columns then for _, v in ipairs(where_columns) do table.insert(columns, v) end end return trim(string.format("%s %s", update_str, where_str)) end -- Generate a DELETE QUERY with a mandatory WHERE instruction. -- @param `table_name` Name of the table -- @param `where_t` A columns/values table to select the row to DELETE -- @return `columns` An list of columns to bind for the query, in the order of the placeholder markers (?) function _M.delete(table_name, where_t) assert(type(table_name) == "string", "table_name must be a string") local delete_str = delete_fragment(table_name) local where_str = where_fragment(where_t, true) return trim(string.format("%s %s", delete_str, where_str)) end -- Generate a TRUNCATE query -- @param `table_name` Name of the table -- @return `query` function _M.truncate(table_name) assert(type(table_name) == "string", "table_name must be a string") return "TRUNCATE "..escape_identifier(table_name).." CASCADE" end return _M
apache-2.0
amohanta/rspamd
src/plugins/lua/rbl.lua
2
16433
--[[ Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru> Copyright (c) 2013-2015, Andrew Lewis <nerf@judo.za.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]-- -- This plugin implements various types of RBL checks -- Documentation can be found here: -- https://rspamd.com/doc/modules/rbl.html local rbls = {} local local_exclusions = nil local private_ips = nil local rspamd_logger = require 'rspamd_logger' local rspamd_ip = require 'rspamd_ip' local rspamd_url = require 'rspamd_url' local symbols = { dkim_allow_symbol = 'R_DKIM_ALLOW', } local dkim_config = rspamd_config:get_all_opt("dkim") if dkim_config['symbol_allow'] then symbols['dkim_allow_symbol'] = dkim_config['symbol_allow'] end local function validate_dns(lstr) if lstr:match('%.%.') then return false end for v in lstr:gmatch('[^%.]+') do if not v:match('^[%w-]+$') or v:len() > 63 or v:match('^-') or v:match('-$') then return false end end return true end local function is_private_ip(rip) if private_ips and private_ips:get_key(rip) then return true end return false end local function is_excluded_ip(rip) if local_exclusions and local_exclusions:get_key(rip) then return true end return false end local function ip_to_rbl(ip, rbl) return table.concat(ip:inversed_str_octets(), '.') .. '.' .. rbl end local function rbl_cb (task) local function rbl_dns_cb(resolver, to_resolve, results, err, key) if results then local thisrbl = nil for k,r in pairs(rbls) do if k == key then thisrbl = r break end end if thisrbl ~= nil then if thisrbl['returncodes'] == nil then if thisrbl['symbol'] ~= nil then task:insert_result(thisrbl['symbol'], 1) end else for _,result in pairs(results) do local ipstr = result:to_string() local foundrc = false for s,i in pairs(thisrbl['returncodes']) do if type(i) == 'string' then if string.find(ipstr, '^' .. i .. '$') then foundrc = true task:insert_result(s, 1) break end elseif type(i) == 'table' then for _,v in pairs(i) do if string.find(ipstr, '^' .. v .. '$') then foundrc = true task:insert_result(s, 1) break end end end end if not foundrc then if thisrbl['unknown'] and thisrbl['symbol'] then task:insert_result(thisrbl['symbol'], 1) else rspamd_logger.err('RBL ' .. thisrbl['rbl'] .. ' returned unknown result ' .. ipstr) end end end end end end task:inc_dns_req() end local havegot = {} local notgot = {} for k,rbl in pairs(rbls) do (function() if rbl['exclude_users'] then if not havegot['user'] and not notgot['user'] then havegot['user'] = task:get_user() if havegot['user'] == nil then notgot['user'] = true end end if havegot['user'] ~= nil then return end end if (rbl['exclude_local'] or rbl['exclude_private_ips']) and not notgot['from'] then if not havegot['from'] then havegot['from'] = task:get_from_ip() if not havegot['from']:is_valid() then notgot['from'] = true end end if havegot['from'] and not notgot['from'] and ((rbl['exclude_local'] and is_excluded_ip(havegot['from'])) or (rbl['exclude_private_ips'] and is_private_ip(havegot['from']))) then return end end if rbl['helo'] then (function() if notgot['helo'] then return end if not havegot['helo'] then havegot['helo'] = task:get_helo() if havegot['helo'] == nil or not validate_dns(havegot['helo']) then notgot['helo'] = true return end end task:get_resolver():resolve_a({task = task, name = havegot['helo'] .. '.' .. rbl['rbl'], callback = rbl_dns_cb, option = k}) end)() end if rbl['dkim'] then (function() if notgot['dkim'] then return end if not havegot['dkim'] then local das = task:get_symbol(symbols['dkim_allow_symbol']) if das and das[1] and das[1]['options'] and das[1]['options'][0] then havegot['dkim'] = das[1]['options'] else notgot['dkim'] = true return end end for _, d in pairs(havegot['dkim']) do if rbl['dkim_domainonly'] then local url_from = rspamd_url.create(task:get_mempool(), d) if url_from then d = url_from:get_tld() else return end end task:get_resolver():resolve_a({task = task, name = d .. '.' .. rbl['rbl'], callback = rbl_dns_cb, option = k}) end end)() end if rbl['emails'] then (function() if notgot['emails'] then return end if not havegot['emails'] then havegot['emails'] = task:get_emails() if havegot['emails'] == nil then notgot['emails'] = true return end local cleanList = {} for _, e in pairs(havegot['emails']) do local localpart = e:get_user() local domainpart = e:get_host() if rbl['emails'] == 'domain_only' then if not cleanList[domainpart] and validate_dns(domainpart) then cleanList[domainpart] = true end else if validate_dns(localpart) and validate_dns(domainpart) then table.insert(cleanList, localpart .. '.' .. domainpart) end end end havegot['emails'] = cleanList if not next(havegot['emails']) then notgot['emails'] = true return end end if rbl['emails'] == 'domain_only' then for domain, _ in pairs(havegot['emails']) do task:get_resolver():resolve_a({task = task, name = domain .. '.' .. rbl['rbl'], callback = rbl_dns_cb, option = k}) end else for _, email in pairs(havegot['emails']) do task:get_resolver():resolve_a({task = task, name = email .. '.' .. rbl['rbl'], callback = rbl_dns_cb, option = k}) end end end)() end if rbl['rdns'] then (function() if notgot['rdns'] then return end if not havegot['rdns'] then havegot['rdns'] = task:get_hostname() if havegot['rdns'] == nil or havegot['rdns'] == 'unknown' then notgot['rdns'] = true return end end task:get_resolver():resolve_a({task = task, name = havegot['rdns'] .. '.' .. rbl['rbl'], callback = rbl_dns_cb, option = k}) end)() end if rbl['from'] then (function() if notgot['from'] then return end if not havegot['from'] then havegot['from'] = task:get_from_ip() if not havegot['from']:is_valid() then notgot['from'] = true return end end if (havegot['from']:get_version() == 6 and rbl['ipv6']) or (havegot['from']:get_version() == 4 and rbl['ipv4']) then task:get_resolver():resolve_a({task = task, name = ip_to_rbl(havegot['from'], rbl['rbl']), callback = rbl_dns_cb, option = k}) end end)() end if rbl['received'] then (function() if notgot['received'] then return end if not havegot['received'] then havegot['received'] = task:get_received_headers() if next(havegot['received']) == nil then notgot['received'] = true return end end for _,rh in ipairs(havegot['received']) do if rh['real_ip'] and rh['real_ip']:is_valid() then if ((rh['real_ip']:get_version() == 6 and rbl['ipv6']) or (rh['real_ip']:get_version() == 4 and rbl['ipv4'])) and ((rbl['exclude_private_ips'] and not is_private_ip(rh['real_ip'])) or not rbl['exclude_private_ips']) and ((rbl['exclude_local_ips'] and not is_excluded_ip(rh['real_ip'])) or not rbl['exclude_local_ips']) then task:get_resolver():resolve_a({task = task, name = ip_to_rbl(rh['real_ip'], rbl['rbl']), callback = rbl_dns_cb, option = k}) end end end end)() end end)() end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 1 then rspamd_config:register_module_option('rbl', 'rbls', 'map') rspamd_config:register_module_option('rbl', 'default_ipv4', 'string') rspamd_config:register_module_option('rbl', 'default_ipv6', 'string') rspamd_config:register_module_option('rbl', 'default_received', 'string') rspamd_config:register_module_option('rbl', 'default_from', 'string') rspamd_config:register_module_option('rbl', 'default_rdns', 'string') rspamd_config:register_module_option('rbl', 'default_helo', 'string') rspamd_config:register_module_option('rbl', 'default_dkim', 'string') rspamd_config:register_module_option('rbl', 'default_dkim_domainonly', 'string') rspamd_config:register_module_option('rbl', 'default_unknown', 'string') rspamd_config:register_module_option('rbl', 'default_exclude_users', 'string') rspamd_config:register_module_option('rbl', 'default_exclude_private_ips', 'string') rspamd_config:register_module_option('rbl', 'local_exclude_ip_map', 'string') rspamd_config:register_module_option('rbl', 'default_exclude_local', 'string') rspamd_config:register_module_option('rbl', 'private_ips', 'string') rspamd_config:register_module_option('rbl', 'default_emails', 'string') rspamd_config:register_module_option('rbl', 'default_is_whitelist', 'string') rspamd_config:register_module_option('rbl', 'default_ignore_whitelists', 'string') end end -- Configuration local opts = rspamd_config:get_all_opt('rbl') if not opts or type(opts) ~= 'table' then return end -- Plugin defaults should not be changed - override these in config -- New defaults should not alter behaviour default_defaults = { ['default_ipv4'] = {[1] = true, [2] = 'ipv4'}, ['default_ipv6'] = {[1] = false, [2] = 'ipv6'}, ['default_received'] = {[1] = true, [2] = 'received'}, ['default_from'] = {[1] = false, [2] = 'from'}, ['default_unknown'] = {[1] = false, [2] = 'unknown'}, ['default_rdns'] = {[1] = false, [2] = 'rdns'}, ['default_helo'] = {[1] = false, [2] = 'helo'}, ['default_dkim'] = {[1] = false, [2] = 'dkim'}, ['default_dkim_domainonly'] = {[1] = true, [2] = 'dkim_domainonly'}, ['default_emails'] = {[1] = false, [2] = 'emails'}, ['default_exclude_users'] = {[1] = false, [2] = 'exclude_users'}, ['default_exclude_private_ips'] = {[1] = true, [2] = 'exclude_private_ips'}, ['default_exclude_users'] = {[1] = false, [2] = 'exclude_users'}, ['default_exclude_local'] = {[1] = true, [2] = 'exclude_local'}, ['default_is_whitelist'] = {[1] = false, [2] = 'is_whitelist'}, ['default_ignore_whitelist'] = {[1] = false, [2] = 'ignore_whitelists'}, } for default, default_v in pairs(default_defaults) do if opts[default] == nil then opts[default] = default_v[1] end end if(opts['local_exclude_ip_map'] ~= nil) then local_exclusions = rspamd_config:add_radix_map(opts['local_exclude_ip_map']) end if(opts['private_ips'] ~= nil) then private_ips = rspamd_config:radix_from_config('rbl', 'private_ips') end local white_symbols = {} local black_symbols = {} local need_dkim = false local id = rspamd_config:register_callback_symbol_priority(1.0, 0, rbl_cb) for key,rbl in pairs(opts['rbls']) do for default, default_v in pairs(default_defaults) do if(rbl[default_v[2]] == nil) then rbl[default_v[2]] = opts[default] end end if type(rbl['returncodes']) == 'table' then for s,_ in pairs(rbl['returncodes']) do if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(s, 1, id) if rbl['dkim'] then need_dkim = true end if(rbl['is_whitelist']) then if type(rbl['whitelist_exception']) == 'string' then if (rbl['whitelist_exception'] ~= s) then table.insert(white_symbols, s) end elseif type(rbl['whitelist_exception']) == 'table' then local foundException = false for _, e in pairs(rbl['whitelist_exception']) do if e == s then foundException = true break end end if not foundException then table.insert(white_symbols, s) end else table.insert(white_symbols, s) end else if rbl['ignore_whitelists'] == false then table.insert(black_symbols, s) end end end end end if not rbl['symbol'] and ((rbl['returncodes'] and rbl['unknown']) or (not rbl['returncodes'])) then rbl['symbol'] = key end if type(rspamd_config.get_api_version) ~= 'nil' and rbl['symbol'] then rspamd_config:register_virtual_symbol(rbl['symbol'], 1, id) if rbl['dkim'] then need_dkim = true end if(rbl['is_whitelist']) then if type(rbl['whitelist_exception']) == 'string' then if (rbl['whitelist_exception'] ~= rbl['symbol']) then table.insert(white_symbols, rbl['symbol']) end elseif type(rbl['whitelist_exception']) == 'table' then local foundException = false for _, e in pairs(rbl['whitelist_exception']) do if e == s then foundException = true break end end if not foundException then table.insert(white_symbols, rbl['symbol']) end else table.insert(white_symbols, rbl['symbol']) end else if rbl['ignore_whitelists'] == false then table.insert(black_symbols, rbl['symbol']) end end end rbls[key] = rbl end for _, w in pairs(white_symbols) do for _, b in pairs(black_symbols) do csymbol = 'RBL_COMPOSITE_' .. w .. '_' .. b rspamd_config:set_metric_symbol(csymbol, 0, 'Autogenerated composite') rspamd_config:add_composite(csymbol, w .. ' & ' .. b) end end if need_dkim then rspamd_config:register_dependency(id, symbols['dkim_allow_symbol']) end
bsd-2-clause
cjshmyr/OpenRA
mods/d2k/maps/ordos-02a/ordos02a.lua
2
4024
--[[ 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. ]] HarkonnenBase = { HConyard, HPower1, HPower2, HBarracks, HOutpost } HarkonnenBaseAreaTrigger = { CPos.New(31, 37), CPos.New(32, 37), CPos.New(33, 37), CPos.New(34, 37), CPos.New(35, 37), CPos.New(36, 37), CPos.New(37, 37), CPos.New(38, 37), CPos.New(39, 37), CPos.New(40, 37), CPos.New(41, 37), CPos.New(42, 37), CPos.New(42, 38), CPos.New(42, 39), CPos.New(42, 40), CPos.New(42, 41), CPos.New(42, 42), CPos.New(42, 43), CPos.New(42, 44), CPos.New(42, 45), CPos.New(42, 46), CPos.New(42, 47), CPos.New(42, 48), CPos.New(42, 49) } HarkonnenReinforcements = { easy = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" } }, normal = { { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" } }, hard = { { "trike", "trike" }, { "light_inf", "trike" }, { "light_inf", "trike" }, { "light_inf", "light_inf", "light_inf", "trike", "trike" }, { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } } HarkonnenAttackPaths = { { HarkonnenEntry3.Location, HarkonnenRally3.Location }, { HarkonnenEntry4.Location, HarkonnenRally5.Location }, { HarkonnenEntry4.Location, HarkonnenRally6.Location }, { HarkonnenEntry5.Location, HarkonnenRally4.Location } } InitialHarkonnenReinforcementsPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry2.Location, HarkonnenRally2.Location } } InitialHarkonnenReinforcements = { { "trike", "trike" }, { "light_inf", "light_inf" } } HarkonnenAttackDelay = { easy = DateTime.Minutes(5), normal = DateTime.Minutes(2) + DateTime.Seconds(40), hard = DateTime.Minutes(1) + DateTime.Seconds(20) } HarkonnenAttackWaves = { easy = 3, normal = 6, hard = 9 } OrdosReinforcements = { "light_inf", "light_inf", "raider" } OrdosEntryPath = { OrdosEntry.Location, OrdosRally.Location } Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillOrdos) end if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") player = Player.GetPlayer("Ordos") InitObjectives(player) KillOrdos = harkonnen.AddPrimaryObjective("Kill all Ordos units.") KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.") Camera.Position = OConyard.CenterPosition Trigger.OnAllKilled(HarkonnenBase, function() Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt) end) Trigger.AfterDelay(DateTime.Minutes(1), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", OrdosReinforcements, OrdosEntryPath, { OrdosEntryPath[1] }) end) TriggerCarryallReinforcements(player, harkonnen, HarkonnenBaseAreaTrigger, InitialHarkonnenReinforcements[1], InitialHarkonnenReinforcementsPaths[1]) TriggerCarryallReinforcements(player, harkonnen, HarkonnenBaseAreaTrigger, InitialHarkonnenReinforcements[2], InitialHarkonnenReinforcementsPaths[2]) local path = function() return Utils.Random(HarkonnenAttackPaths) end SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty]) Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
tangentialism/google-diff-match-patch
lua/diff_match_patch.lua
265
73869
--[[ * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Based on the JavaScript implementation by Neil Fraser. * Ported to Lua by Duncan Cross. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. --]] --[[ -- Lua 5.1 and earlier requires the external BitOp library. -- This library is built-in from Lua 5.2 and later as 'bit32'. require 'bit' -- <http://bitop.luajit.org/> local band, bor, lshift = bit.band, bit.bor, bit.lshift --]] local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local type, setmetatable, ipairs, select = type, setmetatable, ipairs, select local unpack, tonumber, error = unpack, tonumber, error local strsub, strbyte, strchar, gmatch, gsub = string.sub, string.byte, string.char, string.gmatch, string.gsub local strmatch, strfind, strformat = string.match, string.find, string.format local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local max, min, floor, ceil, abs = math.max, math.min, math.floor, math.ceil, math.abs local clock = os.clock -- Utility functions. local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]' local function percentEncode_replace(v) return strformat('%%%02X', strbyte(v)) end local function tsplice(t, idx, deletions, ...) local insertions = select('#', ...) for i = 1, deletions do tremove(t, idx) end for i = insertions, 1, -1 do -- do not remove parentheses around select tinsert(t, idx, (select(i, ...))) end end local function strelement(str, i) return strsub(str, i, i) end local function indexOf(a, b, start) if (#b == 0) then return nil end return strfind(a, b, start, true) end local htmlEncode_pattern = '[&<>\n]' local htmlEncode_replace = { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['\n'] = '&para;<br>' } -- Public API Functions -- (Exported at the end of the script) local diff_main, diff_cleanupSemantic, diff_cleanupEfficiency, diff_levenshtein, diff_prettyHtml local match_main local patch_make, patch_toText, patch_fromText, patch_apply --[[ * The data structure representing a diff is an array of tuples: * {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}} * which means: delete 'Hello', add 'Goodbye' and keep ' world.' --]] local DIFF_DELETE = -1 local DIFF_INSERT = 1 local DIFF_EQUAL = 0 -- Number of seconds to map a diff before giving up (0 for infinity). local Diff_Timeout = 1.0 -- Cost of an empty edit operation in terms of edit characters. local Diff_EditCost = 4 -- At what point is no match declared (0.0 = perfection, 1.0 = very loose). local Match_Threshold = 0.5 -- How far to search for a match (0 = exact location, 1000+ = broad match). -- A match this many characters away from the expected location will add -- 1.0 to the score (0.0 is a perfect match). local Match_Distance = 1000 -- When deleting a large block of text (over ~64 characters), how close do -- the contents have to be to match the expected contents. (0.0 = perfection, -- 1.0 = very loose). Note that Match_Threshold controls how closely the -- end points of a delete need to match. local Patch_DeleteThreshold = 0.5 -- Chunk size for context length. local Patch_Margin = 4 -- The number of bits in an int. local Match_MaxBits = 32 function settings(new) if new then Diff_Timeout = new.Diff_Timeout or Diff_Timeout Diff_EditCost = new.Diff_EditCost or Diff_EditCost Match_Threshold = new.Match_Threshold or Match_Threshold Match_Distance = new.Match_Distance or Match_Distance Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold Patch_Margin = new.Patch_Margin or Patch_Margin Match_MaxBits = new.Match_MaxBits or Match_MaxBits else return { Diff_Timeout = Diff_Timeout; Diff_EditCost = Diff_EditCost; Match_Threshold = Match_Threshold; Match_Distance = Match_Distance; Patch_DeleteThreshold = Patch_DeleteThreshold; Patch_Margin = Patch_Margin; Match_MaxBits = Match_MaxBits; } end end -- --------------------------------------------------------------------------- -- DIFF API -- --------------------------------------------------------------------------- -- The private diff functions local _diff_compute, _diff_bisect, _diff_halfMatchI, _diff_halfMatch, _diff_cleanupSemanticScore, _diff_cleanupSemanticLossless, _diff_cleanupMerge, _diff_commonPrefix, _diff_commonSuffix, _diff_commonOverlap, _diff_xIndex, _diff_text1, _diff_text2, _diff_toDelta, _diff_fromDelta --[[ * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} opt_checklines Has no effect in Lua. * @param {number} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. * @return {Array.<Array.<number|string>>} Array of diff tuples. --]] function diff_main(text1, text2, opt_checklines, opt_deadline) -- Set a deadline by which time the diff must be complete. if opt_deadline == nil then if Diff_Timeout <= 0 then opt_deadline = 2 ^ 31 else opt_deadline = clock() + Diff_Timeout end end local deadline = opt_deadline -- Check for null inputs. if text1 == nil or text1 == nil then error('Null inputs. (diff_main)') end -- Check for equality (speedup). if text1 == text2 then if #text1 > 0 then return {{DIFF_EQUAL, text1}} end return {} end -- LUANOTE: Due to the lack of Unicode support, Lua is incapable of -- implementing the line-mode speedup. local checklines = false -- Trim off common prefix (speedup). local commonlength = _diff_commonPrefix(text1, text2) local commonprefix if commonlength > 0 then commonprefix = strsub(text1, 1, commonlength) text1 = strsub(text1, commonlength + 1) text2 = strsub(text2, commonlength + 1) end -- Trim off common suffix (speedup). commonlength = _diff_commonSuffix(text1, text2) local commonsuffix if commonlength > 0 then commonsuffix = strsub(text1, -commonlength) text1 = strsub(text1, 1, -commonlength - 1) text2 = strsub(text2, 1, -commonlength - 1) end -- Compute the diff on the middle block. local diffs = _diff_compute(text1, text2, checklines, deadline) -- Restore the prefix and suffix. if commonprefix then tinsert(diffs, 1, {DIFF_EQUAL, commonprefix}) end if commonsuffix then diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix} end _diff_cleanupMerge(diffs) return diffs end --[[ * Reduce the number of edits by eliminating semantically trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupSemantic(diffs) local changes = false local equalities = {} -- Stack of indices where equalities are found. local equalitiesLength = 0 -- Keeping our own length var is faster. local lastequality = nil -- Always equal to diffs[equalities[equalitiesLength]][2] local pointer = 1 -- Index of current position. -- Number of characters that changed prior to the equality. local length_insertions1 = 0 local length_deletions1 = 0 -- Number of characters that changed after the equality. local length_insertions2 = 0 local length_deletions2 = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer length_insertions1 = length_insertions2 length_deletions1 = length_deletions2 length_insertions2 = 0 length_deletions2 = 0 lastequality = diffs[pointer][2] else -- An insertion or deletion. if diffs[pointer][1] == DIFF_INSERT then length_insertions2 = length_insertions2 + #(diffs[pointer][2]) else length_deletions2 = length_deletions2 + #(diffs[pointer][2]) end -- Eliminate an equality that is smaller or equal to the edits on both -- sides of it. if lastequality and (#lastequality <= max(length_insertions1, length_deletions1)) and (#lastequality <= max(length_insertions2, length_deletions2)) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 -- Throw away the previous equality (it needs to be reevaluated). equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 length_insertions1, length_deletions1 = 0, 0 -- Reset the counters. length_insertions2, length_deletions2 = 0, 0 lastequality = nil changes = true end end pointer = pointer + 1 end -- Normalize the diff. if changes then _diff_cleanupMerge(diffs) end _diff_cleanupSemanticLossless(diffs) -- Find any overlaps between deletions and insertions. -- e.g: <del>abcxxx</del><ins>xxxdef</ins> -- -> <del>abc</del>xxx<ins>def</ins> -- e.g: <del>xxxabc</del><ins>defxxx</ins> -- -> <ins>def</ins>xxx<del>abc</del> -- Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 2 while diffs[pointer] do if (diffs[pointer - 1][1] == DIFF_DELETE and diffs[pointer][1] == DIFF_INSERT) then local deletion = diffs[pointer - 1][2] local insertion = diffs[pointer][2] local overlap_length1 = _diff_commonOverlap(deletion, insertion) local overlap_length2 = _diff_commonOverlap(insertion, deletion) if (overlap_length1 >= overlap_length2) then if (overlap_length1 >= #deletion / 2 or overlap_length1 >= #insertion / 2) then -- Overlap found. Insert an equality and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(insertion, 1, overlap_length1)}) diffs[pointer - 1][2] = strsub(deletion, 1, #deletion - overlap_length1) diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1) pointer = pointer + 1 end else if (overlap_length2 >= #deletion / 2 or overlap_length2 >= #insertion / 2) then -- Reverse overlap found. -- Insert an equality and swap and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(deletion, 1, overlap_length2)}) diffs[pointer - 1] = {DIFF_INSERT, strsub(insertion, 1, #insertion - overlap_length2)} diffs[pointer + 1] = {DIFF_DELETE, strsub(deletion, overlap_length2 + 1)} pointer = pointer + 1 end end pointer = pointer + 1 end pointer = pointer + 1 end end --[[ * Reduce the number of edits by eliminating operationally trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupEfficiency(diffs) local changes = false -- Stack of indices where equalities are found. local equalities = {} -- Keeping our own length var is faster. local equalitiesLength = 0 -- Always equal to diffs[equalities[equalitiesLength]][2] local lastequality = nil -- Index of current position. local pointer = 1 -- The following four are really booleans but are stored as numbers because -- they are used at one point like this: -- -- (pre_ins + pre_del + post_ins + post_del) == 3 -- -- ...i.e. checking that 3 of them are true and 1 of them is false. -- Is there an insertion operation before the last equality. local pre_ins = 0 -- Is there a deletion operation before the last equality. local pre_del = 0 -- Is there an insertion operation after the last equality. local post_ins = 0 -- Is there a deletion operation after the last equality. local post_del = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. local diffText = diffs[pointer][2] if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then -- Candidate found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer pre_ins, pre_del = post_ins, post_del lastequality = diffText else -- Not a candidate, and can never become one. equalitiesLength = 0 lastequality = nil end post_ins, post_del = 0, 0 else -- An insertion or deletion. if diffs[pointer][1] == DIFF_DELETE then post_del = 1 else post_ins = 1 end --[[ * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> --]] if lastequality and ( (pre_ins+pre_del+post_ins+post_del == 4) or ( (#lastequality < Diff_EditCost / 2) and (pre_ins+pre_del+post_ins+post_del == 3) )) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 lastequality = nil if (pre_ins == 1) and (pre_del == 1) then -- No changes made which could affect previous entry, keep going. post_ins, post_del = 1, 1 equalitiesLength = 0 else -- Throw away the previous equality. equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 post_ins, post_del = 0, 0 end changes = true end end pointer = pointer + 1 end if changes then _diff_cleanupMerge(diffs) end end --[[ * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {number} Number of changes. --]] function diff_levenshtein(diffs) local levenshtein = 0 local insertions, deletions = 0, 0 for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if (op == DIFF_INSERT) then insertions = insertions + #data elseif (op == DIFF_DELETE) then deletions = deletions + #data elseif (op == DIFF_EQUAL) then -- A deletion and an insertion is one substitution. levenshtein = levenshtein + max(insertions, deletions) insertions = 0 deletions = 0 end end levenshtein = levenshtein + max(insertions, deletions) return levenshtein end --[[ * Convert a diff array into a pretty HTML report. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} HTML representation. --]] function diff_prettyHtml(diffs) local html = {} for x, diff in ipairs(diffs) do local op = diff[1] -- Operation (insert, delete, equal) local data = diff[2] -- Text of change. local text = gsub(data, htmlEncode_pattern, htmlEncode_replace) if op == DIFF_INSERT then html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>' elseif op == DIFF_DELETE then html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>' elseif op == DIFF_EQUAL then html[x] = '<span>' .. text .. '</span>' end end return tconcat(html) end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE DIFF FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Has no effect in Lua. * @param {number} deadline Time when the diff should be complete by. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_compute(text1, text2, checklines, deadline) if #text1 == 0 then -- Just add some text (speedup). return {{DIFF_INSERT, text2}} end if #text2 == 0 then -- Just delete some text (speedup). return {{DIFF_DELETE, text1}} end local diffs local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 local i = indexOf(longtext, shorttext) if i ~= nil then -- Shorter text is inside the longer text (speedup). diffs = { {DIFF_INSERT, strsub(longtext, 1, i - 1)}, {DIFF_EQUAL, shorttext}, {DIFF_INSERT, strsub(longtext, i + #shorttext)} } -- Swap insertions for deletions if diff is reversed. if #text1 > #text2 then diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE end return diffs end if #shorttext == 1 then -- Single character string. -- After the previous speedup, the character can't be an equality. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end -- Check to see if the problem can be split in two. do local text1_a, text1_b, text2_a, text2_b, mid_common = _diff_halfMatch(text1, text2) if text1_a then -- A half-match was found, sort out the return data. -- Send both pairs off for separate processing. local diffs_a = diff_main(text1_a, text2_a, checklines, deadline) local diffs_b = diff_main(text1_b, text2_b, checklines, deadline) -- Merge the results. local diffs_a_len = #diffs_a diffs = diffs_a diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common} for i, b_diff in ipairs(diffs_b) do diffs[diffs_a_len + 1 + i] = b_diff end return diffs end end return _diff_bisect(text1, text2, deadline) end --[[ * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisect(text1, text2, deadline) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 local _sub, _element local max_d = ceil((text1_length + text2_length) / 2) local v_offset = max_d local v_length = 2 * max_d local v1 = {} local v2 = {} -- Setting all elements to -1 is faster in Lua than mixing integers and nil. for x = 0, v_length - 1 do v1[x] = -1 v2[x] = -1 end v1[v_offset + 1] = 0 v2[v_offset + 1] = 0 local delta = text1_length - text2_length -- If the total number of characters is odd, then -- the front path will collide with the reverse path. local front = (delta % 2 ~= 0) -- Offsets for start and end of k loop. -- Prevents mapping of space beyond the grid. local k1start = 0 local k1end = 0 local k2start = 0 local k2end = 0 for d = 0, max_d - 1 do -- Bail out if deadline is reached. if clock() > deadline then break end -- Walk the front path one step. for k1 = -d + k1start, d - k1end, 2 do local k1_offset = v_offset + k1 local x1 if (k1 == -d) or ((k1 ~= d) and (v1[k1_offset - 1] < v1[k1_offset + 1])) then x1 = v1[k1_offset + 1] else x1 = v1[k1_offset - 1] + 1 end local y1 = x1 - k1 while (x1 <= text1_length) and (y1 <= text2_length) and (strelement(text1, x1) == strelement(text2, y1)) do x1 = x1 + 1 y1 = y1 + 1 end v1[k1_offset] = x1 if x1 > text1_length + 1 then -- Ran off the right of the graph. k1end = k1end + 2 elseif y1 > text2_length + 1 then -- Ran off the bottom of the graph. k1start = k1start + 2 elseif front then local k2_offset = v_offset + delta - k1 if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then -- Mirror x2 onto top-left coordinate system. local x2 = text1_length - v2[k2_offset] + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end -- Walk the reverse path one step. for k2 = -d + k2start, d - k2end, 2 do local k2_offset = v_offset + k2 local x2 if (k2 == -d) or ((k2 ~= d) and (v2[k2_offset - 1] < v2[k2_offset + 1])) then x2 = v2[k2_offset + 1] else x2 = v2[k2_offset - 1] + 1 end local y2 = x2 - k2 while (x2 <= text1_length) and (y2 <= text2_length) and (strelement(text1, -x2) == strelement(text2, -y2)) do x2 = x2 + 1 y2 = y2 + 1 end v2[k2_offset] = x2 if x2 > text1_length + 1 then -- Ran off the left of the graph. k2end = k2end + 2 elseif y2 > text2_length + 1 then -- Ran off the top of the graph. k2start = k2start + 2 elseif not front then local k1_offset = v_offset + delta - k2 if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then local x1 = v1[k1_offset] local y1 = v_offset + x1 - k1_offset -- Mirror x2 onto top-left coordinate system. x2 = text1_length - x2 + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end end -- Diff took too long and hit the deadline or -- number of diffs equals number of characters, no commonality at all. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end --[[ * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisectSplit(text1, text2, x, y, deadline) local text1a = strsub(text1, 1, x - 1) local text2a = strsub(text2, 1, y - 1) local text1b = strsub(text1, x) local text2b = strsub(text2, y) -- Compute both diffs serially. local diffs = diff_main(text1a, text2a, false, deadline) local diffsb = diff_main(text1b, text2b, false, deadline) local diffs_len = #diffs for i, v in ipairs(diffsb) do diffs[diffs_len + i] = v end return diffs end --[[ * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. --]] function _diff_commonPrefix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerstart = 1 while (pointermin < pointermid) do if (strsub(text1, pointerstart, pointermid) == strsub(text2, pointerstart, pointermid)) then pointermin = pointermid pointerstart = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. --]] function _diff_commonSuffix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, -1) ~= strbyte(text2, -1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerend = 1 while (pointermin < pointermid) do if (strsub(text1, -pointermid, -pointerend) == strsub(text2, -pointermid, -pointerend)) then pointermin = pointermid pointerend = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private --]] function _diff_commonOverlap(text1, text2) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 -- Eliminate the null case. if text1_length == 0 or text2_length == 0 then return 0 end -- Truncate the longer string. if text1_length > text2_length then text1 = strsub(text1, text1_length - text2_length + 1) elseif text1_length < text2_length then text2 = strsub(text2, 1, text1_length) end local text_length = min(text1_length, text2_length) -- Quick check for the worst case. if text1 == text2 then return text_length end -- Start by looking for a single character match -- and increase length until no match is found. -- Performance analysis: http://neil.fraser.name/news/2010/11/04/ local best = 0 local length = 1 while true do local pattern = strsub(text1, text_length - length + 1) local found = strfind(text2, pattern, 1, true) if found == nil then return best end length = length + found - 1 if found == 1 or strsub(text1, text_length - length + 1) == strsub(text2, 1, length) then best = length length = length + 1 end end end --[[ * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * This speedup can produce non-minimal diffs. * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {?Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatchI(longtext, shorttext, i) -- Start with a 1/4 length substring at position i as a seed. local seed = strsub(longtext, i, i + floor(#longtext / 4)) local j = 0 -- LUANOTE: do not change to 1, was originally -1 local best_common = '' local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b while true do j = indexOf(shorttext, seed, j + 1) if (j == nil) then break end local prefixLength = _diff_commonPrefix(strsub(longtext, i), strsub(shorttext, j)) local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1), strsub(shorttext, 1, j - 1)) if #best_common < suffixLength + prefixLength then best_common = strsub(shorttext, j - suffixLength, j - 1) .. strsub(shorttext, j, j + prefixLength - 1) best_longtext_a = strsub(longtext, 1, i - suffixLength - 1) best_longtext_b = strsub(longtext, i + prefixLength) best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1) best_shorttext_b = strsub(shorttext, j + prefixLength) end end if #best_common * 2 >= #longtext then return {best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common} else return nil end end --[[ * Do the two texts share a substring which is at least half the length of the * longer text? * @param {string} text1 First string. * @param {string} text2 Second string. * @return {?Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatch(text1, text2) if Diff_Timeout <= 0 then -- Don't risk returning a non-optimal diff if we have unlimited time. return nil end local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 if (#longtext < 4) or (#shorttext * 2 < #longtext) then return nil -- Pointless. end -- First check if the second quarter is the seed for a half-match. local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4)) -- Check again based on the third quarter. local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2)) local hm if not hm1 and not hm2 then return nil elseif not hm2 then hm = hm1 elseif not hm1 then hm = hm2 else -- Both matched. Select the longest. hm = (#hm1[5] > #hm2[5]) and hm1 or hm2 end -- A half-match was found, sort out the return data. local text1_a, text1_b, text2_a, text2_b if (#text1 > #text2) then text1_a, text1_b = hm[1], hm[2] text2_a, text2_b = hm[3], hm[4] else text2_a, text2_b = hm[1], hm[2] text1_a, text1_b = hm[3], hm[4] end local mid_common = hm[5] return text1_a, text1_b, text2_a, text2_b, mid_common end --[[ * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private --]] function _diff_cleanupSemanticScore(one, two) if (#one == 0) or (#two == 0) then -- Edges are the best. return 6 end -- Each port of this function behaves slightly differently due to -- subtle differences in each language's definition of things like -- 'whitespace'. Since this function's purpose is largely cosmetic, -- the choice has been made to use each language's native features -- rather than force total conformity. local char1 = strsub(one, -1) local char2 = strsub(two, 1, 1) local nonAlphaNumeric1 = strmatch(char1, '%W') local nonAlphaNumeric2 = strmatch(char2, '%W') local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s') local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s') local lineBreak1 = whitespace1 and strmatch(char1, '%c') local lineBreak2 = whitespace2 and strmatch(char2, '%c') local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$') local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n') if blankLine1 or blankLine2 then -- Five points for blank lines. return 5 elseif lineBreak1 or lineBreak2 then -- Four points for line breaks. return 4 elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then -- Three points for end of sentences. return 3 elseif whitespace1 or whitespace2 then -- Two points for whitespace. return 2 elseif nonAlphaNumeric1 or nonAlphaNumeric2 then -- One point for non-alphanumeric. return 1 end return 0 end --[[ * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupSemanticLossless(diffs) local pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while diffs[pointer + 1] do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local equality1 = prevDiff[2] local edit = diff[2] local equality2 = nextDiff[2] -- First, shift the edit as far left as possible. local commonOffset = _diff_commonSuffix(equality1, edit) if commonOffset > 0 then local commonString = strsub(edit, -commonOffset) equality1 = strsub(equality1, 1, -commonOffset - 1) edit = commonString .. strsub(edit, 1, -commonOffset - 1) equality2 = commonString .. equality2 end -- Second, step character by character right, looking for the best fit. local bestEquality1 = equality1 local bestEdit = edit local bestEquality2 = equality2 local bestScore = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) while strbyte(edit, 1) == strbyte(equality2, 1) do equality1 = equality1 .. strsub(edit, 1, 1) edit = strsub(edit, 2) .. strsub(equality2, 1, 1) equality2 = strsub(equality2, 2) local score = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) -- The >= encourages trailing rather than leading whitespace on edits. if score >= bestScore then bestScore = score bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 end end if prevDiff[2] ~= bestEquality1 then -- We have an improvement, save it back to the diff. if #bestEquality1 > 0 then diffs[pointer - 1][2] = bestEquality1 else tremove(diffs, pointer - 1) pointer = pointer - 1 end diffs[pointer][2] = bestEdit if #bestEquality2 > 0 then diffs[pointer + 1][2] = bestEquality2 else tremove(diffs, pointer + 1, 1) pointer = pointer - 1 end end end pointer = pointer + 1 end end --[[ * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupMerge(diffs) diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end. local pointer = 1 local count_delete, count_insert = 0, 0 local text_delete, text_insert = '', '' local commonlength while diffs[pointer] do local diff_type = diffs[pointer][1] if diff_type == DIFF_INSERT then count_insert = count_insert + 1 text_insert = text_insert .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_DELETE then count_delete = count_delete + 1 text_delete = text_delete .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_EQUAL then -- Upon reaching an equality, check for prior redundancies. if count_delete + count_insert > 1 then if (count_delete > 0) and (count_insert > 0) then -- Factor out any common prefixies. commonlength = _diff_commonPrefix(text_insert, text_delete) if commonlength > 0 then local back_pointer = pointer - count_delete - count_insert if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL) then diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2] .. strsub(text_insert, 1, commonlength) else tinsert(diffs, 1, {DIFF_EQUAL, strsub(text_insert, 1, commonlength)}) pointer = pointer + 1 end text_insert = strsub(text_insert, commonlength + 1) text_delete = strsub(text_delete, commonlength + 1) end -- Factor out any common suffixies. commonlength = _diff_commonSuffix(text_insert, text_delete) if commonlength ~= 0 then diffs[pointer][2] = strsub(text_insert, -commonlength) .. diffs[pointer][2] text_insert = strsub(text_insert, 1, -commonlength - 1) text_delete = strsub(text_delete, 1, -commonlength - 1) end end -- Delete the offending records and add the merged ones. if count_delete == 0 then tsplice(diffs, pointer - count_insert, count_insert, {DIFF_INSERT, text_insert}) elseif count_insert == 0 then tsplice(diffs, pointer - count_delete, count_delete, {DIFF_DELETE, text_delete}) else tsplice(diffs, pointer - count_delete - count_insert, count_delete + count_insert, {DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert}) end pointer = pointer - count_delete - count_insert + (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1 elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then -- Merge this equality with the previous one. diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2] tremove(diffs, pointer) else pointer = pointer + 1 end count_insert, count_delete = 0, 0 text_delete, text_insert = '', '' end end if diffs[#diffs][2] == '' then diffs[#diffs] = nil -- Remove the dummy entry at the end. end -- Second pass: look for single edits surrounded on both sides by equalities -- which can be shifted sideways to eliminate an equality. -- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC local changes = false pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while pointer < #diffs do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local currentText = diff[2] local prevText = prevDiff[2] local nextText = nextDiff[2] if strsub(currentText, -#prevText) == prevText then -- Shift the edit over the previous equality. diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1) nextDiff[2] = prevText .. nextDiff[2] tremove(diffs, pointer - 1) changes = true elseif strsub(currentText, 1, #nextText) == nextText then -- Shift the edit over the next equality. prevDiff[2] = prevText .. nextText diff[2] = strsub(currentText, #nextText + 1) .. nextText tremove(diffs, pointer + 1) changes = true end end pointer = pointer + 1 end -- If shifts were made, the diff needs reordering and another shift sweep. if changes then -- LUANOTE: no return value, but necessary to use 'return' to get -- tail calls. return _diff_cleanupMerge(diffs) end end --[[ * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. --]] function _diff_xIndex(diffs, loc) local chars1 = 1 local chars2 = 1 local last_chars1 = 1 local last_chars2 = 1 local x for _x, diff in ipairs(diffs) do x = _x if diff[1] ~= DIFF_INSERT then -- Equality or deletion. chars1 = chars1 + #diff[2] end if diff[1] ~= DIFF_DELETE then -- Equality or insertion. chars2 = chars2 + #diff[2] end if chars1 > loc then -- Overshot the location. break end last_chars1 = chars1 last_chars2 = chars2 end -- Was the location deleted? if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then return last_chars2 end -- Add the remaining character length. return last_chars2 + (loc - last_chars1) end --[[ * Compute and return the source text (all equalities and deletions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Source text. --]] function _diff_text1(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_INSERT then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Compute and return the destination text (all equalities and insertions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Destination text. --]] function _diff_text2(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_DELETE then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Delta text. --]] function _diff_toDelta(diffs) local text = {} for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if op == DIFF_INSERT then text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace) elseif op == DIFF_DELETE then text[x] = '-' .. #data elseif op == DIFF_EQUAL then text[x] = '=' .. #data end end return tconcat(text, '\t') end --[[ * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @throws {Errorend If invalid input. --]] function _diff_fromDelta(text1, delta) local diffs = {} local diffsLength = 0 -- Keeping our own length var is faster local pointer = 1 -- Cursor in text1 for token in gmatch(delta, '[^\t]+') do -- Each token begins with a one character parameter which specifies the -- operation of this token (delete, insert, equality). local tokenchar, param = strsub(token, 1, 1), strsub(token, 2) if (tokenchar == '+') then local invalidDecode = false local decoded = gsub(param, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in _diff_fromDelta: ' .. param) end diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_INSERT, decoded} elseif (tokenchar == '-') or (tokenchar == '=') then local n = tonumber(param) if (n == nil) or (n < 0) then error('Invalid number in _diff_fromDelta: ' .. param) end local text = strsub(text1, pointer, pointer + n - 1) pointer = pointer + n if (tokenchar == '=') then diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_EQUAL, text} else diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_DELETE, text} end else error('Invalid diff operation in _diff_fromDelta: ' .. token) end end if (pointer ~= #text1 + 1) then error('Delta length (' .. (pointer - 1) .. ') does not equal source text length (' .. #text1 .. ').') end return diffs end -- --------------------------------------------------------------------------- -- MATCH API -- --------------------------------------------------------------------------- local _match_bitap, _match_alphabet --[[ * Locate the best instance of 'pattern' in 'text' near 'loc'. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. --]] function match_main(text, pattern, loc) -- Check for null inputs. if text == nil or pattern == nil or loc == nil then error('Null inputs. (match_main)') end if text == pattern then -- Shortcut (potentially not guaranteed by the algorithm) return 1 elseif #text == 0 then -- Nothing to match. return -1 end loc = max(1, min(loc, #text)) if strsub(text, loc, loc + #pattern - 1) == pattern then -- Perfect match at the perfect spot! (Includes case of null pattern) return loc else -- Do a fuzzy compare. return _match_bitap(text, pattern, loc) end end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE MATCH FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Initialise the alphabet for the Bitap algorithm. * @param {string} pattern The text to encode. * @return {Object} Hash of character locations. * @private --]] function _match_alphabet(pattern) local s = {} local i = 0 for c in gmatch(pattern, '.') do s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1)) i = i + 1 end return s end --[[ * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. * @private --]] function _match_bitap(text, pattern, loc) if #pattern > Match_MaxBits then error('Pattern too long.') end -- Initialise the alphabet. local s = _match_alphabet(pattern) --[[ * Compute and return the score for a match with e errors and x location. * Accesses loc and pattern through being a closure. * @param {number} e Number of errors in match. * @param {number} x Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private --]] local function _match_bitapScore(e, x) local accuracy = e / #pattern local proximity = abs(loc - x) if (Match_Distance == 0) then -- Dodge divide by zero error. return (proximity == 0) and 1 or accuracy end return accuracy + (proximity / Match_Distance) end -- Highest score beyond which we give up. local score_threshold = Match_Threshold -- Is there a nearby exact match? (speedup) local best_loc = indexOf(text, pattern, loc) if best_loc then score_threshold = min(_match_bitapScore(0, best_loc), score_threshold) -- LUANOTE: Ideally we'd also check from the other direction, but Lua -- doesn't have an efficent lastIndexOf function. end -- Initialise the bit arrays. local matchmask = lshift(1, #pattern - 1) best_loc = -1 local bin_min, bin_mid local bin_max = #pattern + #text local last_rd for d = 0, #pattern - 1, 1 do -- Scan for the best match; each iteration allows for one more error. -- Run a binary search to determine how far from 'loc' we can stray at this -- error level. bin_min = 0 bin_mid = bin_max while (bin_min < bin_mid) do if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then bin_min = bin_mid else bin_max = bin_mid end bin_mid = floor(bin_min + (bin_max - bin_min) / 2) end -- Use the result from this iteration as the maximum for the next. bin_max = bin_mid local start = max(1, loc - bin_mid + 1) local finish = min(loc + bin_mid, #text) + #pattern local rd = {} for j = start, finish do rd[j] = 0 end rd[finish + 1] = lshift(1, d) - 1 for j = finish, start, -1 do local charMatch = s[strsub(text, j - 1, j - 1)] or 0 if (d == 0) then -- First pass: exact match. rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch) else -- Subsequent passes: fuzzy match. -- Functions instead of operators make this hella messy. rd[j] = bor( band( bor( lshift(rd[j + 1], 1), 1 ), charMatch ), bor( bor( lshift(bor(last_rd[j + 1], last_rd[j]), 1), 1 ), last_rd[j + 1] ) ) end if (band(rd[j], matchmask) ~= 0) then local score = _match_bitapScore(d, j - 1) -- This match will almost certainly be better than any existing match. -- But check anyway. if (score <= score_threshold) then -- Told you so. score_threshold = score best_loc = j - 1 if (best_loc > loc) then -- When passing loc, don't exceed our current distance from loc. start = max(1, loc * 2 - best_loc) else -- Already passed loc, downhill from here on in. break end end end end -- No hope for a (better) match at greater error levels. if (_match_bitapScore(d + 1, loc) > score_threshold) then break end last_rd = rd end return best_loc end -- ----------------------------------------------------------------------------- -- PATCH API -- ----------------------------------------------------------------------------- local _patch_addContext, _patch_deepCopy, _patch_addPadding, _patch_splitMax, _patch_appendText, _new_patch_obj --[[ * Compute a list of patches to turn text1 into text2. * Use diffs if provided, otherwise compute it ourselves. * There are four ways to call this function, depending on what data is * available to the caller: * Method 1: * a = text1, b = text2 * Method 2: * a = diffs * Method 3 (optimal): * a = text1, b = diffs * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * * @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). * @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). * @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for * text1 to text2 (method 4) or undefined (methods 1,2,3). * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function patch_make(a, opt_b, opt_c) local text1, diffs local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c) if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then -- Method 1: text1, text2 -- Compute diffs from text1 and text2. text1 = a diffs = diff_main(text1, opt_b, true) if (#diffs > 2) then diff_cleanupSemantic(diffs) diff_cleanupEfficiency(diffs) end elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then -- Method 2: diffs -- Compute text1 from diffs. diffs = a text1 = _diff_text1(diffs) elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then -- Method 3: text1, diffs text1 = a diffs = opt_b elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table') then -- Method 4: text1, text2, diffs -- text2 is not used. text1 = a diffs = opt_c else error('Unknown call format to patch_make.') end if (diffs[1] == nil) then return {} -- Get rid of the null case. end local patches = {} local patch = _new_patch_obj() local patchDiffLength = 0 -- Keeping our own length var is faster. local char_count1 = 0 -- Number of characters into the text1 string. local char_count2 = 0 -- Number of characters into the text2 string. -- Start with text1 (prepatch_text) and apply the diffs until we arrive at -- text2 (postpatch_text). We recreate the patches one by one to determine -- context info. local prepatch_text, postpatch_text = text1, text1 for x, diff in ipairs(diffs) do local diff_type, diff_text = diff[1], diff[2] if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then -- A new patch starts here. patch.start1 = char_count1 + 1 patch.start2 = char_count2 + 1 end if (diff_type == DIFF_INSERT) then patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length2 = patch.length2 + #diff_text postpatch_text = strsub(postpatch_text, 1, char_count2) .. diff_text .. strsub(postpatch_text, char_count2 + 1) elseif (diff_type == DIFF_DELETE) then patch.length1 = patch.length1 + #diff_text patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff postpatch_text = strsub(postpatch_text, 1, char_count2) .. strsub(postpatch_text, char_count2 + #diff_text + 1) elseif (diff_type == DIFF_EQUAL) then if (#diff_text <= Patch_Margin * 2) and (patchDiffLength ~= 0) and (#diffs ~= x) then -- Small equality inside a patch. patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length1 = patch.length1 + #diff_text patch.length2 = patch.length2 + #diff_text elseif (#diff_text >= Patch_Margin * 2) then -- Time for a new patch. if (patchDiffLength ~= 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch patch = _new_patch_obj() patchDiffLength = 0 -- Unlike Unidiff, our patch lists have a rolling context. -- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff -- Update prepatch text & pos to reflect the application of the -- just completed patch. prepatch_text = postpatch_text char_count1 = char_count2 end end end -- Update the current character count. if (diff_type ~= DIFF_INSERT) then char_count1 = char_count1 + #diff_text end if (diff_type ~= DIFF_DELETE) then char_count2 = char_count2 + #diff_text end end -- Pick up the leftover patch if not empty. if (patchDiffLength > 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch end return patches end --[[ * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @param {string} text Old text. * @return {Array.<string|Array.<boolean>>} Two return values, the * new text and an array of boolean values. --]] function patch_apply(patches, text) if patches[1] == nil then return text, {} end -- Deep copy the patches so that no changes are made to originals. patches = _patch_deepCopy(patches) local nullPadding = _patch_addPadding(patches) text = nullPadding .. text .. nullPadding _patch_splitMax(patches) -- delta keeps track of the offset between the expected and actual location -- of the previous patch. If there are patches expected at positions 10 and -- 20, but the first patch was found at 12, delta is 2 and the second patch -- has an effective expected position of 22. local delta = 0 local results = {} for x, patch in ipairs(patches) do local expected_loc = patch.start2 + delta local text1 = _diff_text1(patch.diffs) local start_loc local end_loc = -1 if #text1 > Match_MaxBits then -- _patch_splitMax will only provide an oversized pattern in -- the case of a monster delete. start_loc = match_main(text, strsub(text1, 1, Match_MaxBits), expected_loc) if start_loc ~= -1 then end_loc = match_main(text, strsub(text1, -Match_MaxBits), expected_loc + #text1 - Match_MaxBits) if end_loc == -1 or start_loc >= end_loc then -- Can't find valid trailing context. Drop this patch. start_loc = -1 end end else start_loc = match_main(text, text1, expected_loc) end if start_loc == -1 then -- No match found. :( results[x] = false -- Subtract the delta for this failed patch from subsequent patches. delta = delta - patch.length2 - patch.length1 else -- Found a match. :) results[x] = true delta = start_loc - expected_loc local text2 if end_loc == -1 then text2 = strsub(text, start_loc, start_loc + #text1 - 1) else text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1) end if text1 == text2 then -- Perfect match, just shove the replacement text in. text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs) .. strsub(text, start_loc + #text1) else -- Imperfect match. Run a diff to get a framework of equivalent -- indices. local diffs = diff_main(text1, text2, false) if (#text1 > Match_MaxBits) and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then -- The end points match, but the content is unacceptably bad. results[x] = false else _diff_cleanupSemanticLossless(diffs) local index1 = 1 local index2 for y, mod in ipairs(patch.diffs) do if mod[1] ~= DIFF_EQUAL then index2 = _diff_xIndex(diffs, index1) end if mod[1] == DIFF_INSERT then text = strsub(text, 1, start_loc + index2 - 2) .. mod[2] .. strsub(text, start_loc + index2 - 1) elseif mod[1] == DIFF_DELETE then text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text, start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1)) end if mod[1] ~= DIFF_DELETE then index1 = index1 + #mod[2] end end end end end end -- Strip the padding off. text = strsub(text, #nullPadding + 1, -#nullPadding - 1) return text, results end --[[ * Take a list of patches and return a textual representation. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} Text representation of patches. --]] function patch_toText(patches) local text = {} for x, patch in ipairs(patches) do _patch_appendText(patch, text) end return tconcat(text) end --[[ * Parse a textual representation of patches and return a list of patch objects. * @param {string} textline Text representation of patches. * @return {Array.<_new_patch_obj>} Array of patch objects. * @throws {Error} If invalid input. --]] function patch_fromText(textline) local patches = {} if (#textline == 0) then return patches end local text = {} for line in gmatch(textline, '([^\n]*)') do text[#text + 1] = line end local textPointer = 1 while (textPointer <= #text) do local start1, length1, start2, length2 = strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$') if (start1 == nil) then error('Invalid patch string: "' .. text[textPointer] .. '"') end local patch = _new_patch_obj() patches[#patches + 1] = patch start1 = tonumber(start1) length1 = tonumber(length1) or 1 if (length1 == 0) then start1 = start1 + 1 end patch.start1 = start1 patch.length1 = length1 start2 = tonumber(start2) length2 = tonumber(length2) or 1 if (length2 == 0) then start2 = start2 + 1 end patch.start2 = start2 patch.length2 = length2 textPointer = textPointer + 1 while true do local line = text[textPointer] if (line == nil) then break end local sign; sign, line = strsub(line, 1, 1), strsub(line, 2) local invalidDecode = false local decoded = gsub(line, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in patch_fromText: ' .. line) end line = decoded if (sign == '-') then -- Deletion. patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line} elseif (sign == '+') then -- Insertion. patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line} elseif (sign == ' ') then -- Minor equality. patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line} elseif (sign == '@') then -- Start of next patch. break elseif (sign == '') then -- Blank line? Whatever. else -- WTF? error('Invalid patch mode "' .. sign .. '" in: ' .. line) end textPointer = textPointer + 1 end end return patches end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE PATCH FUNCTIONS -- --------------------------------------------------------------------------- local patch_meta = { __tostring = function(patch) local buf = {} _patch_appendText(patch, buf) return tconcat(buf) end } --[[ * Class representing one patch operation. * @constructor --]] function _new_patch_obj() return setmetatable({ --[[ @type {Array.<Array.<number|string>>} ]] diffs = {}; --[[ @type {?number} ]] start1 = 1; -- nil; --[[ @type {?number} ]] start2 = 1; -- nil; --[[ @type {number} ]] length1 = 0; --[[ @type {number} ]] length2 = 0; }, patch_meta) end --[[ * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param {_new_patch_obj} patch The patch to grow. * @param {string} text Source text. * @private --]] function _patch_addContext(patch, text) if (#text == 0) then return end local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1) local padding = 0 -- LUANOTE: Lua's lack of a lastIndexOf function results in slightly -- different logic here than in other language ports. -- Look for the first two matches of pattern in text. If two are found, -- increase the pattern length. local firstMatch = indexOf(text, pattern) local secondMatch = nil if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) end while (#pattern == 0 or secondMatch ~= nil) and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do padding = padding + Patch_Margin pattern = strsub(text, max(1, patch.start2 - padding), patch.start2 + patch.length1 - 1 + padding) firstMatch = indexOf(text, pattern) if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) else secondMatch = nil end end -- Add one chunk for good luck. padding = padding + Patch_Margin -- Add the prefix. local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1) if (#prefix > 0) then tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix}) end -- Add the suffix. local suffix = strsub(text, patch.start2 + patch.length1, patch.start2 + patch.length1 - 1 + padding) if (#suffix > 0) then patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix} end -- Roll back the start points. patch.start1 = patch.start1 - #prefix patch.start2 = patch.start2 - #prefix -- Extend the lengths. patch.length1 = patch.length1 + #prefix + #suffix patch.length2 = patch.length2 + #prefix + #suffix end --[[ * Given an array of patches, return another array that is identical. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function _patch_deepCopy(patches) local patchesCopy = {} for x, patch in ipairs(patches) do local patchCopy = _new_patch_obj() local diffsCopy = {} for i, diff in ipairs(patch.diffs) do diffsCopy[i] = {diff[1], diff[2]} end patchCopy.diffs = diffsCopy patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy[x] = patchCopy end return patchesCopy end --[[ * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} The padding string added to each side. --]] function _patch_addPadding(patches) local paddingLength = Patch_Margin local nullPadding = '' for x = 1, paddingLength do nullPadding = nullPadding .. strchar(x) end -- Bump all the patches forward. for x, patch in ipairs(patches) do patch.start1 = patch.start1 + paddingLength patch.start2 = patch.start2 + paddingLength end -- Add some padding on start of first diff. local patch = patches[1] local diffs = patch.diffs local firstDiff = diffs[1] if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. tinsert(diffs, 1, {DIFF_EQUAL, nullPadding}) patch.start1 = patch.start1 - paddingLength -- Should be 0. patch.start2 = patch.start2 - paddingLength -- Should be 0. patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #firstDiff[2]) then -- Grow first equality. local extraLength = paddingLength - #firstDiff[2] firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2] patch.start1 = patch.start1 - extraLength patch.start2 = patch.start2 - extraLength patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end -- Add some padding on end of last diff. patch = patches[#patches] diffs = patch.diffs local lastDiff = diffs[#diffs] if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding} patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #lastDiff[2]) then -- Grow last equality. local extraLength = paddingLength - #lastDiff[2] lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength) patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end return nullPadding end --[[ * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. --]] function _patch_splitMax(patches) local patch_size = Match_MaxBits local x = 1 while true do local patch = patches[x] if patch == nil then return end if patch.length1 > patch_size then local bigpatch = patch -- Remove the big old patch. tremove(patches, x) x = x - 1 local start1 = bigpatch.start1 local start2 = bigpatch.start2 local precontext = '' while bigpatch.diffs[1] do -- Create one of several smaller patches. local patch = _new_patch_obj() local empty = true patch.start1 = start1 - #precontext patch.start2 = start2 - #precontext if precontext ~= '' then patch.length1, patch.length2 = #precontext, #precontext patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext} end while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do local diff_type = bigpatch.diffs[1][1] local diff_text = bigpatch.diffs[1][2] if (diff_type == DIFF_INSERT) then -- Insertions are harmless. patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1] tremove(bigpatch.diffs, 1) empty = false elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1) and (patch.diffs[1][1] == DIFF_EQUAL) and (#diff_text > 2 * patch_size) then -- This is a large deletion. Let it pass in one chunk. patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text empty = false patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} tremove(bigpatch.diffs, 1) else -- Deletion or equality. -- Only take as much as we can stomach. diff_text = strsub(diff_text, 1, patch_size - patch.length1 - Patch_Margin) patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text if (diff_type == DIFF_EQUAL) then patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text else empty = false end patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} if (diff_text == bigpatch.diffs[1][2]) then tremove(bigpatch.diffs, 1) else bigpatch.diffs[1][2] = strsub(bigpatch.diffs[1][2], #diff_text + 1) end end end -- Compute the head context for the next patch. precontext = _diff_text2(patch.diffs) precontext = strsub(precontext, -Patch_Margin) -- Append the end context for this patch. local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin) if postcontext ~= '' then patch.length1 = patch.length1 + #postcontext patch.length2 = patch.length2 + #postcontext if patch.diffs[1] and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2] .. postcontext else patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext} end end if not empty then x = x + 1 tinsert(patches, x, patch) end end end x = x + 1 end end --[[ * Emulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * @return {string} The GNU diff string. --]] function _patch_appendText(patch, text) local coords1, coords2 local length1, length2 = patch.length1, patch.length2 local start1, start2 = patch.start1, patch.start2 local diffs = patch.diffs if length1 == 1 then coords1 = start1 else coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1 end if length2 == 1 then coords2 = start2 else coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2 end text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n' local op -- Escape the body of the patch with %xx notation. for x, diff in ipairs(patch.diffs) do local diff_type = diff[1] if diff_type == DIFF_INSERT then op = '+' elseif diff_type == DIFF_DELETE then op = '-' elseif diff_type == DIFF_EQUAL then op = ' ' end text[#text + 1] = op .. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace) .. '\n' end return text end -- Expose the API local _M = {} _M.DIFF_DELETE = DIFF_DELETE _M.DIFF_INSERT = DIFF_INSERT _M.DIFF_EQUAL = DIFF_EQUAL _M.diff_main = diff_main _M.diff_cleanupSemantic = diff_cleanupSemantic _M.diff_cleanupEfficiency = diff_cleanupEfficiency _M.diff_levenshtein = diff_levenshtein _M.diff_prettyHtml = diff_prettyHtml _M.match_main = match_main _M.patch_make = patch_make _M.patch_toText = patch_toText _M.patch_fromText = patch_fromText _M.patch_apply = patch_apply -- Expose some non-API functions as well, for testing purposes etc. _M.diff_commonPrefix = _diff_commonPrefix _M.diff_commonSuffix = _diff_commonSuffix _M.diff_commonOverlap = _diff_commonOverlap _M.diff_halfMatch = _diff_halfMatch _M.diff_bisect = _diff_bisect _M.diff_cleanupMerge = _diff_cleanupMerge _M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless _M.diff_text1 = _diff_text1 _M.diff_text2 = _diff_text2 _M.diff_toDelta = _diff_toDelta _M.diff_fromDelta = _diff_fromDelta _M.diff_xIndex = _diff_xIndex _M.match_alphabet = _match_alphabet _M.match_bitap = _match_bitap _M.new_patch_obj = _new_patch_obj _M.patch_addContext = _patch_addContext _M.patch_splitMax = _patch_splitMax _M.patch_addPadding = _patch_addPadding _M.settings = settings return _M
apache-2.0
ProtectionTeam/PCT
plugins/msg-checks.lua
2
18847
local TIME_CHECK = 2 local function pre_process(msg) local data = load_data(_config.moderation.data) local chat = msg.to.id local user = msg.from.id local is_channel = msg.to.type == "channel" local is_chat = msg.to.type == "chat" local auto_leave = 'auto_leave_bot' local hash = "gp_lang:"..chat local lang = redis:get(hash) local muteallchk = 'muteall:'..msg.to.id if is_channel or is_chat then local TIME_CHECK = 2 if data[tostring(chat)] then if data[tostring(chat)]['settings']['time_check'] then TIME_CHECK = tonumber(data[tostring(chat)]['settings']['time_check']) end end if msg.text then if msg.text:match("(.*)") then if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md") tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil) end end end if redis:get(muteallchk) and not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if not redis:get('autodeltime') then redis:setex('autodeltime', 14400, true) run_bash("rm -rf ~/.telegram-cli/data/sticker/*") run_bash("rm -rf ~/.telegram-cli/data/photo/*") run_bash("rm -rf ~/.telegram-cli/data/animation/*") run_bash("rm -rf ~/.telegram-cli/data/video/*") run_bash("rm -rf ~/.telegram-cli/data/audio/*") run_bash("rm -rf ~/.telegram-cli/data/voice/*") run_bash("rm -rf ~/.telegram-cli/data/temp/*") run_bash("rm -rf ~/.telegram-cli/data/thumb/*") run_bash("rm -rf ~/.telegram-cli/data/document/*") run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*") run_bash("rm -rf ~/.telegram-cli/data/encrypted/*") run_bash("rm -rf ./data/photos/*") end if data[tostring(chat)] and data[tostring(chat)]['settings'] then settings = data[tostring(chat)]['settings'] else return end if settings.mute_gif then mute_gif = settings.mute_gif else mute_gif = 'no' end if settings.mute_photo then mute_photo = settings.mute_photo else mute_photo = 'no' end if settings.mute_sticker then mute_sticker = settings.mute_sticker else mute_sticker = 'no' end if settings.mute_contact then mute_contact = settings.mute_contact else mute_contact = 'no' end if settings.mute_inline then mute_inline = settings.mute_inline else mute_inline = 'no' end if settings.mute_game then mute_game = settings.mute_game else mute_game = 'no' end if settings.mute_text then mute_text = settings.mute_text else mute_text = 'no' end if settings.mute_keyboard then mute_keyboard = settings.mute_keyboard else mute_keyboard = 'no' end if settings.mute_forward then mute_forward = settings.mute_forward else mute_forward = 'no' end if settings.mute_location then mute_location = settings.mute_location else mute_location = 'no' end if settings.mute_document then mute_document = settings.mute_document else mute_document = 'no' end if settings.mute_voice then mute_voice = settings.mute_voice else mute_voice = 'no' end if settings.mute_audio then mute_audio = settings.mute_audio else mute_audio = 'no' end if settings.mute_video then mute_video = settings.mute_video else mute_video = 'no' end if settings.mute_tgservice then mute_tgservice = settings.mute_tgservice else mute_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_join then lock_join = settings.lock_join else lock_join = 'no' end if settings.lock_tag then lock_tag = settings.lock_tag else lock_tag = 'no' end if settings.lock_username then lock_username = settings.lock_username else lock_username = 'no' end if settings.lock_pin then lock_pin = settings.lock_pin else lock_pin = 'no' end if settings.lock_english then lock_english = settings.lock_english else lock_english = 'no' end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_mention then lock_mention = settings.lock_mention else lock_mention = 'no' end if settings.lock_edit then lock_edit = settings.lock_edit else lock_edit = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_flood then lock_flood = settings.lock_flood else lock_flood = 'no' end if settings.lock_markdown then lock_markdown = settings.lock_markdown else lock_markdown = 'no' end if settings.lock_webpage then lock_webpage = settings.lock_webpage else lock_webpage = 'no' end if settings.lock_tabchi then lock_tabchi = settings.lock_tabchi else lock_tabchi = 'no' end if msg.adduser or msg.joinuser or msg.deluser then if mute_tgservice == "yes" then del_msg(chat, tonumber(msg.id)) end end if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then if msg.adduser or msg.joinuser then if lock_join == "yes" then function join_kick(arg, data) kick_user(data.id_, msg.to.id) end if msg.adduser then tdcli.getUser(msg.adduser, join_kick, nil) elseif msg.joinuser then tdcli.getUser(msg.joinuser, join_kick, nil) end end end end if msg.pinned and is_channel then if lock_pin == "yes" then if is_owner(msg) then return end if tonumber(msg.from.id) == our_id then return end local pin_msg = data[tostring(chat)]['pin'] if pin_msg then tdcli.pinChannelMessage(msg.to.id, pin_msg, 1) elseif not pin_msg then tdcli.unpinChannelMessage(msg.to.id) end if lang then tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html") elseif not lang then tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html") end end end if not is_mod(msg) and not is_whitelist(msg.from.id, msg.to.id) then if msg.edited and lock_edit == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.forward_info_ and mute_forward == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.photo_ and mute_photo == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.video_ and mute_video == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.document_ and mute_document == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.sticker_ and mute_sticker == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.animation_ and mute_gif == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.contact_ and mute_contact == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.location_ and mute_location == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.voice_ and mute_voice == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.content_ and mute_keyboard == "yes" then if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.game_ and mute_game == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.audio_ and mute_audio == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.media.caption then local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if link_caption and lock_link == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tag_caption = msg.media.caption:match("#") if tag_caption and lock_tag == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local username_caption = msg.media.caption:match("@") if username_caption and lock_username == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if is_filter(msg, msg.media.caption) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local badword_caption = msg.media.caption:match("کس")or msg.media.caption:match("کص")or msg.media.caption:match("کون")or msg.media.caption:match("کیر")or msg.media.caption:match("ممه")or msg.media.caption:match("کیری")or msg.media.caption:match("حرومی")or msg.media.caption:match("ننه")or msg.media.caption:match("کصده")or msg.media.caption:match("کث")or msg.media.caption:match("کسکش")or msg.media.caption:match("کصکش")or msg.media.caption:match("لاشی")or msg.media.caption:match("ناموس")or msg.media.caption:match("جنده")or msg.media.caption:match("یتیم")or msg.media.caption:match("خارکسده")or msg.media.caption:match("مادرجنده")or msg.media.caption:match("حرومزاده")or msg.media.caption:match("خواهرجنده")or msg.media.caption:match("خواهرتو")or msg.media.caption:match("مادرتو")or msg.media.caption:match("کونی")or msg.media.caption:match("اوبی")or msg.media.caption:match("لاشی")or msg.media.caption:match("kir")or msg.media.caption:match("mame")or msg.media.caption:match("kos")or msg.media.caption:match("lashi") if badword_caption and lock_badword == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tabchi_caption = msg.media.caption:match("ady")or msg.media.caption:match("Add")or msg.media.caption:match("add")or msg.media.caption:match("ادی عشقم")or msg.media.caption:match("ادشدی")or msg.media.caption:match("ادی بپر پیوی")or msg.media.caption:match("ادشد")or msg.media.caption:match("شرکن پیوی")or msg.media.caption:match("شرکن")or msg.media.caption:match("ادی پیوی شرکن")or msg.media.caption:match("پیوی شرکن")or msg.media.caption:match("ادد")or msg.media.caption:match("اد") if tabchi_caption and lock_tabchi == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local english_caption = msg.media.caption:match("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") if english_caption and lock_english == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]") if arabic_caption and lock_arabic == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.text then local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local max_chars = 40 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_char'] then max_chars = tonumber(data[tostring(msg.to.id)]['settings']['set_char']) end end local _nl, real_digits = string.gsub(msg.text, '%d', '') local max_real_digits = tonumber(max_chars) * 50 local max_len = tonumber(max_chars) * 51 if lock_spam == "yes" then if string.len(msg.text) > max_len or ctrl_chars > max_chars or real_digits > max_real_digits then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if link_msg and lock_link == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tag_msg = msg.text:match("#") if tag_msg and lock_tag == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local username_msg = msg.text:match("@") if username_msg and lock_username == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if is_filter(msg, msg.text) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local badword_msg = msg.text:match("کیر")or msg.text:match("کون")or msg.text:match("کص")or msg.text:match("کس")or msg.text:match("ممه")or msg.text:match("کیری")or msg.text:match("حرومی")or msg.text:match("ننه")or msg.text:match("کصده")or msg.text:match("کث")or msg.text:match("کسکش")or msg.text:match("کصکش")or msg.text:match("لاشی")or msg.text:match("ناموس")or msg.text:match("جنده")or msg.text:match("یتیم")or msg.text:match("خارکسده")or msg.text:match("مادرجنده")or msg.text:match("حرومزاده")or msg.text:match("خواهرجنده")or msg.text:match("خواهرتو")or msg.text:match("مادرتو")or msg.text:match("کونی")or msg.text:match("اوبی")or msg.text:match("لاشی")or msg.text:match("kir")or msg.text:match("kos")or msg.text:match("mame")or msg.text:match("lashi") if badword_msg and lock_badword == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tabchi_msg = msg.text:match("add")or msg.text:match("Add")or msg.text:match("ady")or msg.text:match("add")or msg.text:match("ادی عشقم")or msg.text:match("ادشدی")or msg.text:match("ادی بپر پیوی")or msg.text:match("ادشد")or msg.text:match("شرکن پیوی")or msg.text:match("شرکن")or msg.text:match("ادی پیوی شرکن")or msg.text:match("پیوی شرکن")or msg.text:match("ادد")or msg.text:match("اد") if tabchi_msg and lock_tabchi == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local english_msg = msg.text:match("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") if english_msg and lock_english == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if is_filter(msg, msg.text) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local arabic_msg = msg.text:match("[\216-\219][\128-\191]") if arabic_msg and lock_arabic == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.text:match("(.*)") and mute_text == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.content_.entities_ and msg.content_.entities_[0] then if msg.content_.entities_[0].ID == "MessageEntityMentionName" then if lock_mention == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then if lock_webpage == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then if lock_markdown == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end end if msg.to.type ~= 'pv' then if lock_flood == "yes" then if is_mod(msg) and is_whitelist(msg.from.id, msg.to.id) then return end if msg.adduser or msg.joinuser then return end local hash = 'user:'..user..':msgs' local msgs = tonumber(redis:get(hash) or 0) local NUM_MSG_MAX = 5 if data[tostring(chat)] then if data[tostring(chat)]['settings']['num_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max']) end end if msgs > NUM_MSG_MAX then if msg.from.username then user_name = "@"..msg.from.username else user_name = msg.from.first_name end if redis:get('sender:'..user..':flood') then return else del_msg(chat, msg.id) kick_user(user, chat) redis:del(hash) if not lang then tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md") elseif lang then tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md") end redis:setex('sender:'..user..':flood', 30, true) end end redis:setex(hash, TIME_CHECK, msgs+1) end end end end return msg end return { patterns = {}, patterns_fa = {}, pre_process = pre_process } --End msg_checks.lua--
gpl-3.0
JodliDev/DsMMO
mod/scripts/components/DsMMO.lua
1
36570
----------settings---------- local VERSION = 9 local LEVEL_MAX = 10 local LEVEL_UP_RATE = GetModConfigData("level_up_rate", KnownModIndex:GetModActualName("DsMMO")) or 1.5 local PENALTY_DIVIDE = GetModConfigData("penalty_divide", KnownModIndex:GetModActualName("DsMMO")) or 2 local RECIPE_DISTANCE = 10 local DSMMO_ACTIONS = { ["CHOP"] = 100, ["MINE"] = 50, ["ATTACK"] = 70, ["PLANT"] = 40, --and (partly) DEPLOY ["BUILD"] = 70, --and REPAIR and HAMMER and (partly) DEPLOY ["DIG"] = 40, ["EAT"] = 50, ["PICK"] = 30 } local MIN_EXP_ARRAY = { DSMMO_ACTIONS.CHOP, DSMMO_ACTIONS.MINE, DSMMO_ACTIONS.ATTACK, DSMMO_ACTIONS.PLANT, DSMMO_ACTIONS.BUILD, DSMMO_ACTIONS.DIG, DSMMO_ACTIONS.EAT, DSMMO_ACTIONS.PICK, } local ACTION_SPEED_INCREASE = { --be aware: Not all action have a simular named state! ["CHOP"] = "chop", -- scripts/stategraphs/SGwilson.lua:1707 to :1778 ["MINE"] = "mine" -- scripts/stategraphs/SGwilson.lua:1828 to :1846 } local DEPLOY_PLANT_ACTIONS = { --deploying these will give PLANT-exp. Everything else gives BUILD-exp pinecone = true, twiggy_nut = true, acorn = true, berrybush = true, berrybush2 = true, berrybush_juicy = true, sapling = true, grass = true } local DIG_SKILL_TARGETS = { --Treasurehunter works on these targets molehill = true } ----------global functions---------- local function is_fullMoon() return TheWorld.state.moonphase == "full" --GetClock():GetMoonPhase() end local function spawn_to_target(n, target) SpawnPrefab(n).Transform:SetPosition(target.Transform:GetWorldPosition()) end local function get_chance(base_r, lvl) local chance = base_r * (lvl / LEVEL_MAX) return is_fullMoon() and chance + 0.5 or chance end local function get_success(player, action, base_r) local chance = get_chance(base_r, player.components.DsMMO.level[action]) return math.random() < chance end local function alert(player, msg, len) player.components.talker:Say(msg, len or 10) end local function get_max_exp(action, lvl) return DSMMO_ACTIONS[action] + math.ceil(DSMMO_ACTIONS[action] * math.pow(LEVEL_UP_RATE, lvl)) end local function get_level(action, xp) if xp < DSMMO_ACTIONS[action] then return 0 else for lvl=1, LEVEL_MAX, 1 do if get_max_exp(action, lvl) > xp then return lvl end end return lvl --This would be way better for performance. But it leads to rounding errors: --return math.floor(math.log((xp-DSMMO_ACTIONS[action]) / DSMMO_ACTIONS[action]) / math.log(LEVEL_UP_RATE)) +1 end end local function add_spaces(str, size) local space = "" for i = string.len(str)+1, size, 1 do space = space .."_" end return space end ----------recipes and skills---------- local RECIPES = { amulet = { name="Ritual of death", tree="EAT", num=4, recipe={mandrake=2, nightmarefuel=2}, min_level=5, chance=2, fu=function(player, center) local self = player.components.DsMMO local xp = math.floor(self.exp.EAT / PENALTY_DIVIDE) --self.exp.EAT = xp --self.level.EAT = get_level("EAT", xp) self:set_level("EAT", get_level("EAT", xp), true) self._no_penalty = true player:PushEvent('death') center:Remove() end }, deerclops_eyeball = { name="Ritual of a new life", tree="EAT", num=7, recipe={goose_feather=2, bearger_fur=2, dragon_scales=1, fireflies=2}, min_level=8, chance=2, fu=function(player, center) local self = player.components.DsMMO player.components.inventory:DropEverything(false, false) self._player_original_position = player:GetPosition() self._player_backup[player.userid] = { map = player.player_classified.MapExplorer:RecordMap(), dsmmo = player.components.DsMMO:OnSave() } self:set_level("EAT", 0, true) TheWorld:PushEvent("ms_playerdespawnanddelete", player) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, molehill = { name="Ritual of mole infestation", tree="DIG", num=3, recipe={rocks=1, flint=1, nitre=1, goldnugget=1, marble=1, moonrocknugget=1, bluegem=1, redgem=1, purplegem=1, yellowgem=1, orangegem=1, greengem=1}, min_level=2, chance=1, fu=function(player, center) spawn_to_target("mole", center) if get_success(player, "DIG", 0.05) then spawn_to_target("mole", center) spawn_to_target("mole", center) spawn_to_target("mole", center) alert(player, "That was lucky") end end }, shovel = { name="Ritual of mole attraction", tree="DIG", num=4, recipe={houndstooth=2, log=2}, min_level=3, chance=1.5, fu=function(player, center) local x,y,z = center.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, 30, {'mole'}) for k,v in pairs(ents) do v.Transform:SetPosition(x,y,z) end end }, pitchfork = { name="Ritual of roman streets", tree="DIG", num=7, recipe={guano=3, rocks=3, boards=3, fireflies=1}, min_level=5, chance=0.8, fu=function(player, center) local x, y = TheWorld.Map:GetTileCoordsAtPoint(center.Transform:GetWorldPosition()) TheWorld.Map:SetTile(x, y, GROUND.ROAD) TheWorld.Map:RebuildLayer(GROUND.ROAD, x, y) TheWorld.Map:SetTile(x+1, y, GROUND.ROAD) TheWorld.Map:RebuildLayer(GROUND.ROAD, x+1, y) TheWorld.Map:SetTile(x-1, y, GROUND.ROAD) TheWorld.Map:RebuildLayer(GROUND.ROAD, x-1, y) center:Remove() end }, coontail = { name="Ritual of pussy love", tree="BUILD", num=5, recipe={fireflies=2, meat=1, houndstooth=2}, min_level=1, chance=0.5, fu=function(player, center) spawn_to_target("catcoonden", center) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, cave_banana_cooked = { name="Ritual of dumb monkeys", tree="BUILD", num=5, recipe={fireflies=2, poop=2, purplegem=1}, min_level=2, chance=0.5, fu=function(player, center) spawn_to_target("monkeybarrel", center) center:Remove() end, check=function(player, center) return TheWorld:HasTag("cave") end }, pond = { name="Ritual of dry humping", tree="BUILD", num=6, recipe={fish=2, fireflies=2, froglegs=1, mosquitosack=1}, min_level=3, chance=0.5, fu=function(player, center) center:Remove() end }, fish = { name="Ritual of splishy splashy", tree="BUILD", num=4, recipe={fireflies=2, froglegs=1, mosquitosack=1}, min_level=3, chance=0.5, fu=function(player, center) if TheWorld:HasTag("cave") then spawn_to_target("pond_cave", center) elseif TheWorld.Map:GetTileAtPoint(center.Transform:GetWorldPosition()) == GROUND.MARSH then spawn_to_target("pond_mos", center) else spawn_to_target("pond", center) end center:Remove() end }, walrus_camp = { name="Ritual of arctic fishing", tree="BUILD", num=6, recipe={cane=2, walrushat=2, fireflies=2}, min_level=4, chance=0.5, fu=function(player, center) center:Remove() end }, walrus_tusk = { name="Ritual of whalers feast", tree="BUILD", num=6, recipe={cane=2, walrushat=2, fireflies=2}, min_level=4, chance=0.5, fu=function(player, center) spawn_to_target("walrus_camp", center) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, houndstooth = { name="Ritual of puppy love", tree="BUILD", num=8, recipe={redgem=3, bluegem=3, fireflies=2}, min_level=5, chance=0.5, fu=function(player, center) spawn_to_target("houndmound", center) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, batwing = { name="Ritual of... I am Batman!", tree="BUILD", num=9, recipe={guano=4, rocks=3, fireflies=2}, min_level=6, chance=0.5, fu=function(player, center) spawn_to_target("batcave", center) center:Remove() end, check=function(player, center) return TheWorld:HasTag("cave") end }, batcave = { name="Ritual of robins fate", tree="BUILD", num=9, recipe={batwing=1, guano=3, rocks=3, fireflies=2}, min_level=6, chance=0.5, fu=function(player, center) center:Remove() end }, pigskin = { name="Ritual of Aquarius", tree="BUILD", num=11, recipe={fish=3, boards=3, rocks=3, fireflies=2}, min_level=7, chance=0.5, fu=function(player, center) spawn_to_target("mermhouse", center) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, armorsnurtleshell = { name="Ritual of escargot", tree="BUILD", num=8, recipe={slurtleslime=2, slurtle_shellpieces=3, slurtlehat=1, fireflies=2}, min_level=7, chance=0.5, fu=function(player, center) spawn_to_target("slurtlehole", center) center:Remove() end, check=function(player, center) return TheWorld:HasTag("cave") end }, tallbirdegg = { name="Ritual of Saurons bird", tree="BUILD", num=5, recipe={beardhair=2, cutgrass=2, fireflies=1}, min_level=8, chance=0.5, fu=function(player, center) spawn_to_target("tallbirdnest", center) center:Remove() end, check=function(player, center) return not TheWorld:HasTag("cave") end }, firepit = { name="Ritual of the pigable flame", tree="BUILD", num=7, recipe={pigskin=4, dragon_scales=1, fireflies=2}, min_level=8, chance=0.5, fu=function(player, center) spawn_to_target("pigtorch", center) center:Remove() end }, skeleton_player = { name="Ritual of rerevival", tree="BUILD", num=4, recipe={nightmarefuel=1, marble=2, amulet=1}, min_level=9, chance=0.8, check=function(player, center) for k, v in pairs(player.components.touchstonetracker.used) do return true end return false end, fu=function(player, center) local used = {} for k, v in pairs(player.components.touchstonetracker.used) do table.insert(used, k) end local removed_index = used[math.random(1, #used)] local touchstone = player.components.DsMMO._touchstone_index[removed_index] if touchstone then center:Remove() player.components.touchstonetracker.used[removed_index] = nil used[removed_index] = nil player.player_classified:SetUsedTouchStones(used) touchstone._enablelights:set(true) touchstone:PushEvent("enablelightsdirty", true) -- needed on singleplayer local player_pos = player:GetPosition() player.components.DsMMO._player_original_position = player_pos player:DoTaskInTime(1, function(player) player.Physics:Teleport(touchstone.Transform:GetWorldPosition()) player.components.health:SetInvincible(true) player.entity:Hide() touchstone.SoundEmitter:PlaySound("dontstarve/common/rebirth_amulet_raise") player:PushEvent("ghostvision", true) -- needed on singleplayer player.player_classified.isghostmode:set(true) end) player:DoTaskInTime(4, function() player.components.health:SetInvincible(false) player.Transform:SetPosition(player_pos.x, player_pos.y, player_pos.z) player.entity:Show() player.player_classified.isghostmode:set(false) player:PushEvent("ghostvision", false) player.components.DsMMO._player_original_position = nil end) end end }, campfire = { name="Ritual of homing flame", tree="BUILD", num=8, recipe={cutgrass=2, log=2, twigs=2, pinecone=2}, min_level=10, chance=1, fu=function(player, center) local self = player.components.DsMMO local pos = self._teleport_to center.components.fueled:DoDelta(TUNING.LARGE_FUEL) player.Physics:Teleport(pos.x, pos.y, pos.z) self:set_level("BUILD", 9, true) end, check=function(player, center) return player.components.DsMMO._teleport_to ~= nil end }, berries = { name="Ritual of redness", tree="PLANT", num=3, recipe={fireflies=1, spoiled_food=2}, min_level=3, chance=1, fu=function(player, center) spawn_to_target("berrybush", center) center:Remove() end }, berries_juicy = { name="Ritual of red juiciness", tree="PLANT", num=3, recipe={fireflies=1, spoiled_food=2}, min_level=4, chance=1, fu=function(player, center) spawn_to_target("berrybush_juicy", center) center:Remove() end }, cave_banana = { name="Ritual of bananana", tree="PLANT", num=3, recipe={spoiled_food=2, fireflies=1}, min_level=6, chance=0.9, fu=function(player, center) spawn_to_target("cave_banana_tree", center) center:Remove() end, check=function(player, center) return TheWorld:HasTag("cave") end }, livinglog = { name="Ritual of magic mushrooms", tree="PLANT", num=4, recipe={red_cap=1, blue_cap=1, green_cap=1, fireflies=1}, min_level=8, chance=0.8, fu=function(player, center) local r = math.random(1,3) if r == 1 then spawn_to_target("blue_mushroom", center) elseif r == 2 then spawn_to_target("green_mushroom", center) else spawn_to_target("red_mushroom", center) end center:Remove() end }, twigs = { name="Ritual of the longest Twig", tree="PICK", num=3, recipe={log=2, fireflies=1}, min_level=2, chance=1, fu=function(player, center) spawn_to_target("sapling", center) center:Remove() end }, cutgrass = { name="Ritual of reggae dreams", tree="PICK", num=3, recipe={spoiled_food=2, fireflies=1}, min_level=3, chance=0.9, fu=function(player, center) spawn_to_target("grass", center) center:Remove() end }, lightbulb = { name="Ritual of shiny balls", tree="PICK", num=3, recipe={twigs=2, fireflies=1}, min_level=5, chance=0.8, fu=function(player, center) spawn_to_target("flower_cave", center) center:Remove() end, check=function(player, center) return TheWorld:HasTag("cave") end }, cutreeds = { name="Ritual of Poe", tree="PICK", num=3, recipe={spoiled_food=2, fireflies=5}, min_level=7, chance=0.7, fu=function(player, center) spawn_to_target("reeds", center) center:Remove() end, check=function(player, center) return TheWorld.Map:GetTileAtPoint(center.Transform:GetWorldPosition()) == GROUND.MARSH end } } local SKILLS = { fireflies= { name="Ghosty fireflies", tree="PICK", min_level=1, chance=0.9 }, hungry_attack = { name="Hungry fighter", tree="EAT", min_level=1, rate=1 }, self_cannibalism = { name="Self-cannibalism", tree="EAT", min_level=3, rate=-0.05 }, attack = { name="Explosive touch", tree="ATTACK", min_level=1, chance=0.5 }, attacked = { name="Beetaliation", tree="ATTACK", min_level=2, chance=0.4 }, fertilize = { name="Double the shit", tree="PLANT", min_level=1, chance=0.5 }, harvest = { name="Plant another day", tree="PLANT", min_level=2, chance=0.5 }, dig = { name="Treasure hunter", tree="DIG", min_level=1, chance=0.3, items={--keys are their respective chances and should sum up to 1 [0.5]={"lightbulb", "redgem", "bluegem"}, [0.3]={"mandrake", "purplegem", "cutreeds", "slurper_pelt", "furtuft"}, [0.2]={"moonrocknugget", "beardhair", "yellowgem", "orangegem"} } } } ----------Mod-settings---------- print("[DsMMO] Implementing settings") for k,v in pairs(RECIPES) do if not GetModConfigData(k, KnownModIndex:GetModActualName("DsMMO")) then RECIPES[k] = nil print("[DsMMO] Disabling " ..k) end end for k,v in pairs(SKILLS) do if not GetModConfigData(k, KnownModIndex:GetModActualName("DsMMO")) then SKILLS[k] = nil print("[DsMMO] Disabling " ..k) end end local function duplicate_recipe(origin, copy) RECIPES[copy] = { duplicate = true, name = origin.name, tree = origin.tree, id = origin.tree, num = origin.num, recipe = origin.recipe, min_level = origin.min_level, chance = origin.chance, fu = origin.fu } end local function add_to_index(array) for k,v in pairs(array) do if not v._duplicate then local action = v.tree local lvl = v.min_level if not RECIPE_LEVEL_INDEX[action] then RECIPE_LEVEL_INDEX[action] = {} end if not RECIPE_LEVEL_INDEX[action][lvl] then RECIPE_LEVEL_INDEX[action][lvl] = {} end table.insert(RECIPE_LEVEL_INDEX[action][lvl], v) end end end if RECIPES.pond then --in case its disabled in the settings duplicate_recipe(RECIPES.pond, "pond_mos") duplicate_recipe(RECIPES.pond, "pond_cave") end ----------Prep-work---------- print("[DsMMO] Creating level up index") RECIPE_LEVEL_INDEX = {} add_to_index(SKILLS) add_to_index(RECIPES) ----------listener functions---------- local function onPerformaction(player, data) local action = player.bufferedaction or data.action local self = player.components.DsMMO if action then local actionId = action.action.id --if actionId == "EAT" then --if player.components.hunger.current < player.components.hunger.max and action.invobject and action.invobject.components.edible.hungervalue > 0 then --self:get_experience(actionId) --end if actionId == "HARVEST" then self:get_experience("PLANT") local crop = action.target.components.crop if crop and self:test_skill(SKILLS.harvest) then player.components.inventory:GiveItem(SpawnPrefab(crop.product_prefab)) spawn_to_target("collapse_small", player) end elseif actionId == "FERTILIZE" then self:get_experience("PLANT") local crop = action.target.components.crop if crop and not crop:IsReadyForHarvest() and self:test_skill(SKILLS.harvest) then local inst = SpawnPrefab("guano") crop:Fertilize(inst, player) if inst:IsValid() then inst:Remove() end spawn_to_target("collapse_small", player) end elseif actionId == "HAUNT" then if action.target then local targetN = action.target.prefab if targetN == "flower_evil" then spawn_to_target("ground_chunks_breaking", player) if self:test_skill(SKILLS.fireflies) then spawn_to_target("collapse_small", action.target) local fireflies = SpawnPrefab("fireflies") fireflies.Transform:SetPosition(action.target.Transform:GetWorldPosition()) fireflies.components.inventoryitem.ondropfn(fireflies) action.target:Remove() end end end elseif actionId == "ADDFUEL" then if action.target.prefab == "firepit" then --self._teleport_to = action.target.Transform:GetWorldPosition() self._teleport_to = action.target:GetPosition() end elseif actionId == "REPAIR" or actionId == "HAMMER" then self:get_experience("BUILD") elseif actionId == "TERRAFORM" then self:get_experience("DIG") elseif actionId == "DEPLOY" then self:get_experience(DEPLOY_PLANT_ACTIONS[action.invobject.prefab] and "PLANT" or "BUILD") elseif self.level[actionId] then self:get_experience(actionId) if actionId == "ATTACK" then if action.target and self:test_skill(SKILLS.attack) and action.target.components.combat then spawn_to_target("explode_small", action.target) action.target.SoundEmitter:PlaySound("dontstarve/common/blackpowder_explo") action.target.components.combat:GetAttacked(player, TUNING.SPEAR_DAMAGE) end elseif actionId == "DIG" then if not action.target.DsMMO_creation and action.invobject and DIG_SKILL_TARGETS[action.invobject.prefab] and self:test_skill(SKILLS.dig) then local items = SKILLS.dig.items local r = math.random() for k,v in pairs(items) do if r < k then spawn_to_target(v[math.random(1,table.getn(v))], player) break else r = r - k end end end end end end end local function onAttacked(player, data) player.components.DsMMO:get_experience("ATTACK") if data and data.attacker and data.attacker.prefab ~= "bee" and data.attacker.prefab ~= "killerbee" and data.attacker ~= player and player.components.DsMMO:test_skill(SKILLS.attacked) then local bee = SpawnPrefab("bee") bee.persists = false bee.Transform:SetPosition(player.Transform:GetWorldPosition()) bee.components.combat:SetTarget(data.attacker) bee.components.combat:SetRetargetFunction(nil, nil) bee.components.health:SetPercent(0.5) bee:RemoveComponent("lootdropper") bee:RemoveComponent("workable") if TheWorld.state.isspring then bee.AnimState:SetBuild("bee_build") end bee:DoTaskInTime(10, function(inst) if inst:IsValid() then inst:Remove() end end) end end local function onStartStarving(player) local self = player.components.DsMMO local skill = SKILLS.hungry_attack if self:test_skill(skill) then if player.components.combat ~= nil and player.components.combat.damagemultiplier ~= nil then player.default_damagemultiplier = player.components.combat.damagemultiplier else player.default_damagemultiplier = 1 end local new_damagemultiplier = self.level[skill.tree] * skill.rate if new_damagemultiplier > player.default_damagemultiplier then player.components.combat.damagemultiplier = new_damagemultiplier end end end local function onStopStarving(player) if player.default_damagemultiplier and player.components.combat and player.components.combat.damagemultiplier then player.components.combat.damagemultiplier = player.default_damagemultiplier end end local function onbecameghost(player) player.components.DsMMO:penalty() end local function onLogout(player) local self = player.components.DsMMO if self._info_entity then self:log_msg("Removing skill-indicator-sign") self._info_entity:Remove() self._info_entity = nil end end ----------Class---------- local DsMMO = Class(function(self, player) self.client = false self.player = player self._player_original_position = nil --if not nil, this will be saved when the player logs out unexpectedly self._action_states = {} self._info_entity = nil self.last_action = "EAT" self._teleport_to = nil local origin_updateState = player.sg.UpdateState player.sg.UpdateState = function(...) if not player.sg.currentstate then return end if self._action_states[player.sg.currentstate.name] then player.sg.currentstate = self._action_states[player.sg.currentstate.name] end origin_updateState(...) end --self.recipe = net_string(player.GUID, "DsMMO.recipe", "DsMMO.recipe") --## self:create_array() --this is a waste of performance - But I havent found a way to detect a newly created character --player:ListenForEvent("ms_becameghost", onbecameghost) player:ListenForEvent("death", onbecameghost) player:ListenForEvent("onremove", onLogout) player:ListenForEvent("attacked", onAttacked) player:ListenForEvent("performaction", onPerformaction) player:ListenForEvent("startstarving", onStartStarving) player:ListenForEvent("stopstarving", onStopStarving) end) function DsMMO:prepare_client() local guid = self.player.player_classified.GUID self:log_msg("Client-mod enabled") self.net_level_up_rate = net_ushortint(guid, "DsMMO.level_up_rate", "DsMMO.level_up_rate") self.net_min_exp = net_bytearray(guid, "DsMMO.min_exp", "DsMMO.min_exp") self.level_up_rate = LEVEL_UP_RATE --on a world without caves, we just take this value from here self.net_level_up_rate:set(LEVEL_UP_RATE*10) -- a shortint is less expensive than a float - so we just multiply self.net_min_exp:set(MIN_EXP_ARRAY) --local t = {} --table.insert(t, 2) --table.insert(t, 5) --self.net_min_exp:set(t) end function DsMMO:init_client() local guid = self.player.player_classified.GUID self:log_msg("Client-mod is setup") self.client = true self.recipe = net_string(guid, "DsMMO.recipe", "DsMMO.recipe") self.net_exp = {} for k_action,v in pairs(DSMMO_ACTIONS) do self.net_exp[k_action] = net_uint(guid, "DsMMO.exp." ..k_action, "DsMMO.exp." ..k_action) self.net_exp[k_action]:set(self.exp[k_action]) end end function DsMMO:update_client(action) if self.client then self.net_exp[action]:set(self.exp[action]) end end function DsMMO:log_msg(msg) print("[DsMMO/" ..self.player.name .."] " ..msg) end function DsMMO:add_indexVars(touchtstone_index, player_backup) self._touchstone_index = touchtstone_index self._player_backup = player_backup end function DsMMO:get_experience(action, silent) local player = self.player local lvl = self.level[action] if lvl < LEVEL_MAX then local xp = self.exp[action] + 1 local max_exp = self.max_exp[action] self.exp[action] = xp; if xp > max_exp then lvl = lvl+1 self.level[action] = lvl self.max_exp[action] = get_max_exp(action, lvl) self:update_client(action) if not silent then alert(player, self:newLevelString(action, lvl)) player.SoundEmitter:PlaySound("dontstarve/characters/wx78/levelup") end self:update_actionSpeed(action) end end self:set_last_action(action) end function DsMMO:set_last_action(action) self.last_action = action if self._info_entity ~= nil then local inst = nil if action == "CHOP" then inst = SpawnPrefab("axe") elseif action == "MINE" then inst = SpawnPrefab("pickaxe") elseif action == "ATTACK" then inst = SpawnPrefab("spear") elseif action == "PLANT" then inst = SpawnPrefab("carrot") elseif action == "BUILD" then inst = SpawnPrefab("hammer") elseif action == "DIG" then inst = SpawnPrefab("shovel") elseif action == "EAT" then inst = SpawnPrefab("meatballs") elseif action == "PICK" then inst = SpawnPrefab("berries") else inst = SpawnPrefab("minisign") end self._info_entity.components.drawable:OnDrawn(inst.prefab, inst) inst:Remove() end end function DsMMO:newLevelString(action, lvl) local base = action .."-level: " ..lvl .." !\n" if lvl < LEVEL_MAX then base = base ..self:calc_mssing_xp(action) .." exp until lvl " ..(lvl+1) .."\n" end if RECIPE_LEVEL_INDEX[action] and RECIPE_LEVEL_INDEX[action][lvl] then for k,v in pairs(RECIPE_LEVEL_INDEX[action][lvl]) do base = base .."\nYou learned a new skill: " ..v.name end end return base end function DsMMO:update_actionSpeed(action) --Unfortunately, there is no real way to increase the Action-state-speed -- So we create our own State and override it if necessary -- sources: -- scripts/stategraph.lua -- scripts/stategraphs/SGwilson.lua if ACTION_SPEED_INCREASE[action] then local lvl = self.level[action]/LEVEL_MAX local action_key = ACTION_SPEED_INCREASE[action] --local action_key = string.lower(action) local origin_state = self.player.sg.sg.states[action_key] if self._action_states[action_key] then local new_state = self._action_states[action_key].timeline for k_timeline,v_timeline in pairs(new_state) do local t = origin_state.timeline[k_timeline].time new_state[k_timeline] = TimeEvent(t - t*lvl, v_timeline.fn) --new_state.timeline[k_timeline] = TimeEvent(v_timeline.time - v_timeline.time*lvl, v_timeline.fn) end else self._action_states[action_key] = State{name=origin_state.name, timeline={}} local new_state = self._action_states[action_key] for k,v in pairs(origin_state) do if k == "timeline" then for k_timeline,v_timeline in pairs(v) do new_state.timeline[k_timeline] = TimeEvent(v_timeline.time - v_timeline.time*lvl, v_timeline.fn) end else new_state[k] = v end end end end end function DsMMO:init_recipe(target) local recipe_data = RECIPES[target.prefab] if recipe_data then if self.level[recipe_data.tree] < recipe_data.min_level then alert(self.player, "I don't feel prepared...") if self.client then self.recipe:set_local("") --to make sure that the same recipe can be sent multiple times self.recipe:set(target.prefab) end elseif recipe_data.check and not recipe_data.check(self.player, target) then alert(self.player, "I just can't...") else self:check_recipe(target, recipe_data.recipe, recipe_data.num, recipe_data.tree, recipe_data.chance, recipe_data.fu) end return true end return false end function DsMMO:check_recipe(center, recipe, ings_needed_sum, tree, chance, fn) local collection = {} local pos = center:GetPosition() local near = TheSim:FindEntities(pos.x, pos.y, pos.z, RECIPE_DISTANCE) local ingredients = {} for k,v in pairs(recipe) do ingredients[k] = v end for k,v in pairs(near) do local itemN = v.prefab local ing_num = ingredients[itemN] if v.parent == nil and ings_needed_sum > 0 and ing_num and ing_num>0 then self:log_msg("Recipe: Found " ..itemN) table.insert(collection, v) ingredients[itemN] = ing_num - 1 ings_needed_sum = ings_needed_sum - 1 if ings_needed_sum <= 0 then for k2,v2 in pairs(collection) do local fire = SpawnPrefab("campfirefire") fire.Transform:SetPosition(v2.Transform:GetWorldPosition()) fire:DoTaskInTime(2, function(inst) inst:Remove() end) v2:Remove() end self.player:DoTaskInTime(2, function(player) spawn_to_target("collapse_big", center) if get_success(player, tree, chance) then spawn_to_target("lightning", center) fn(player, center) else alert(player, "It failed...") end end) return end end end if self.client then self.recipe:set_local("") --to make sure that the same recipe can be sent multiple times self.recipe:set(center.prefab) end --self.recipe:set_local("") --to make sure that the same recipe can be sent multiple times --## --self.recipe:set(center.prefab) --## --alert(self.player, "What am I missing..?") alert(self.player, "I am still missing " ..ings_needed_sum ..((ings_needed_sum>1) and " ingredients." or " ingredient.")) end function DsMMO:test_skill(skill) return skill and self.level[skill.tree] >= skill.min_level and (not skill.chance or get_success(self.player, skill.tree, skill.chance)) end function DsMMO:OnLoad(data) if data.dsmmo_version then if data.dsmmo_version == VERSION and data.dsmmo_level_up_rate == LEVEL_UP_RATE then self.exp = data.dsmmo_exp self.max_exp = data.dsmmo_max_exp self.level = data.dsmmo_level --for k_action,v in pairs(DSMMO_ACTIONS) do --self.max_exp[k_action] = get_max_exp(k_action, self.level[k_action]) --end for k,v in pairs(ACTION_SPEED_INCREASE) do self:update_actionSpeed(k) end else self:log_msg("Upgrading from v" ..(data.dsmmo_version or "nil") ..",rate=" ..(data.dsmmo_level_up_rate or "nil") .." to v" ..VERSION ..",rate=" ..LEVEL_UP_RATE) for k,v in pairs(DSMMO_ACTIONS) do --we transfer each variable seperately to make sure the different version stays compatible if data.dsmmo_level[k] then self.exp[k] = data.dsmmo_exp[k] local lvl = get_level(k, data.dsmmo_exp[k]) self.level[k] = lvl self.max_exp[k] = get_max_exp(k, lvl) --self.exp_left[k]:set(get_max_exp(k, lvl) - data.dsmmo_exp[k]) --## --self.net_level[k]:set(lvl) --## self:update_actionSpeed(k) end end end if data._player_original_position then self.player.Physics:Teleport(data._player_original_position.x, data._player_original_position.y, data._player_original_position.z) end self._teleport_to = data._teleport_to end end function DsMMO:OnSave() local data = { dsmmo_exp = self.exp, dsmmo_max_exp = self.max_exp, dsmmo_level = self.level, _teleport_to = self._teleport_to, dsmmo_version = VERSION, dsmmo_level_up_rate = LEVEL_UP_RATE } if self._player_original_position then self:log_msg("saving original player-position") data["_player_original_position"] = self._player_original_position end return data end function DsMMO:create_array() local player = self.player local guid = player.GUID self.exp = {} --self.exp_left = {} --self.net_level = {} self.level = {} self.max_exp = {} for k,v in pairs(DSMMO_ACTIONS) do self.exp[k] = 0 self.level[k] = 0 self.max_exp[k] = DSMMO_ACTIONS[k] --self.exp_left[k] = net_ushortint(guid, "DsMMO.expleft." ..k) --## --self.net_level[k] = net_ushortint(guid, "DsMMO.level." ..k) --## end end function DsMMO:penalty() if self._no_penalty then self._no_penalty = nil return end for k,v in pairs(DSMMO_ACTIONS) do local xp = math.floor(self.exp[k] / PENALTY_DIVIDE) self.exp[k] = xp if xp > 0 then --self.level[k] = get_level(k, xp) --self:update_client(k) --self:update_actionSpeed(k) self:set_level(k, get_level(k, xp), true) end end end function DsMMO:set_level(action, lvl, silent) if DSMMO_ACTIONS[action] then local max_exp = get_max_exp(action, lvl-1) self.exp[action] = max_exp self.max_exp[action] = max_exp self.level[action] = lvl-1 self:get_experience(action, silent) return true else return false end end function DsMMO:calc_mssing_xp(action) return self.max_exp[action] - self.exp[action] +1 end function DsMMO:use_cannibalism_skill(action, heal) local skill = SKILLS.self_cannibalism local output = "" if not self:test_skill(skill) then output = "I don't know how..." else if not self.exp[action] then output = "I can't eat the skill " ..action else local comp = nil local diff = nil if heal == "health" then comp = self.player.components.health diff = math.ceil(comp.maxhealth - comp.currenthealth) elseif heal == "sanity" then comp = self.player.components.sanity diff = math.ceil(comp.max - comp.current) elseif heal == "hunger" then comp = self.player.components.hunger diff = math.ceil(comp.max - comp.current) else output = heal .." is nothing I can gain by eating myself" end if comp ~= nil then diff = diff + math.ceil(diff * (self.level[skill.tree] * skill.rate)) --skill.rate is negative if self.exp[action] < diff then output = "I don't have enough exp for that" else comp:SetPercent(1) self.exp[action] = self.exp[action] - diff self.level[action] = get_level(action, self.exp[action]) self:update_client(action) output = "Lost " ..diff .." " ..action .. "-exp" end end end end alert(self.player, output, 5) end function DsMMO:show_info() local action = self.last_action local output = "" if DSMMO_ACTIONS[action] then local lvl = self.level[action] local xp = self:calc_mssing_xp(action) local level = self.level output = (lvl < LEVEL_MAX and (action ..": " ..xp .." exp --> lvl " ..(lvl+1)) or (action ..": lvl " ..lvl)) .."\n__________\nI have learned the following " ..action .."-skills:\n" if RECIPE_LEVEL_INDEX[action] then for k_lvl,v_lvl in pairs(RECIPE_LEVEL_INDEX[action]) do if lvl >= k_lvl then for k,v in pairs(v_lvl) do output = output .."\n" ..v.name .."(" ..(v.chance ~= nil and (get_chance(v.chance, level[v.tree])*100) .."%)" or (level[v.tree] * v.rate) .."x)" ) end end end end else output = action .." is not a valid DsMMO-skill" end return output end function DsMMO:run_command(cmd, arg1, arg2, arg3) local output = "" local dur = 5 if arg1 == "help" or arg1 == "?" then dur = 20 output = "______________________ Possible commands: ______________________" .."\n#dsmmo ________________________________ Spawns a level info sign" .."\n#dsmmo [ skill ] ___________________ level info sign for a specific skill" .."\n#dsmmo eat [ action ] [ health | hunger | sanity ] ___________________" .."\n_________ Self-cannibalism-command to exchange EAT-levels for healing" .."\n#dsmmo list _____________________________ List of all DsMMO-levels" .."\n#dsmmo help ______________________________________ this help-text" elseif arg1 == "list" then for k,v in pairs(self.level) do output = output ..k ..":" ..add_spaces(k, 10) ..add_spaces(tostring(v), 2) ..v .."\n" end elseif arg1 == "eat" and arg2 and arg3 then self:use_cannibalism_skill(string.upper(arg2), string.lower(arg3)) return else if self._info_entity and self._info_entity.entity:IsValid() then self._info_entity.Transform:SetPosition(self.player.Transform:GetWorldPosition()) else local inst = SpawnPrefab("minisign") inst.persists = false inst.Transform:SetPosition(self.player.Transform:GetWorldPosition()) inst.DsMMO_creation = true inst.components.inspectable.getspecialdescription = function(inst, player) return player.components.DsMMO:show_info() end self._info_entity = inst inst:RemoveComponent("burnable") inst.components.workable:SetOnFinishCallback(function(inst) inst:Remove() end) end local action if arg1 and DSMMO_ACTIONS[string.upper(arg1)] then action = string.upper(arg1) else action = self.last_action end self:set_last_action(action) output = self:show_info() end alert(self.player, output, dur) end return DsMMO
apache-2.0
lite5/lua-codec
test/test_rsa_encrypt_decrypt.lua
3
1474
local codec = require('codec') local src = '123456' local pubpem = [[-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsxjKD2lnmkmELoo5QphM/VdRE JKym26R0T+19JDa3MVZFDbwgUGT8XM8bElrKgxexhTVRt07btyIejdbiPx7sCbWc VP8peZI+QZEVVzaE2Ci5n0lP9v9GUSl0QfZU94uIwl++BVq0VFvbHax/R/q4oTRD 1u73ASM27QW42+cJFwIDAQAB -----END PUBLIC KEY-----]] local bs = codec.rsa_public_encrypt(src, pubpem, 2) local dst = codec.base64_encode(bs) print(dst) local privpem = [[-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCsxjKD2lnmkmELoo5QphM/VdREJKym26R0T+19JDa3MVZFDbwg UGT8XM8bElrKgxexhTVRt07btyIejdbiPx7sCbWcVP8peZI+QZEVVzaE2Ci5n0lP 9v9GUSl0QfZU94uIwl++BVq0VFvbHax/R/q4oTRD1u73ASM27QW42+cJFwIDAQAB AoGALHoNMQI52HBgSSV8q2hFVi2bKjuisoWibUrSIT/8UeaChd5GSq9Hf+vIaPit pKpgpBNdqX6d71PSlbj/01hadg5IxrGWQZWzT/3IzuhTxAu4TkztUJelGRcM6ykZ 5AxijiIxTLWSY/ygtEaM2QShhl8dCReNT+oIDGf/iMSTVykCQQDl07WZR9ATReVc vM7/v9iiz/g1Tj9/8AOuyYOZ5kp5a8IAr48dXixzuTZY66RwPj/J5vrzLuHc7Uc0 RAi4hgmTAkEAwHMxP0KVOzDH49SsiUjfOycqrBl68QCXUWQj2mi7Bb1pLryoYDFv FTuk6pxKyfr5O8M2s8thTz6f3EO7hFqk7QJAdX8Ly2ZkYUYNoaDBbwzEk1AhhBcR 7bVmHJjXV/ndP0Aw+arHTutTbIJW35TxB5U7hVw6FdN1Ez6XdYgGsVeNUwJAEjlW SoVFmGtQInT7Oaza5sEYu19WUwgZTC3Nb1tHio2bLj/TOfi0ajBRt53BP0sy2sPr pC74MgbeIH+RfEERKQJBAIpPkQztkbpZwD9gDiK86U+HHYZrhglxgfDIXYwTH3z/ KCrfyNxiH2im9ZhwuhLs7LDD7wDPHUC5BItx2tYN10s= -----END RSA PRIVATE KEY-----]] local dbs = codec.base64_decode(dst) local dsrc = codec.rsa_private_decrypt(dbs, privpem) print(dsrc) assert(dsrc == src)
mit
jcmoyer/hug
vector2.lua
1
7471
-- -- Copyright 2013 J.C. Moyer -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- --- Implements a 2D vector type. -- `vector2` is implemented as a table with X and Y components residing at -- indices `1` and `2`, respectively. This design choice has the following -- implications: -- -- 1. `unpack` can be used to retrieve the components of a vector as needed. -- 2. Numerical indices give certain performance benefits due to the way tables -- are implemented in Lua. -- -- @type vector2 -- @usage -- local a = vector2.new(3, 4) -- local b = vector2.new(5, 2) -- -- allocates a new vector: -- local c = a + b -- -- modifies vector b in-place: -- b:sub(a) -- -- -- unpack allows you to pass vector components into functions: -- love.graphics.translate(unpack(c)) local mathx = require('hug.extensions.math') local module = require('hug.module') local vector2 = module.new() local function isvector2(v) return getmetatable(v) == vector2 end --- Implements binary operator `+` for `vector2` objects. -- @tparam vector2 a The first vector. -- @tparam vector2 b The second vector. -- @treturn vector2 The result of adding `a` and `b`. function vector2.__add(a, b) return a:clone():add(b) end --- Implements binary operator `-` for `vector2` objects. -- @tparam vector2 a The first vector. -- @tparam vector2 b The second vector. -- @treturn vector2 The result of subtracting `b` from `a`. function vector2.__sub(a, b) return a:clone():sub(b) end --- Implements binary operator `*` for `vector2` objects. -- @tparam vector2|number a The first vector or scalar. -- @tparam number|vector2 b The second vector or scalar. -- @treturn vector2 The result of multiplying `a` by `b`. function vector2.__mul(a, b) local result if isvector2(a) then result = a:clone() result:mul(b) else result = b:clone() result:mul(a) end return result end --- Implements binary operator `/` for `vector2` objects. -- @tparam vector2 a The vector. -- @number b The scalar. -- @treturn vector2 A new `vector2` containing the results of the division. function vector2.__div(a, b) return a:clone():div(b) end --- Implements binary operator `==` for `vector2` objects. -- @tparam vector2 a Vector A. -- @tparam vector2 b Vector B. -- @treturn boolean True if the vectors are equal; otherwise false. function vector2.__eq(a, b) return a[1] == b[1] and a[2] == b[2] end --- Implements `tostring` for `vector2` objects. -- Do not use this method for serialization as the format may change in the -- future. This method only guarantees that `vector2` objects can be converted -- to a human-readable representation. -- @treturn string A `string` representation for this vector. function vector2:__tostring() return string.format('<%f,%f>', self[1], self[2]) end --- Creates a new vector2 object. -- @number[opt=0] x The X component for this vector. Defaults to 0 if none is -- provided. -- @number[opt=0] y The Y component for this vector. Defaults to 0 if none is -- provided. -- @treturn vector2 A new vector 2 object with the specified magnitude. function vector2.new(x, y) local instance = { x or 0, y or 0 } return setmetatable(instance, vector2) end --- Creates a new vector2 object from polar coordinates. -- @number r The radial coordinate. -- @number phi The polar angle. -- @treturn vector2 A new vector 2 object with the specified radial coordinate and angle. function vector2.frompolar(r, phi) local x = r * math.cos(phi) local y = r * math.sin(phi) return vector2.new(x, y) end --- Clones this vector2 and returns it. -- @treturn vector2 function vector2:clone() return vector2.new(unpack(self)) end --- Returns the X component of this vector. -- This is equivalent to vector[1]. -- @treturn number The X component of this vector. function vector2:x() return self[1] end --- Returns the Y component of this vector. -- This is equivalent to vector[2]. -- @treturn number The Y component of this vector. function vector2:y() return self[2] end --- Computes the length of this vector. -- @treturn number The length of this vector. function vector2:len() local x = self[1] local y = self[2] return math.sqrt(x * x + y * y) end --- Computes the dot product between this vector and another. -- @tparam vector2 vec The second vector. -- @treturn number The dot product between the given vectors. function vector2:dot(vec) return self[1] * vec[1] + self[2] * vec[2] end --- Adds another vector to this one. -- @tparam vector2|number a If a `vector2` is provided, each of its components -- will be added to the components of this vector. If a number is provided -- instead, it will be added to the X component of this vector. -- @number b Amount to add to the Y component of this vector. Only required if -- `a` is not a `vector2`. -- @treturn vector2 This vector. function vector2:add(a, b) if isvector2(a) then self[1] = self[1] + a[1] self[2] = self[2] + a[2] else self[1] = self[1] + a self[2] = self[2] + b end return self end --- Subtracts another vector from this one. -- @tparam vector2|number a If a `vector2` is provided, its components will be -- subtracted from the components of this vector. If a number is provided -- instead, it will be subtracted from the X component of this vector. -- @number b Amount to subtract from the Y component of this vector. Only -- required if `a` is not a `vector2`. -- @treturn vector2 This vector. function vector2:sub(a, b) if isvector2(a) then self[1] = self[1] - a[1] self[2] = self[2] - a[2] else self[1] = self[1] - a self[2] = self[2] - b end return self end --- Multiplies this vector by a scalar amount. -- @number a Amount to multiply this vector by. -- @treturn vector2 This vector. function vector2:mul(a) self[1] = self[1] * a self[2] = self[2] * a return self end --- Divides this vector by a scalar amount. -- @number a Amount to divide this vector by. -- @treturn vector2 This vector. function vector2:div(a) self[1] = self[1] / a self[2] = self[2] / a return self end --- Normalizes this vector. -- This vector will become a unit vector codirectional with the original -- vector. -- @treturn vector2 This vector. function vector2:normalize() local x = self[1] local y = self[2] local l = math.sqrt(x * x + y * y) self[1] = x / l self[2] = y / l return self end --- Sets the individual components of this vector. -- @number x New value for the X component of this vector. -- @number y New value for the Y component of this vector. -- @treturn vector2 This vector. function vector2:set(x, y) if isvector2(x) then self[1] = x[1] self[2] = x[2] else self[1] = x self[2] = y end return self end --- Linearly interpolates between two vectors and writes the result to `output`. function vector2.lerp(from, to, t, output) output[1] = mathx.lerp(from[1], to[1], t) output[2] = mathx.lerp(from[2], to[2], t) end return vector2
apache-2.0
otland/forgottenserver
data/actions/scripts/other/bed_modification_kits.lua
13
1647
local beds = { [7904] = {{7811, 7812}, {7813, 7814}}, -- green kit [7905] = {{7819, 7820}, {7821, 7822}}, -- yellow kit [7906] = {{7815, 7816}, {7817, 7818}}, -- red kit [7907] = {{1754, 1755}, {1760, 1761}}, -- removal kit [20252] = {{20197, 20198}, {20199, 20200}} -- canopy kit } local function internalBedTransform(item, targetItem, toPosition, itemArray) targetItem:transform(itemArray[1]) targetItem:getPosition():sendMagicEffect(CONST_ME_POFF) Tile(toPosition):getItemByType(ITEM_TYPE_BED):transform(itemArray[2]) toPosition:sendMagicEffect(CONST_ME_POFF) item:remove() end function onUse(player, item, fromPosition, target, toPosition, isHotkey) local newBed = beds[item:getId()] if not newBed or type(target) ~= "userdata" or not target:isItem() then return false end local tile = Tile(toPosition) if not tile or not tile:getHouse() then return false end local targetItemId = target:getId() if targetItemId == newBed[1][1] or targetItemId == newBed[2][1] then player:sendTextMessage(MESSAGE_STATUS_SMALL, "You already have this bed modification.") return true end for _, bed in pairs(beds) do if bed[1][1] == targetItemId or table.contains({1758, 5502, 18027}, targetItemId) then toPosition:sendMagicEffect(CONST_ME_POFF) toPosition.y = toPosition.y + 1 internalBedTransform(item, target, toPosition, newBed[1]) break elseif bed[2][1] == targetItemId or table.contains({1756, 5500, 18029}, targetItemId) then toPosition:sendMagicEffect(CONST_ME_POFF) toPosition.x = toPosition.x + 1 internalBedTransform(item, target, toPosition, newBed[2]) break end end return true end
gpl-2.0