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
dangersuperbot/super_boomrange
plugins/speaking.lua
1
1979
local function run(msg) if msg.text == "hi" then return "های" end if msg.text == "Hi" then return "سلام عزیزم" end if msg.text == "Hello" then return "سلام" end if msg.text == "hello" then return "سلوم عجقم" end if msg.text == "Salam" then return "سلام علیکم" end if msg.text == "salam" then return "علیکم السلام" end if msg.text == "سلام" then return "Hi" end if msg.text == "س" then return "مثل آدم بنویس سلام!" end if msg.text == "fuck" then return "you ! _|_" end if msg.text == "boomrange" then return "جانم؟" end if msg.text == "bomrange" then return "جانم؟" end if msg.text == "danger" then return "با بابام کاری داری؟ 😎 تو @xXDangerXxبهم بگو بهش میگم 🤗" end if msg.text == "senator" then return "با بابام کاری داری؟ 😎 تو @senator_blackkهم بگو بهش میگم 🤗🤗" end if msg.text == "بومرنگ" then return "کاری داشتی؟" end if msg.text == "bot" then return "من ربات نیستم !" end if msg.text == "ربات" then return "من ربات نیستم !" end if msg.text == "بات" then return "من ربات نیستم !" end if msg.text == "روبات" then return "من ربات نیستم !" end if msg.text == "Bot" then return "Huuuum?" end if msg.text == "Bye" then return "بای عجیجم" end if msg.text == "bye" then return "خدا حافظ" end if msg.text == "بای" then return "bye" end if msg.text == "خداحافظ" then return "Bye" end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^[Hh]i$", "^[Hh]ello$", "^[Bb]ot$", "^[Bb]ye$", "^سلام$", "^س$", "^بای$", "^خداحافظ$", "^?$", "^boomrange$", "^[Bb]omrange$", "^[Dd]anger$", "^senator$", "^[Ss]alam$", "^بات$", "^ربات$", "^روبات$", }, run = run, --privileged = true, pre_process = pre_process }
gpl-2.0
hectron/dotfiles
nvim/.config/nvim/after/plugin/lspconfig.rc.lua
1
1826
local nvim_lsp_installed, nvim_lsp = pcall(require, "lspconfig") if not nvim_lsp_installed then print("nvim-lsp is not installed! Aborting") return end local mason_installed, mason_config = pcall(require, "mason") if not mason_installed then print("Unable to install LSP servers because mason is not installed") return end local mason_lspconfig_installed, mason_lspconfig = pcall(require, "mason-lspconfig") if not mason_lspconfig_installed then print("Unable to install LSP servers because mason-lspconfig is not installed") return end -- Automatically install these LSP servers and set them up with proper 'on_attach' functions local lsp_servers = { 'bashls', 'dockerls', 'gopls', 'jsonnet_ls', 'pyright', 'solargraph', 'sumneko_lua', 'terraformls', 'tsserver', 'vimls', 'yamlls', } mason_config.setup({}) mason_lspconfig.setup({ automatic_installation = true, ensure_installed = lsp_servers, }) -- Specify any custom settings for an LSP server here local server_specific_opts = { ['solargraph'] = function(opts) opts.settings = { filetypes = { 'ruby', 'rake' } } end, ['gopls'] = function(opts) opts.cmd = { 'gopls', '-remote=auto' } end, ['sumneko_lua'] = function(opts) opts.settings = { Lua = { diagnostics = { globals = { 'vim', }, }, workspace = { library = vim.api.nvim_get_runtime_file("", true), }, }, } end, } local lsp_handlers = require("lsp/handlers") for _, server_name in pairs(lsp_servers) do local opts = { on_attach = lsp_handlers.on_attach, capabilities = lsp_handlers.capabilities, } if server_specific_opts[server_name] then server_specific_opts[server_name](opts) end nvim_lsp[server_name].setup(opts) end
mit
pazos/koreader
spec/unit/document_registry_spec.lua
8
2568
describe("document registry module", function() local DocSettings, DocumentRegistry setup(function() require("commonrequire") DocSettings = require("docsettings") DocumentRegistry = require("document/documentregistry") end) it("should get preferred rendering engine", function() assert.is_equal("crengine", DocumentRegistry:getProvider("bla.epub").provider) assert.is_equal("mupdf", DocumentRegistry:getProvider("bla.pdf").provider) end) it("should return all supported rendering engines", function() local providers = DocumentRegistry:getProviders("bla.epub") assert.is_equal("crengine", providers[1].provider.provider) assert.is_equal("mupdf", providers[2].provider.provider) end) it("should set per-document setting for rendering engine", function() local path = "../../foo.epub" local pdf_provider = DocumentRegistry:getProvider("bla.pdf") DocumentRegistry:setProvider(path, pdf_provider, false) local provider = DocumentRegistry:getProvider(path) assert.is_equal("mupdf", provider.provider) local docsettings = DocSettings:open(path) docsettings:purge() end) it("should set global setting for rendering engine", function() local path = "../../foo.fb2" local pdf_provider = DocumentRegistry:getProvider("bla.pdf") DocumentRegistry:setProvider(path, pdf_provider, true) local provider = DocumentRegistry:getProvider(path) assert.is_equal("mupdf", provider.provider) G_reader_settings:delSetting("provider") end) it("should return per-document setting for rendering engine", function() local path = "../../foofoo.epub" local docsettings = DocSettings:open(path) docsettings:saveSetting("provider", "mupdf") docsettings:flush() local provider = DocumentRegistry:getProvider(path) assert.is_equal("mupdf", provider.provider) docsettings:purge() end) it("should return global setting for rendering engine", function() local path = "../../foofoo.fb2" local provider_setting = {} provider_setting.fb2 = "mupdf" G_reader_settings:saveSetting("provider", provider_setting) local provider = DocumentRegistry:getProvider(path) assert.is_equal("mupdf", provider.provider) G_reader_settings:delSetting("provider") end) end)
agpl-3.0
16cameronk/MyoScripts
ScriptGeneratorPython/luaTemplateSimple.lua
2
1844
scriptId = 'com.thalmic.generated' --TEMPLATE FOR SCRIPT GENERATION, DO NOT MODIFY --Helper functions function conditionallySwapWave(pose) if myo.getArm() == "left" then if pose == "waveIn" then pose = "waveOut" elseif pose == "waveOut" then pose = "waveIn" end end return pose end --Control Functions function waveInAction() --myo.debug("WaveIn") --PLACEHOLDER:WAVEIN end function waveOutAction() --myo.debug("WaveOut") --PLACEHOLDER:WAVEOUT end function fingersSpreadAction() --myo.debug("fingersSpread") --PLACEHOLDER:FINGERSSPREAD end function fistAction() --myo.debug("fist") --PLACEHOLDER:FIST end function thumbToPinkyAction() --PLACEHOLDER: thumbToPinky end --Toggle Unlock Functions function lock() enabled = false myo.vibrate("short") end function unlock() enabled = true myo.vibrate("short") myo.vibrate("short") end function onPoseEdge(pose, edge) pose=conditionallySwapWave(pose) local now = myo.getTimeMilliseconds() if edge == "on" then if pose == "waveIn" and enabled then waveInAction() elseif pose == "waveOut" and enabled then waveOutAction() elseif pose == "fist" and enabled then fistAction() elseif pose == "fingersSpread" and enabled then fingersSpreadAction() elseif pose == "thumbToPinky" then if enabled then lock() else unlock() end end end end -- onPeriodic runs every ~10ms function onPeriodic() end -- Only activate when using correct application function onForegroundWindowChange(app, title) enabled = true if string.match(title, "PLACEHOLDER:TITLE") then return true end end
mit
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/EaseExponentialIn.lua
7
1132
-------------------------------- -- @module EaseExponentialIn -- @extend ActionEase -- @parent_module cc -------------------------------- -- brief Create the action with the inner action.<br> -- param action The pointer of the inner action.<br> -- return A pointer of EaseExponentialIn action. If creation failed, return nil. -- @function [parent=#EaseExponentialIn] create -- @param self -- @param #cc.ActionInterval action -- @return EaseExponentialIn#EaseExponentialIn ret (return value: cc.EaseExponentialIn) -------------------------------- -- -- @function [parent=#EaseExponentialIn] clone -- @param self -- @return EaseExponentialIn#EaseExponentialIn ret (return value: cc.EaseExponentialIn) -------------------------------- -- -- @function [parent=#EaseExponentialIn] update -- @param self -- @param #float time -- @return EaseExponentialIn#EaseExponentialIn self (return value: cc.EaseExponentialIn) -------------------------------- -- -- @function [parent=#EaseExponentialIn] reverse -- @param self -- @return ActionEase#ActionEase ret (return value: cc.ActionEase) return nil
mit
ayumus/ayume-ui
your_server/your_character/SavedVariables/NeedToKnow.lua
1
18030
NeedToKnow_Settings = nil NeedToKnow_CharSettings = { ["Locked"] = false, ["Specs"] = { [2] = "G2", }, ["Profiles"] = { ["G2"] = { ["nGroups"] = 4, ["FontSize"] = 12, ["BarTexture"] = "BantoBar", ["bUncompressed"] = true, ["BarSpacing"] = 3, ["BkgdColor"] = { 0, -- [1] 0, -- [2] 0, -- [3] 0.8, -- [4] }, ["Groups"] = { { ["Enabled"] = true, ["NumberBars"] = 3, ["Position"] = { "TOPLEFT", -- [1] "TOPLEFT", -- [2] 100, -- [3] -100, -- [4] }, ["Scale"] = 1, ["Bars"] = { { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [1] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [2] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [3] }, ["FixedDuration"] = 0, ["Width"] = 270, }, -- [1] { ["Enabled"] = false, ["NumberBars"] = 3, ["Position"] = { "TOPLEFT", -- [1] "TOPLEFT", -- [2] 100, -- [3] -200, -- [4] }, ["Scale"] = 1, ["Bars"] = { { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [1] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [2] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [3] }, ["FixedDuration"] = 0, ["Width"] = 270, }, -- [2] { ["Enabled"] = false, ["NumberBars"] = 3, ["Position"] = { "TOPLEFT", -- [1] "TOPLEFT", -- [2] 100, -- [3] -300, -- [4] }, ["Scale"] = 1, ["Bars"] = { { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [1] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [2] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [3] }, ["FixedDuration"] = 0, ["Width"] = 270, }, -- [3] { ["Enabled"] = false, ["NumberBars"] = 3, ["Position"] = { "TOPLEFT", -- [1] "TOPLEFT", -- [2] 100, -- [3] -400, -- [4] }, ["Scale"] = 1, ["Bars"] = { { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [1] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [2] { ["buffcd_duration"] = 0, ["append_usable"] = false, ["AuraName"] = "", ["Unit"] = "player", ["blink_label"] = "", ["OnlyMine"] = true, ["vct_enabled"] = false, ["show_icon"] = false, ["show_count"] = true, ["bDetectExtends"] = false, ["blink_ooc"] = true, ["MissingBlink"] = { ["a"] = 0.5, ["r"] = 0.9, ["g"] = 0.1, ["b"] = 0.1, }, ["usable_duration"] = 0, ["vct_extra"] = 0, ["vct_spell"] = "", ["show_text"] = true, ["show_ttn2"] = false, ["show_time"] = true, ["show_text_user"] = "", ["blink_enabled"] = false, ["append_cd"] = true, ["TimeFormat"] = "Fmt_SingleUnit", ["show_spark"] = true, ["BarColor"] = { ["a"] = 1, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0.6, }, ["show_all_stacks"] = false, ["vct_color"] = { ["a"] = 0.3, ["r"] = 0.6, ["g"] = 0.6, ["b"] = 0, }, ["buffcd_reset_spells"] = "", ["BuffOrDebuff"] = "HELPFUL", ["show_ttn1"] = false, ["show_mypip"] = false, ["show_ttn3"] = false, ["blink_boss"] = false, ["Enabled"] = true, }, -- [3] }, ["FixedDuration"] = 0, ["Width"] = 270, }, -- [4] }, ["BarPadding"] = 3, ["name"] = "Ayume-Tichondrius.2", ["BarFont"] = "Friz Quadrata TT", }, }, }
unlicense
bottelebot/Umbrella
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
pazos/koreader
frontend/apps/cloudstorage/dropbox.lua
2
5612
local BD = require("ui/bidi") local ConfirmBox = require("ui/widget/confirmbox") local DocumentRegistry = require("document/documentregistry") local DropBoxApi = require("apps/cloudstorage/dropboxapi") local InfoMessage = require("ui/widget/infomessage") local MultiInputDialog = require("ui/widget/multiinputdialog") local UIManager = require("ui/uimanager") local ReaderUI = require("apps/reader/readerui") local util = require("util") local Screen = require("device").screen local T = require("ffi/util").template local _ = require("gettext") local DropBox = {} function DropBox:run(url, password, choose_folder_mode) return DropBoxApi:listFolder(url, password, choose_folder_mode) end function DropBox:showFiles(url, password) return DropBoxApi:showFiles(url, password) end function DropBox:downloadFile(item, password, path, close) local code_response = DropBoxApi:downloadFile(item.url, password, path) if code_response == 200 then local __, filename = util.splitFilePathName(path) if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then UIManager:show(InfoMessage:new{ text = T(_("File saved to:\n%1"), BD.filename(path)), }) else UIManager:show(ConfirmBox:new{ text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"), BD.filepath(path)), ok_callback = function() close() ReaderUI:showReader(path) end }) end else UIManager:show(InfoMessage:new{ text = T(_("Could not save file to:\n%1"), BD.filepath(path)), timeout = 3, }) end end function DropBox:downloadFileNoUI(url, password, path) local code_response = DropBoxApi:downloadFile(url, password, path) if code_response == 200 then return true else return false end end function DropBox:config(item, callback) local text_info = "How to generate Access Token:\n".. "1. Open the following URL in your Browser, and log in using your account: https://www.dropbox.com/developers/apps.\n".. "2. Click on >>Create App<<, then select >>Dropbox API app<<.\n".. "3. Now go on with the configuration, choosing the app permissions and access restrictions to your DropBox folder.\n".. "4. Enter the >>App Name<< that you prefer (e.g. KOReader).\n".. "5. Now, click on the >>Create App<< button.\n" .. "6. When your new App is successfully created, please click on the Generate button.\n".. "7. Under the 'Generated access token' section, then enter code in Dropbox token field." local hint_top = _("Your Dropbox name") local text_top = "" local hint_bottom = _("Dropbox token\n\n\n\n") local text_bottom = "" local title local text_button_right = _("Add") if item then title = _("Edit Dropbox account") text_button_right = _("Apply") text_top = item.text text_bottom = item.password else title = _("Add Dropbox account") end self.settings_dialog = MultiInputDialog:new { title = title, fields = { { text = text_top, hint = hint_top , }, { text = text_bottom, hint = hint_bottom, scroll = false, }, }, buttons = { { { text = _("Cancel"), callback = function() self.settings_dialog:onClose() UIManager:close(self.settings_dialog) end }, { text = _("Info"), callback = function() UIManager:show(InfoMessage:new{ text = text_info }) end }, { text = text_button_right, callback = function() local fields = MultiInputDialog:getFields() if fields[1] ~= "" and fields[2] ~= "" then if item then --edit callback(item, fields) else -- add new callback(fields) end self.settings_dialog:onClose() UIManager:close(self.settings_dialog) else UIManager:show(InfoMessage:new{ text = _("Please fill in all fields.") }) end end }, }, }, width = math.floor(Screen:getWidth() * 0.95), height = math.floor(Screen:getHeight() * 0.2), input_type = "text", } UIManager:show(self.settings_dialog) self.settings_dialog:onShowKeyboard() end function DropBox:info(token) local info = DropBoxApi:fetchInfo(token) local info_text if info and info.name then info_text = T(_"Type: %1\nName: %2\nEmail: %3\nCountry: %4", "Dropbox",info.name.display_name, info.email, info.country) else info_text = _("No information available") end UIManager:show(InfoMessage:new{text = info_text}) end return DropBox
agpl-3.0
joaofvieira/luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
47
3692
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
mys007/cudnn.torch
functional.lua
2
1403
-- this file attempts to provide a purely functional set of bindings -- all functions in this file retain absolutely no state. -- There shouldn't be any reference to "self" in this file. local cudnn = require 'cudnn.env' local errcheck = cudnn.errcheck cudnn.functional = {} local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); -- accumulates the bias into output. -- output is assumed to be allocated and given. cudnn.functional.SpatialBias_updateOutput = function(bias, output) local biasDesc = cudnn.toDescriptor(bias:view(1, bias:nElement(),1,1)) local oDesc = cudnn.toDescriptor(output) errcheck('cudnnAddTensor', cudnn.getHandle(), 'CUDNN_ADD_SAME_C', one:data(), biasDesc[0], bias:data(), one:data(), oDesc[0], output:data()) end -- accumulates the gradients into gradBias. -- gradBias is assumed to be allocated and given. cudnn.functional.SpatialBias_accGradParameters = function(gradOutput, gradBias, scale) scale = scale or 1.0 local scaleT = torch.FloatTensor({scale}) local oDesc = cudnn.toDescriptor(gradOutput) local biasDesc = cudnn.toDescriptor(gradBias:view(1, gradBias:nElement(),1,1)) errcheck('cudnnConvolutionBackwardBias', cudnn.getHandle(), scaleT:data(), oDesc[0], gradOutput:data(), one:data(), biasDesc[0], gradBias:data()) end
bsd-2-clause
joaofvieira/luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
68
7091
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ip = require "luci.ip" local fs = require "nixio.fs" if arg[1] then mp = Map("olsrd", translate("OLSR - Plugins")) p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration")) p:depends("library", arg[1]) p.anonymous = true ign = p:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end lib = p:option(DummyValue, "library", translate("Library")) lib.default = arg[1] local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")() local cidr if ip and mask and ip:match(":") then cidr = ip.IPv6(ip, mask) elseif ip and mask then cidr = ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "br-lan" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" }, { Value, "services_file", "/var/run/services_olsr" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }, { DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" }, { Value, "macs_file", "/path/to/macs_file" }, { Value, "macs_change_script", "/path/to/script" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "127.0.0.1" } }, ["olsrd_jsoninfo.so.0.0"] = { { Value, "accept", "127.0.0.1" }, { Value, "port", "9090" }, { Value, "UUIDFile", "/etc/olsrd/olsrd.uuid" }, }, ["olsrd_watchdog.so.0.1"] = { { Value, "file", "/var/run/olsrd.watchdog" }, { Value, "interval", "30" } }, ["olsrd_mdns.so.1.0.0"] = { { DynamicList, "NonOlsrIf", "lan" } }, ["olsrd_p2pd.so.0.1.0"] = { { DynamicList, "NonOlsrIf", "lan" }, { Value, "P2pdTtl", "10" } }, ["olsrd_arprefresh.so.0.1"] = {}, ["olsrd_dot_draw.so.0.3"] = {}, ["olsrd_dyn_gw_plain.so.0.4"] = {}, ["olsrd_pgraph.so.1.1"] = {}, ["olsrd_tas.so.0.1"] = {} } -- build plugin options with dependencies if knownPlParams[arg[1]] then for _, option in ipairs(knownPlParams[arg[1]]) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end field.optional = true field.default = default --field:depends({ library = arg[1] }) end end end return mp else mpi = Map("olsrd", translate("OLSR - Plugins")) local plugins = {} mpi.uci:foreach("olsrd", "LoadPlugin", function(section) if section.library and not plugins[section.library] then plugins[section.library] = true end end ) -- create a loadplugin section for each found plugin for v in fs.dir("/usr/lib") do if v:sub(1, 6) == "olsrd_" then if not plugins[v] then mpi.uci:section( "olsrd", "LoadPlugin", nil, { library = v, ignore = 1 } ) end end end t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") ) t.anonymous = true t.template = "cbi/tblsection" t.override_scheme = true function t.extedit(self, section) local lib = self.map:get(section, "library") or "" return luci.dispatcher.build_url("admin", "services", "olsrd", "plugins") .. "/" .. lib end ign = t:option( Flag, "ignore", translate("Enabled") ) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end t:option( DummyValue, "library", translate("Library") ) return mpi end
apache-2.0
REZATITAN/X
plugins/stats.lua
236
3989
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
dangersuperbot/super_boomrange
plugins/remind.lua
4
1709
local filename='data/remind.lua' local cronned = load_from_file(filename) local function save_cron(msg, text,date) local origin = get_receiver(msg) if not cronned[date] then cronned[date] = {} end local arr = { origin, text } ; table.insert(cronned[date], arr) serialize_to_file(cronned, filename) return end local function delete_cron(date) for k,v in pairs(cronned) do if k == date then cronned[k]=nil end end serialize_to_file(cronned, filename) end local function cron() for date, values in pairs(cronned) do if date < os.time() then --time's up send_msg(values[1][1], "️❗یادآوری:\n"..values[1][2], ok_cb, false) delete_cron(date) --TODO: Maybe check for something else? Like user end end end local function actually_run(msg, delay,text) save_cron(msg, text,delay) return "❗️ من در تاریخ " .. os.date("%x درزمان %H:%M",delay+16200) .. "به شما درباره:\n"..text.."\nیاد آوری میکنم\nتاریخ کنونی:" .. os.date("%x زمان کنونی: %H:%M:%S",os.time() + 16200) end local function run(msg, matches) if not matches[1] or not matches[2] then return lang_text(msg.to.id, 'seefcmds') end local sum = 0 local b,_ = string.gsub(matches[1],"[a-zA-Z]","") if string.find(matches[1], "m") then sum=sum+b*60 end if string.find(matches[1], "h") then sum=sum+b*3600 end local date=sum+os.time() local text = matches[2] local text = actually_run(msg, date, text) return text end return { description = "remind plugin", usage = { "!remind 2h0m text" }, patterns = { "^[!/#]remind ([0-9]+[hmHM]) (.+)$", }, run = run, cron = cron }
gpl-2.0
pazos/koreader
frontend/persist.lua
2
3600
local bitser = require("ffi/bitser") local dump = require("dump") local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local function readFile(file, bytes) local f, str, err f, err = io.open(file, "rb") if not f then return nil, err end str, err = f:read(bytes or "*a") f:close() if not str then return nil, err end return str end local codecs = { -- bitser: binary form, fast encode/decode, low size. Not human readable. bitser = { id = "bitser", reads_from_file = false, serialize = function(t) local ok, str = pcall(bitser.dumps, t) if not ok then return nil, "cannot serialize " .. tostring(t) end return str end, deserialize = function(str) local ok, t = pcall(bitser.loads, str) if not ok then return nil, "malformed serialized data" end return t end, }, -- dump: human readable, pretty printed, fast enough for most user cases. dump = { id = "dump", reads_from_file = true, serialize = function(t, as_bytecode) local content if as_bytecode then local bytecode, err = load("return " .. dump(t)) if not bytecode then logger.warn("cannot convert table to bytecode", err, "fallback to text") else content = string.dump(bytecode, true) end end if not content then content = "return " .. dump(t) end return content end, deserialize = function(str) local t, err = loadfile(str) if not t then t, err = loadstring(str) end if not t then return nil, err end return t() end, } } local Persist = {} function Persist:new(o) o = o or {} assert(type(o.path) == "string", "path is required") o.codec = o.codec or "dump" setmetatable(o, self) self.__index = self return o end function Persist:exists() local mode = lfs.attributes(self.path, "mode") if mode then return mode == "file" end end function Persist:timestamp() return lfs.attributes(self.path, "modification") end function Persist:size() return lfs.attributes(self.path, "size") end function Persist:load() local t, err if codecs[self.codec].reads_from_file then t, err = codecs[self.codec].deserialize(self.path) else local str str, err = readFile(self.path) if not str then return nil, err end t, err = codecs[self.codec].deserialize(str) end if not t then return nil, err end return t end function Persist:save(t, as_bytecode) local str, file, err str, err = codecs[self.codec].serialize(t, as_bytecode) if not str then return nil, err end file, err = io.open(self.path, "wb") if not file then return nil, err end file:write(str) file:close() return true end function Persist:delete() if not self:exists() then return end return os.remove(self.path) end function Persist.getCodec(name) local fallback = codecs["dump"] for key, codec in pairs(codecs) do if type(key) == "string" and key == name then return codec end end return fallback end return Persist
agpl-3.0
rigeirani/satn
plugins/linkpv.lua
66
30275
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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 bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] 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.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules 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 is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') 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..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) 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 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, 'Group link for ('..string.gsub(msg.to.print_name, "_", " ")..'):\n'..group_link) end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 50 then return "Wrong number,range is [2-50]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { usage = { "linkpv: Send Link In Private Chat.", }, patterns = { "^([Ll]inkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
JustinNiu/MUSI89903-Assignment2
3rdparty/sndlib/premake4.lua
16
3961
-- sndlib premake4 -- requires premake-4.4 (for os.is64bit) -- currently assumes you want s7 (scheme) as the extension language -------------------------------------------------------------------------------- -- Command Line -------------------------------------------------------------------------------- newoption({trigger = "with-g++", description = "Optionally use g++ compiler."}) if (not _ACTION) then if (os.is("windows")) then _ACTION = "vs2010" else _ACTION = "gmake" end end -------------------------------------------------------------------------------- -- Global Config -------------------------------------------------------------------------------- --General DebugFlags = {"Symbols", "NoPCH", "NoManifest"} ReleaseFlags = {"NoPCH", "NoManifest"} SpeedFlags = {"OptimizeSpeed", "NoPCH", "NoManifest"} --Warnings StandardGCCWarnings = {"-Wall"} --Mac MacFrameworks = {"-framework CoreAudio", "-framework CoreFoundation", "-framework CoreMidi"} MacTarget = "-mmacosx-version-min=10.6" -------------------------------------------------------------------------------- -- Paths -------------------------------------------------------------------------------- PathToRoot = "" PathToSrc = "./" PathToLib = "lib/" -- folder to save libs in PathToBin = "bin/" -- folder to save apps in PathToObj = "obj/" -- intermediate dir for object files -------------------------------------------------------------------------------- -- -------------------------------------------------------------------------------- solution("sndlib") --Create a release, debug, and speed configuration for each project. configurations({"Release", "Debug", "Speed"}) -------------------------------------------------------------------------------- -- project sndlib: create static libsndlib -------------------------------------------------------------------------------- project("sndlib") -- optionally use g++ compiler for .c files if (_OPTIONS["with-g++"]) then language("C++") -- buildoptions( {"-x c++"}) -- for clang on osx? else language("C") end if (_OPTIONS["with-gsl"]) then defines("HAVE_GSL") links({"gsl", "gslcblas"}) end defines("WITH_AUDIO") defines("HAVE_SCHEME") defines("HAVE_PREMAKE") if (os.get() == "macosx") then -- links({"dl"}) linkoptions(MacFrameworks) else if (os.get() == "windows") then links("winmm") else if (os.get() == "linux") then defines("HAVE_ALSA") else -- I tried FreeBSD (had to remove -ldl from LIBS in gmake.unix), but -- premake died with some lua error. end end end if (os.is64bit()) then defines("SIZEOF_VOID_P=8") else defines("SIZEOF_VOID_P=4") end -- TODO: WORDS_BIGENDIAN: -- I got this from some Lua mailing list -- I have no idea what it does! -- apparently it returns true if little-endian -- -- function endian() -- return string.byte(string.dump(function() end),7) -- end -- -- if (!endian()) then -- defines("WORDS_BIGENDIAN") -- end -- until I have a test case, I think I'll leave it little-endian by default -- it's not clear that Lua works in big-endian machines kind("StaticLib") flags({"StaticRuntime"}) includedirs({PathToSrc}) objdir(PathToObj) targetdir(PathToLib) files({"headers.*", "audio.*", "io.*", "sound.*", "xen.*", "vct.*", "clm.*", "sndlib2xen.*", "clm2xen.*", "s7.*"}) defines({"HAVE_CONFIG_H=1"}) -- ADD WHATEVER OTHER PROJECTS YOU WANT, EG: -- project("s7") -- kind("ConsoleApp") -- ... configuration "Debug" flags(DebugFlags) defines("DEBUG") configuration "Release" flags(ReleaseFlags) defines({"NDEBUG", "_NDEBUG"}) configuration "Speed" flags(SpeedFlags) defines({"NDEBUG", "_NDEBUG"}) -- to find a library os.findlib("X11"), nil if not found -- os.execute to run external prog -- os.isfile("path") true if file exists, else false -- os.outputof("command")
mit
soumith/nn
SpatialLPPooling.lua
2
1027
local SpatialLPPooling, parent = torch.class('nn.SpatialLPPooling', 'nn.Sequential') function SpatialLPPooling:__init(nInputPlane, pnorm, kW, kH, dW, dH) parent.__init(self) dW = dW or kW dH = dH or kH self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.nInputPlane = nInputPlane if pnorm == 2 then self:add(nn.Square()) else self:add(nn.Power(pnorm)) end self:add(nn.SpatialSubSampling(nInputPlane, kW, kH, dW, dH)) if pnorm == 2 then self:add(nn.Sqrt()) else self:add(nn.Power(1/pnorm)) end self:get(2).bias:zero() self:get(2).weight:fill(1) end -- the module is a Sequential: by default, it'll try to learn the parameters -- of the sub sampler: we avoid that by redefining its methods. function SpatialLPPooling:reset() end function SpatialLPPooling:accGradParameters() end function SpatialLPPooling:accUpdateGradParameters() end function SpatialLPPooling:zeroGradParameters() end function SpatialLPPooling:updateParameters() end
bsd-3-clause
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/includes/modules/killicon.lua
2
2591
-- DO NOT EDIT THIS FILE! -- Globals that we need local surface = surface local Msg = Msg local Color = Color --[[--------------------------------------------------------- Name: killicon Desc: Stores and serves killicons for deathnotice -----------------------------------------------------------]] module("killicon") local Icons = {} local TYPE_FONT = 0 local TYPE_TEXTURE = 1 function AddFont( name, font, character, color ) Icons[name] = {} Icons[name].type = TYPE_FONT Icons[name].font = font Icons[name].character = character Icons[name].color = color end function Add( name, material, color ) Icons[name] = {} Icons[name].type = TYPE_TEXTURE Icons[name].texture = surface.GetTextureID( material ) Icons[name].color = color end function AddAlias( name, alias ) Icons[name] = Icons[alias] end function Exists( name ) return Icons[name] != nil end function GetSize( name ) if (!Icons[name]) then Msg("Warning: killicon not found '"..name.."'\n") Icons[name] = Icons["default"] end local t = Icons[name] -- Cached if (t.size) then return t.size.w, t.size.h end local w, h = 0 if ( t.type == TYPE_FONT ) then surface.SetFont( t.font ) w, h = surface.GetTextSize( t.character ) end if ( t.type == TYPE_TEXTURE ) then -- Estimate the size from the size of the font surface.SetFont( "HL2MPTypeDeath" ) w, h = surface.GetTextSize( "0" ) -- Fudge it slightly h = h * 0.75 -- Make h/w 1:1 local tw, th = surface.GetTextureSize( t.texture ) w = tw * (h / th) end t.size = {} t.size.w = w or 32 t.size.h = h or 32 return w, h end function Draw( x, y, name, alpha ) alpha = alpha or 255 if (!Icons[name]) then Msg("Warning: killicon not found '"..name.."'\n") Icons[name] = Icons["default"] end local t = Icons[name] if ( !t.size ) then GetSize( name ) end local w = t.size.w local h = t.size.h x = x - w * 0.5 if ( t.type == TYPE_FONT ) then y = y - h * 0.1 surface.SetTextPos( x, y ) surface.SetFont( t.font ) surface.SetTextColor( t.color.r, t.color.g, t.color.b, alpha ) surface.DrawText( t.character ) end if ( t.type == TYPE_TEXTURE ) then y = y - h * 0.3 surface.SetTexture( t.texture ) surface.SetDrawColor( t.color.r, t.color.g, t.color.b, alpha ) surface.DrawTexturedRect( x, y, w, h ) end end --AddFont( "default", "HL2MPTypeDeath", "6", Color( 255, 240, 10, 255 ) ) local Color_Icon = Color( 255, 80, 0, 255 ) Add( "default", "HUD/killicons/default", Color_Icon ) AddAlias( "suicide", "default" )
mit
anonymous12212020/sbss
plugins/welcome.lua
35
3625
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nدرباره گروه :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nقوانین گروه :\n"..rules.."\n" end local sambutan = "سلام "..nama.."\nبه گروه '"..string.gsub(msg.to.print_name, "_", " ").."'\nخوش اومدی \n برای دیدن دستورات ربات راهنما رو ارسال کن\n" local text = sambutan..about..rules.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Bye '..bye_name end end return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
rboman/progs
sandbox/lua/point.lua
1
1503
-- Example of point class made after reading a lua tutorial -- point class local Pt = { } Pt.x = 0 Pt.y = 0 -- constructor Pt.new = function (self, object) object = object or {} -- Use provided table, or create new one setmetatable(object, self) -- Assign meta table self.__index = self -- return Pt values missing in "object" return object end -- add 2 points Pt.__add = function(self, p) return Pt:new({x=self.x+p.x, y=self.y+p.y}) end -- substract 2 points Pt.__sub = function(self, p) return Pt:new({x=self.x-p.x, y=self.y-p.y}) end -- scalar multiplication or scalar product if both args are points Pt.__mul = function(self, p) -- print('type(self) = '..type(self)) -- print('type(p) = '..type(p)) if type(self)=='number' then return Pt:new({x=self*p.x, y=self*p.y}) elseif type(p)=='number' then return Pt:new({x=self.x*p, y=self.y*p}) else return self.x*p.x + self.y*p.y end end -- scalar division Pt.__div = function(self, p) return Pt:new({x=self.x/p, y=self.y/p}) end -- convert to string Pt.__tostring = function(self) return '('..self.x..', '..self.y..')' end -- cross product Pt.cross = function(self, p) return self.x*p.y-self.y*p.x end -- norm/length Pt.norm = function(self) return math.sqrt(self.x*self.x+self.y*self.y) end -- normalized Pt.normalized = function(self) local n = self:norm() assert(n~=0,"vector norm is 0!") return self/n end return Pt -- returns the table
apache-2.0
joaofvieira/luci
applications/luci-app-ddns/luasrc/controller/ddns.lua
29
7451
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2013 Manuel Munz <freifunk at somakoma dot de> -- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed to the public under the Apache License 2.0. module("luci.controller.ddns", package.seeall) local NX = require "nixio" local NXFS = require "nixio.fs" local DISP = require "luci.dispatcher" local HTTP = require "luci.http" local UCI = require "luci.model.uci" local SYS = require "luci.sys" local DDNS = require "luci.tools.ddns" -- ddns multiused functions local UTIL = require "luci.util" DDNS_MIN = "2.4.2-1" -- minimum version of service required function index() local nxfs = require "nixio.fs" -- global definitions not available local sys = require "luci.sys" -- in function index() local ddns = require "luci.tools.ddns" -- ddns multiused functions local verinst = ddns.ipkg_ver_installed("ddns-scripts") local verok = ddns.ipkg_ver_compare(verinst, ">=", "2.0.0-0") -- do NOT start it not ddns-scripts version 2.x if not verok then return end -- no config create an empty one if not nxfs.access("/etc/config/ddns") then nxfs.writefile("/etc/config/ddns", "") end entry( {"admin", "services", "ddns"}, cbi("ddns/overview"), _("Dynamic DNS"), 59) entry( {"admin", "services", "ddns", "detail"}, cbi("ddns/detail"), nil ).leaf = true entry( {"admin", "services", "ddns", "hints"}, cbi("ddns/hints", {hideapplybtn=true, hidesavebtn=true, hideresetbtn=true}), nil ).leaf = true entry( {"admin", "services", "ddns", "global"}, cbi("ddns/global"), nil ).leaf = true entry( {"admin", "services", "ddns", "logview"}, call("logread") ).leaf = true entry( {"admin", "services", "ddns", "startstop"}, call("startstop") ).leaf = true entry( {"admin", "services", "ddns", "status"}, call("status") ).leaf = true end -- function to read all sections status and return data array local function _get_status() local uci = UCI.cursor() local service = SYS.init.enabled("ddns") and 1 or 0 local url_start = DISP.build_url("admin", "system", "startup") local data = {} -- Array to transfer data to javascript data[#data+1] = { enabled = service, -- service enabled url_up = url_start, -- link to enable DDS (System-Startup) } uci:foreach("ddns", "service", function (s) -- Get section we are looking at -- and enabled state local section = s[".name"] local enabled = tonumber(s["enabled"]) or 0 local datelast = "_empty_" -- formatted date of last update local datenext = "_empty_" -- formatted date of next update -- get force seconds local force_seconds = DDNS.calc_seconds( tonumber(s["force_interval"]) or 72 , s["force_unit"] or "hours" ) -- get/validate pid and last update local pid = DDNS.get_pid(section) local uptime = SYS.uptime() local lasttime = DDNS.get_lastupd(section) if lasttime > uptime then -- /var might not be linked to /tmp lasttime = 0 -- and/or not cleared on reboot end -- no last update happen if lasttime == 0 then datelast = "_never_" -- we read last update else -- calc last update -- sys.epoch - sys uptime + lastupdate(uptime) local epoch = os.time() - uptime + lasttime -- use linux date to convert epoch datelast = DDNS.epoch2date(epoch) -- calc and fill next update datenext = DDNS.epoch2date(epoch + force_seconds) end -- process running but update needs to happen -- problems if force_seconds > uptime force_seconds = (force_seconds > uptime) and uptime or force_seconds if pid > 0 and ( lasttime + force_seconds - uptime ) <= 0 then datenext = "_verify_" -- run once elseif force_seconds == 0 then datenext = "_runonce_" -- no process running and NOT enabled elseif pid == 0 and enabled == 0 then datenext = "_disabled_" -- no process running and enabled elseif pid == 0 and enabled ~= 0 then datenext = "_stopped_" end -- get/set monitored interface and IP version local iface = s["interface"] or "_nonet_" local use_ipv6 = tonumber(s["use_ipv6"]) or 0 if iface ~= "_nonet_" then local ipv = (use_ipv6 == 1) and "IPv6" or "IPv4" iface = ipv .. " / " .. iface end -- try to get registered IP local domain = s["domain"] or "_nodomain_" local dnsserver = s["dns_server"] or "" local force_ipversion = tonumber(s["force_ipversion"] or 0) local force_dnstcp = tonumber(s["force_dnstcp"] or 0) local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh]] command = command .. [[ get_registered_ip ]] .. domain .. [[ ]] .. use_ipv6 .. [[ ]] .. force_ipversion .. [[ ]] .. force_dnstcp .. [[ ]] .. dnsserver local reg_ip = SYS.exec(command) if reg_ip == "" then reg_ip = "_nodata_" end -- fill transfer array data[#data+1] = { section = section, enabled = enabled, iface = iface, domain = domain, reg_ip = reg_ip, pid = pid, datelast = datelast, datenext = datenext } end) uci:unload("ddns") return data end -- called by XHR.get from detail_logview.htm function logread(section) -- read application settings local uci = UCI.cursor() local log_dir = uci:get("ddns", "global", "log_dir") or "/var/log/ddns" local lfile = log_dir .. "/" .. section .. ".log" local ldata = NXFS.readfile(lfile) if not ldata or #ldata == 0 then ldata="_nodata_" end uci:unload("ddns") HTTP.write(ldata) end -- called by XHR.get from overview_status.htm function startstop(section, enabled) local uci = UCI.cursor() local pid = DDNS.get_pid(section) local data = {} -- Array to transfer data to javascript -- if process running we want to stop and return if pid > 0 then local tmp = NX.kill(pid, 15) -- terminate NX.nanosleep(2) -- 2 second "show time" -- status changed so return full status data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) return end -- read uncommitted changes -- we don't save and commit data from other section or other options -- only enabled will be done local exec = true local changed = uci:changes("ddns") for k_config, v_section in pairs(changed) do -- security check because uci.changes only gets our config if k_config ~= "ddns" then exec = false break end for k_section, v_option in pairs(v_section) do -- check if only section of button was changed if k_section ~= section then exec = false break end for k_option, v_value in pairs(v_option) do -- check if only enabled was changed if k_option ~= "enabled" then exec = false break end end end end -- we can not execute because other -- uncommitted changes pending, so exit here if not exec then HTTP.write("_uncommitted_") return end -- save enable state uci:set("ddns", section, "enabled", ( (enabled == "true") and "1" or "0") ) uci:save("ddns") uci:commit("ddns") uci:unload("ddns") -- start dynamic_dns_updater.sh script os.execute ([[/usr/lib/ddns/dynamic_dns_updater.sh %s 0 > /dev/null 2>&1 &]] % section) NX.nanosleep(3) -- 3 seconds "show time" -- status changed so return full status data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) end -- called by XHR.poll from overview_status.htm function status() local data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) end
apache-2.0
drmingdrmer/lua-paxos
lib/acid/paxoshelper.lua
2
4861
local _M = { _VERSION = require("acid.paxos._ver") } local tableutil = require( "acid.tableutil" ) local base = require( "acid.paxos.base" ) local errors = base.errors local nr_retry = 5 function _M.get_or_elect_leader(paxos, lease) local rst, err, errmes = paxos:local_get( 'leader' ) if err then paxos:logerr( {err=err, errmes=errmes}, "while local_get('leader'):", paxos.member_id) return nil, err, errmes end -- start to track version change. if version changed, -- paxos stops any write operation. paxos.ver = rst.ver if rst.val ~= nil then return rst, nil, nil end paxos:logerr( rst, "leader not found for:", paxos.member_id) return _M.elect_leader( paxos, lease ) end function _M.elect_leader(paxos, lease) return paxos:set( 'leader', { ident = paxos.member_id.ident, __lease = lease, }) end function _M.change_view(paxos, changes) -- changes = { -- add = { a=1, b=1 }, -- del = { c=1, d=1 }, -- merge = { f1={ f2={} } }, -- } -- change_view push cluster to a consistent state: -- . changes applied to cluster -- . other process is in progress changing view, apply it and return -- error DuringChange -- . no change. do nothing and return error -- . paxos race condition. update it -- after this step completed, it is required to track version changing to -- make sure no other change_view to break this procedure. for _ = 1, nr_retry do local c, err, errmes = _M._change_view( paxos, changes ) if err == errors.QuorumFailure then _M._sleep(paxos) paxos:sync() else return c, err, errmes end end return nil, errors.QuorumFailure end function _M._change_view(paxos, changes) local c, err, errmes = paxos:read() if err then return nil, err, errmes end _M._merge_changes( c.val, changes.merge or {} ) local cval = c.val local view, err, errmes = _M._make_2group_view(cval.view, changes ) if err then if err == errors.DuringChange then paxos:sync() if #cval.view == 2 then table.remove( cval.view, 1 ) _M._set_change_view( paxos, c ) end elseif err == errors.NoChange then return c, nil, nil end return nil, err, errmes end cval.view = view local _, err, errmes = _M._set_change_view( paxos, c ) if err then return nil, err, errmes end -- After update to dual-group view, commit once more with the new view to -- create new member. local _, err, errmes = paxos:sync() if err then return nil, err, errmes end table.remove( cval.view, 1 ) return _M._set_change_view( paxos, c ) end function _M._set_change_view( paxos, c ) local _c, err, errmes = paxos:read() if err then return nil, err, errmes end if tableutil.eq( c.val, _c.val ) then local p, err, errmes = paxos:new_proposer() if err then return nil, err, errmes end local c, err, errmes = p:commit_specific(_c) if err then return nil, err, errmes end return c, nil, nil end local c, err, errmes = paxos:write(c.val) if err then return nil, err, errmes end return c, nil, nil end function _M.with_cluster_locked(paxos, f, exptime) local cluster_id = paxos.member_id.cluster_id local _mid = { cluster_id= cluster_id, ident='__admin', } local _l, err = paxos.impl:lock(_mid, exptime) if err then return nil, errors.LockTimeout, err end local rst, err, errmes = f() paxos.impl:unlock(_l) return rst, err, errmes end function _M._make_2group_view(view, changes) -- Create intermedia view. -- Intermedia view of val contains 2 groups: the current group and the -- group to change to. local view = tableutil.dup( view, true ) if view[ 2 ] ~= nil then return nil, errors.DuringChange end view[ 2 ] = tableutil.dup( view[ 1 ], true ) tableutil.merge( view[ 2 ], changes.add or {} ) for k, v in pairs(changes.del or {}) do view[ 2 ][ k ] = nil end if tableutil.eq( view[1], view[2] ) then return nil, errors.NoChange end return view, nil, nil end -- merge cannot be nested loop table function _M._merge_changes(c, merge) for k, v in pairs(merge) do if type(v) == 'table' and type(c[k]) == 'table' then _M._merge_changes( c[k], v ) else c[ k ] = v end end return c end function _M._sleep(paxos) if paxos.impl.sleep then paxos.impl:sleep() end end return _M
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/eyeposer.lua
1
3978
TOOL.Category = "Poser" TOOL.Name = "#tool.eyeposer.name" TOOL.Command = nil TOOL.ConfigName = nil local function ConvertRelativeToEyesAttachment( Entity, Pos ) if ( Entity:IsNPC() ) then return Pos end -- Convert relative to eye attachment local eyeattachment = Entity:LookupAttachment( "eyes" ) if ( eyeattachment == 0 ) then return end local attachment = Entity:GetAttachment( eyeattachment ) if ( !attachment ) then return end local LocalPos, LocalAng = WorldToLocal( Pos, Angle(0,0,0), attachment.Pos, attachment.Ang ) return LocalPos end --[[--------------------------------------------------------- Selects entity and aims their eyes -----------------------------------------------------------]] function TOOL:LeftClick( trace ) if (self.SelectedEntity == nil) then if ( !IsValid( trace.Entity ) ) then return end self.SelectedEntity = trace.Entity self:GetWeapon():SetNetworkedEntity( 0, self.SelectedEntity ) return end local selectedent = self.SelectedEntity self.SelectedEntity = nil self:GetWeapon():SetNetworkedEntity( 0, NULL ) if (!selectedent:IsValid()) then return end local LocalPos = ConvertRelativeToEyesAttachment( selectedent, trace.HitPos ) if (!LocalPos) then return false end selectedent:SetEyeTarget( LocalPos ) end --[[--------------------------------------------------------- Makes the eyes look at the player -----------------------------------------------------------]] function TOOL:RightClick( trace ) self:GetWeapon():SetNetworkedEntity( 0, NULL ) self.SelectedEntity = nil if ( !IsValid( trace.Entity ) ) then return end if ( CLIENT ) then return true end local pos = self:GetOwner():EyePos() local LocalPos = ConvertRelativeToEyesAttachment( trace.Entity, pos ) if (!LocalPos) then return false end trace.Entity:SetEyeTarget( LocalPos ) end if ( CLIENT ) then --[[--------------------------------------------------------- Draw a box indicating the face we have selected -----------------------------------------------------------]] function TOOL:DrawHUD() local selected = self:GetWeapon():GetNetworkedEntity( 0 ) if ( !IsValid( selected ) ) then return end local vEyePos = selected:EyePos() local eyeattachment = selected:LookupAttachment( "eyes" ) if (eyeattachment == 0) then return end local attachment = selected:GetAttachment( eyeattachment ) local scrpos = attachment.Pos:ToScreen() if (!scrpos.visible) then return end -- Try to get each eye position.. this is a real guess and won't work on non-humans local Leye = (attachment.Pos + attachment.Ang:Right() * 1.5):ToScreen() local Reye = (attachment.Pos - attachment.Ang:Right() * 1.5):ToScreen() -- Work out the side distance to give a rough headsize box.. local player_eyes = LocalPlayer():EyeAngles() local side = (attachment.Pos + player_eyes:Right() * 10):ToScreen() local size = 4 local Owner = self:GetOwner() -- Get Target local tr = util.GetPlayerTrace( Owner ) local trace = util.TraceLine( tr ) local scrhit = trace.HitPos:ToScreen() local x = scrhit.x local y = scrhit.y local LocalPos = ConvertRelativeToEyesAttachment( selected, trace.HitPos ) selected:SetEyeTarget( LocalPos ) -- Todo, make look less like ass surface.SetDrawColor( 0, 0, 0, 100 ) surface.DrawLine( Leye.x-1, Leye.y+1, x-1, y+1 ) surface.DrawLine( Leye.x-1, Leye.y-1, x-1, y-1 ) surface.DrawLine( Leye.x+1, Leye.y+1, x+1, y+1 ) surface.DrawLine( Leye.x+1, Leye.y-1, x+1, y-1 ) surface.DrawLine( Reye.x-1, Reye.y+1, x-1, y+1 ) surface.DrawLine( Reye.x-1, Reye.y-1, x-1, y-1 ) surface.DrawLine( Reye.x+1, Reye.y+1, x+1, y+1 ) surface.DrawLine( Reye.x+1, Reye.y-1, x+1, y-1 ) surface.SetDrawColor( 0, 255, 0, 255 ) surface.DrawLine( Leye.x, Leye.y, x, y ) surface.DrawLine( Reye.x, Reye.y, x, y ) surface.DrawLine( Leye.x, Leye.y-1, x, y-1 ) surface.DrawLine( Reye.x, Reye.y-1, x, y-1 ) end end
mit
Samake/Minecraft
Minecraft/client/handler/ModelHandlerC.lua
1
3878
--[[ Name: Minecraft Filename: ModelHandlerC.lua Authors: Sam@ke --]] ModelHandlerC = {} function ModelHandlerC:constructor(parent) mainOutput("ModelHandlerC was loaded.") self.mainClass = parent self.lodDistance = 300 self.texturePack = engineLoadTXD("res/models/minecraft.txd") self.blockCol = engineLoadCOL("res/models/blockCol.col") self.doorCol = engineLoadCOL("res/models/doorCol.col") -- // terrain // -- self.terrainID = 15049 self.terrainModel = engineLoadDFF("res/models/terrainPlane.dff") self.terrainCol = engineLoadCOL("res/models/terrainCol.col") engineImportTXD(self.texturePack, self.terrainID) engineReplaceModel(self.terrainModel, self.terrainID) engineReplaceCOL(self.terrainCol, self.terrainID) -- // blocks // -- -- ids 1851 - 1882 self.blockStoneID = 1851 self.blockStoneModel = engineLoadDFF("res/models/stoneBlock.dff") engineImportTXD(self.texturePack, self.blockStoneID) engineReplaceModel(self.blockStoneModel, self.blockStoneID) engineReplaceCOL(self.blockCol, self.blockStoneID) self.blockDirtID = 1852 self.blockDirtModel = engineLoadDFF("res/models/dirtBlock.dff") engineImportTXD(self.texturePack, self.blockDirtID) engineReplaceModel(self.blockDirtModel, self.blockDirtID) engineReplaceCOL(self.blockCol, self.blockDirtID) self.blockGrassID = 1853 self.blockGrassModel = engineLoadDFF("res/models/grassBlock.dff") engineImportTXD(self.texturePack, self.blockGrassID) engineReplaceModel(self.blockGrassModel, self.blockGrassID) engineReplaceCOL(self.blockCol, self.blockGrassID) self.grassPlantID = 1854 self.grassPlantModel = engineLoadDFF("res/models/grassPlant.dff") engineImportTXD(self.texturePack, self.grassPlantID) engineReplaceModel(self.grassPlantModel, self.grassPlantID) self.blockSandID = 1855 self.blockSandModel = engineLoadDFF("res/models/sandBlock.dff") engineImportTXD(self.texturePack, self.blockSandID) engineReplaceModel(self.blockSandModel, self.blockSandID) engineReplaceCOL(self.blockCol, self.blockSandID) self.blockGlassWhiteID = 1856 self.blockGlassWhiteModel = engineLoadDFF("res/models/glassWhiteBlock.dff", self.blockGlassWhiteID) engineImportTXD(self.texturePack, self.blockGlassWhiteID) engineReplaceModel(self.blockGlassWhiteModel, self.blockGlassWhiteID) engineReplaceCOL(self.blockCol, self.blockGlassWhiteID) self.sapplingOakID = 1857 self.sapplingOakModel = engineLoadDFF("res/models/sapplingOak.dff") engineImportTXD(self.texturePack, self.sapplingOakID) engineReplaceModel(self.sapplingOakModel, self.sapplingOakID) self.blockWoodOAKID = 1858 self.blockWoodOAKModel = engineLoadDFF("res/models/woodBlockOAK.dff") engineImportTXD(self.texturePack, self.blockWoodOAKID) engineReplaceModel(self.blockWoodOAKModel, self.blockWoodOAKID) engineReplaceCOL(self.blockCol, self.blockWoodOAKID) self.blockLeavesOAKID = 1859 self.blockLeavesOAKModel = engineLoadDFF("res/models/leavesBlockOAK.dff") engineImportTXD(self.texturePack, self.blockLeavesOAKID) engineReplaceModel(self.blockLeavesOAKModel, self.blockLeavesOAKID) engineReplaceCOL(self.blockCol, self.blockLeavesOAKID) -- // doors // -- -- ids 1830 - 1838 self.doorWoodID = 1830 self.doorWoodModel = engineLoadDFF("res/models/doorWood.dff", self.doorWoodID) engineImportTXD(self.texturePack, self.doorWoodID) engineReplaceModel(self.doorWoodModel, self.doorWoodID) engineReplaceCOL(self.doorCol, self.doorWoodID) self:setLodDistance() end function ModelHandlerC:setLodDistance() for index, object in ipairs(getElementsByType("object")) do if isElement(object) and (object:isLowLOD()) then local modelID = object:getModel() engineSetModelLODDistance(modelID, self.lodDistance) end object:setDoubleSided(true) end end function ModelHandlerC:destructor() mainOutput("ModelHandlerC was deleted.") end
gpl-3.0
yetsky/luci
modules/admin-mini/luasrc/controller/mini/index.lua
79
1429
--[[ 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$ ]]-- module("luci.controller.mini.index", package.seeall) function index() local root = node() if not root.lock then root.target = alias("mini") root.index = true end entry({"about"}, template("about")) local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10) page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.index = true entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10) entry({"mini", "index", "logout"}, call("action_logout"), _("Logout")) end function action_logout() local dsp = require "luci.dispatcher" local sauth = require "luci.sauth" if dsp.context.authsession then sauth.kill(dsp.context.authsession) dsp.context.urltoken.stok = nil end luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url()) luci.http.redirect(luci.dispatcher.build_url()) end
apache-2.0
wgapl/torch7
TensorMath.lua
3
46035
local wrap = require 'cwrap' require 'torchcwrap' local interface = wrap.CInterface.new() local method = wrap.CInterface.new() interface:print([[ #include "TH.h" #include "luaT.h" #include "utils.h" ]]) -- specific to torch: we generate a 'dispatch' function -- first we create a helper function -- note that it let the "torch" table on the stack interface:print([[ static const void* torch_istensortype(lua_State *L, const char *tname) { if(!tname) return NULL; if(!luaT_pushmetatable(L, tname)) return NULL; lua_pushstring(L, "torch"); lua_rawget(L, -2); if(lua_istable(L, -1)) return tname; else { lua_pop(L, 2); return NULL; } return NULL; } ]]) interface:print([[ static int torch_isnonemptytable(lua_State *L, int idx) { int empty; if (!lua_istable(L, idx)) return 0; lua_rawgeti(L, idx, 1); empty = lua_isnil(L, -1); lua_pop(L, 1); return !empty; } ]]) interface.dispatchregistry = {} function interface:wrap(name, ...) -- usual stuff wrap.CInterface.wrap(self, name, ...) -- dispatch function if not interface.dispatchregistry[name] then interface.dispatchregistry[name] = true table.insert(interface.dispatchregistry, {name=name, wrapname=string.format("torch_%s", name)}) interface:print(string.gsub([[ static int torch_NAME(lua_State *L) { int narg = lua_gettop(L); const void *tname; if(narg >= 1 && (tname = torch_istensortype(L, luaT_typename(L, 1)))) /* first argument is tensor? */ { } else if(narg >= 2 && (tname = torch_istensortype(L, luaT_typename(L, 2)))) /* second? */ { } else if(narg >= 1 && lua_type(L, narg) == LUA_TSTRING && (tname = torch_istensortype(L, lua_tostring(L, narg)))) /* do we have a valid tensor type string then? */ { lua_remove(L, -2); } else if(!(tname = torch_istensortype(L, torch_getdefaulttensortype(L)))) luaL_error(L, "internal error: the default tensor type does not seem to be an actual tensor"); lua_pushstring(L, "NAME"); lua_rawget(L, -2); if(lua_isfunction(L, -1)) { lua_insert(L, 1); lua_pop(L, 2); /* the two tables we put on the stack above */ lua_call(L, lua_gettop(L)-1, LUA_MULTRET); } else return luaL_error(L, "%s does not implement the torch.NAME() function", tname); return lua_gettop(L); } ]], 'NAME', name)) end end function interface:dispatchregister(name) local txt = self.txt table.insert(txt, string.format('static const struct luaL_Reg %s [] = {', name)) for _,reg in ipairs(self.dispatchregistry) do table.insert(txt, string.format('{"%s", %s},', reg.name, reg.wrapname)) end table.insert(txt, '{NULL, NULL}') table.insert(txt, '};') table.insert(txt, '') self.dispatchregistry = {} end interface:print('/* WARNING: autogenerated file */') interface:print('') local function wrap(...) local args = {...} -- interface interface:wrap(...) -- method: we override things possibly in method table field for _,x in ipairs(args) do if type(x) == 'table' then -- ok, now we have a list of args for _, arg in ipairs(x) do if arg.method then for k,v in pairs(arg.method) do if v == 'nil' then -- special case, we erase the field arg[k] = nil else arg[k] = v end end end end end end local unpack = unpack or table.unpack method:wrap(unpack(args)) end local reals = {ByteTensor='unsigned char', CharTensor='char', ShortTensor='short', IntTensor='int', LongTensor='long', FloatTensor='float', DoubleTensor='double'} local accreals = {ByteTensor='long', CharTensor='long', ShortTensor='long', IntTensor='long', LongTensor='long', FloatTensor='double', DoubleTensor='double'} for _,Tensor in ipairs({"ByteTensor", "CharTensor", "ShortTensor", "IntTensor", "LongTensor", "FloatTensor", "DoubleTensor"}) do local real = reals[Tensor] local accreal = accreals[Tensor] function interface.luaname2wrapname(self, name) return string.format('torch_%s_%s', Tensor, name) end function method.luaname2wrapname(self, name) return string.format('m_torch_%s_%s', Tensor, name) end local function cname(name) return string.format('TH%s_%s', Tensor, name) end local function lastdim(argn) return function(arg) return string.format("TH%s_nDimension(%s)", Tensor, arg.args[argn]:carg()) end end local function lastdimarray(argn) return function(arg) return string.format("TH%s_nDimension(arg%d_data[0])", Tensor, arg.args[argn].i) end end wrap("zero", cname("zero"), {{name=Tensor, returned=true}}) wrap("fill", cname("fill"), {{name=Tensor, returned=true}, {name=real}}) wrap("zeros", cname("zeros"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name="LongArg"}}) wrap("ones", cname("ones"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name="LongArg"}}) wrap("reshape", cname("reshape"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="LongArg"}}) wrap("gather", cname("gather"), {{name=Tensor, default=true, returned=true, init=function(arg) return table.concat( { arg.__metatable.init(arg), string.format("THLongStorage* %s_size = THLongTensor_newSizeOf(%s);", arg:carg(), arg.args[4]:carg()), string.format("TH%s_resize(%s, %s_size, NULL);", Tensor, arg:carg(), arg:carg()), string.format("THLongStorage_free(%s_size);", arg:carg()) }, '\n') end }, {name=Tensor}, {name="index"}, {name="IndexTensor", noreadadd=true}}) wrap("scatter", cname("scatter"), {{name=Tensor, returned=true}, {name="index"}, {name="IndexTensor", noreadadd=true}, {name=Tensor}}, cname("scatterFill"), {{name=Tensor, returned=true}, {name="index"}, {name="IndexTensor", noreadadd=true}, {name=real}}) wrap("dot", cname("dot"), {{name=Tensor}, {name=Tensor}, {name=accreal, creturned=true}}) wrap("add", cname("add"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}}, cname("cadd"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real, default=1}, {name=Tensor}}) wrap("csub", cname("sub"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}}, cname("csub"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real, default=1}, {name=Tensor}}) wrap("mul", cname("mul"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}}) wrap("div", cname("div"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}}) wrap("clamp", cname("clamp"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}, {name=real}}) wrap("match", cname("match"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor}, {name=Tensor}, {name=real, default=1} }) wrap("cmul", cname("cmul"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=Tensor}}) wrap("cpow", cname("cpow"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=Tensor}}) wrap("cdiv", cname("cdiv"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=Tensor}}) wrap("addcmul", cname("addcmul"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real, default=1}, {name=Tensor}, {name=Tensor}}) wrap("addcdiv", cname("addcdiv"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real, default=1}, {name=Tensor}, {name=Tensor}}) wrap("mv", cname("addmv"), {{name=Tensor, default=true, returned=true, method={default='nil'}, init=function(arg) return table.concat( { arg.__metatable.init(arg), string.format("TH%s_resize1d(%s, %s->size[0]);", Tensor, arg:carg(), arg.args[5]:carg()) }, '\n') end, precall=function(arg) return table.concat( { string.format("TH%s_zero(%s);", Tensor, arg:carg()), arg.__metatable.precall(arg) }, '\n') end, }, {name=real, default=0, invisible=true}, {name=Tensor, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=2}, {name=Tensor, dim=1}} ) wrap("mm", cname("addmm"), {{name=Tensor, default=true, returned=true, method={default='nil'}, init=function(arg) return table.concat( { arg.__metatable.init(arg), string.format("TH%s_resize2d(%s, %s->size[0], %s->size[1]);", Tensor, arg:carg(), arg.args[5]:carg(), arg.args[6]:carg()) }, '\n') end, precall=function(arg) return table.concat( { string.format("TH%s_zero(%s);", Tensor, arg:carg()), arg.__metatable.precall(arg) }, '\n') end, }, {name=real, default=0, invisible=true}, {name=Tensor, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=2}, {name=Tensor, dim=2}} ) wrap("bmm", cname("baddbmm"), {{name=Tensor, default=true, returned=true, method={default='nil'}, init=function(arg) return table.concat( { arg.__metatable.init(arg), string.format("TH%s_resize3d(%s, %s->size[0], %s->size[1], %s->size[2]);", Tensor, arg:carg(), arg.args[5]:carg(), arg.args[5]:carg(), arg.args[6]:carg()) }, '\n') end, precall=function(arg) return table.concat( { string.format("TH%s_zero(%s);", Tensor, arg:carg()), arg.__metatable.precall(arg) }, '\n') end, }, {name=real, default=0, invisible=true}, {name=Tensor, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=3}} ) wrap("ger", cname("addr"), {{name=Tensor, default=true, returned=true, method={default='nil'}, init=function(arg) return table.concat( { arg.__metatable.init(arg), string.format("TH%s_resize2d(%s, %s->size[0], %s->size[0]);", Tensor, arg:carg(), arg.args[5]:carg(), arg.args[6]:carg()) }, '\n') end, precall=function(arg) return table.concat( { string.format("TH%s_zero(%s);", Tensor, arg:carg()), arg.__metatable.precall(arg) }, '\n') end }, {name=real, default=1, invisible=true}, {name=Tensor, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=1}, {name=Tensor, dim=1}} ) for _,f in ipairs({ {name="addmv", dim1=1, dim2=2, dim3=1}, {name="addmm", dim1=2, dim2=2, dim3=2}, {name="addr", dim1=2, dim2=1, dim3=1}, {name="addbmm", dim1=2, dim2=3, dim3=3}, {name="baddbmm", dim1=3, dim2=3, dim3=3}, } ) do interface:wrap(f.name, cname(f.name), {{name=Tensor, default=true, returned=true}, {name=real, default=1}, {name=Tensor, dim=f.dim1}, {name=real, default=1}, {name=Tensor, dim=f.dim2}, {name=Tensor, dim=f.dim3}}) -- there is an ambiguity here, hence the more complicated setup method:wrap(f.name, cname(f.name), {{name=Tensor, returned=true, dim=f.dim1}, {name=real, default=1, invisible=true}, {name=Tensor, default=1, dim=f.dim1}, {name=real, default=1}, {name=Tensor, dim=f.dim2}, {name=Tensor, dim=f.dim3}}, cname(f.name), {{name=Tensor, returned=true, dim=f.dim1}, {name=real}, {name=Tensor, default=1, dim=f.dim1}, {name=real}, {name=Tensor, dim=f.dim2}, {name=Tensor, dim=f.dim3}}) end wrap("numel", cname("numel"), {{name=Tensor}, {name="long", creturned=true}}) for _,name in ipairs({"cumsum", "cumprod"}) do wrap(name, cname(name), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="index", default=1}}) end wrap("sum", cname("sumall"), {{name=Tensor}, {name=accreal, creturned=true}}, cname("sum"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="index"}}) wrap("prod", cname("prodall"), {{name=Tensor}, {name=accreal, creturned=true}}, cname("prod"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="index"}}) for _,name in ipairs({"min", "max"}) do wrap(name, cname(name .. "all"), {{name=Tensor}, {name=real, creturned=true}}, cname(name), {{name=Tensor, default=true, returned=true}, {name="IndexTensor", default=true, returned=true, noreadadd=true}, {name=Tensor}, {name="index"}}) end for _,name in ipairs({"cmin", "cmax"}) do wrap(name, cname(name), {{name=Tensor, default=true, returned=true}, {name=Tensor, method={default=1}}, {name=Tensor}}, cname(name .. "Value"), {{name=Tensor, default=true, returned=true}, {name=Tensor, method={default=1}}, {name=real}}) end wrap("trace", cname("trace"), {{name=Tensor}, {name=accreal, creturned=true}}) wrap("cross", cname("cross"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name=Tensor}, {name="index", default=0}}) wrap("diag", cname("diag"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="long", default=0}}) wrap("eye", cname("eye"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name="long"}, {name="long", default=0}}) wrap("range", cname("range"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=accreal}, {name=accreal}, {name=accreal, default=1}}) wrap("randperm", cname("randperm"), {{name=Tensor, default=true, returned=true, method={default='nil'}, postcall=function(arg) return table.concat( { arg.__metatable.postcall(arg), string.format("TH%s_add(%s, %s, 1);", Tensor, arg:carg(), arg:carg()) }, '\n') end}, {name="Generator", default=true}, {name="long"}}) wrap("sort", cname("sort"), {{name=Tensor, default=true, returned=true}, {name="IndexTensor", default=true, returned=true, noreadadd=true}, {name=Tensor}, {name="index", default=lastdim(3)}, {name="boolean", default=0}}) wrap("kthvalue", cname("kthvalue"), {{name=Tensor, default=true, returned=true}, {name="IndexTensor", default=true, returned=true, noreadadd=true}, {name=Tensor}, {name="index"}, {name="index", default=lastdim(3)}}) wrap("mode", cname("mode"), {{name=Tensor, default=true, returned=true}, {name="IndexTensor", default=true, returned=true, noreadadd=true}, {name=Tensor}, {name="index", default=lastdim(3)}}) wrap("median", cname("median"), {{name=Tensor, default=true, returned=true}, {name="IndexTensor", default=true, returned=true, noreadadd=true}, {name=Tensor}, {name="index", default=lastdim(3)}}) wrap("tril", cname("tril"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="int", default=0}}) wrap("triu", cname("triu"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="int", default=0}}) wrap("cat", cname("cat"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name=Tensor}, {name="index", default=lastdim(2)}}, cname("catArray"), {{name=Tensor, default=true, returned=true}, {name=Tensor .. "Array"}, {name="index", default=lastdimarray(2)}}) if Tensor == 'ByteTensor' then -- we declare this only once interface:print( [[ static long THRandom_random2__(THGenerator *gen, long a, long b) { THArgCheck(b >= a, 2, "upper bound must be larger than lower bound"); return((THRandom_random(gen) % (b+1-a)) + a); } static long THRandom_random1__(THGenerator *gen, long b) { THArgCheck(b > 0, 1, "upper bound must be strictly positive"); return(THRandom_random(gen) % b + 1); } ]]) end interface:print(string.gsub( [[ static void THTensor_random2__(THTensor *self, THGenerator *gen, long a, long b) { THArgCheck(b >= a, 2, "upper bound must be larger than lower bound"); TH_TENSOR_APPLY(real, self, *self_data = ((THRandom_random(gen) % (b+1-a)) + a);) } static void THTensor_random1__(THTensor *self, THGenerator *gen, long b) { THArgCheck(b > 0, 1, "upper bound must be strictly positive"); TH_TENSOR_APPLY(real, self, *self_data = (THRandom_random(gen) % b + 1);) } ]], 'Tensor', Tensor):gsub('real', real)) wrap('random', 'THRandom_random2__', {{name='Generator', default=true}, {name='long'}, {name='long'}, {name='long', creturned=true}}, 'THRandom_random1__', {{name='Generator', default=true}, {name='long'}, {name='long', creturned=true}}, 'THRandom_random', {{name='Generator', default=true}, {name='long', creturned=true}}, cname("random2__"), {{name=Tensor, returned=true}, {name='Generator', default=true}, {name='long'}, {name='long'}}, cname("random1__"), {{name=Tensor, returned=true}, {name='Generator', default=true}, {name='long'}}, cname("random"), {{name=Tensor, returned=true}, {name='Generator', default=true}}) for _,f in ipairs({{name='geometric'}, {name='bernoulli', a=0.5}}) do wrap(f.name, string.format("THRandom_%s", f.name), {{name='Generator', default=true}, {name="double", default=f.a}, {name="double", creturned=true}}, cname(f.name), {{name=Tensor, returned=true}, {name='Generator', default=true}, {name="double", default=f.a}}) end wrap("squeeze", cname("squeeze"), {{name=Tensor, default=true, returned=true, postcall=function(arg) local txt = {} if arg.returned then table.insert(txt, string.format('if(arg%d->nDimension == 1 && arg%d->size[0] == 1)', arg.i, arg.i)) -- number table.insert(txt, string.format('lua_pushnumber(L, (lua_Number)(*TH%s_data(arg%d)));', Tensor, arg.i)) end return table.concat(txt, '\n') end}, {name=Tensor}}, cname("squeeze1d"), {{name=Tensor, default=true, returned=true, postcall= function(arg) local txt = {} if arg.returned then table.insert(txt, string.format('if(!hasdims && arg%d->nDimension == 1 && arg%d->size[0] == 1)', arg.i, arg.i)) -- number table.insert(txt, string.format('lua_pushnumber(L, (lua_Number)(*TH%s_data(arg%d)));}', Tensor, arg.i)) end return table.concat(txt, '\n') end}, {name=Tensor, precall= function(arg) return string.format('{int hasdims = arg%d->nDimension > 1;', arg.i) end}, {name="index"}}) wrap("sign", cname("sign"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}) wrap("conv2", cname("conv2Dmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=2}, {name=Tensor, dim=2}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}}, cname("conv2Dcmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=3}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}}, cname("conv2Dmv"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=4}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}} ) wrap("xcorr2", cname("conv2Dmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=2}, {name=Tensor, dim=2}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}}, cname("conv2Dcmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=3}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}}, cname("conv2Dmv"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=4}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}} ) wrap("conv3", cname("conv3Dmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=3}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}}, cname("conv3Dcmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=4}, {name=Tensor, dim=4}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}}, cname("conv3Dmv"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=4}, {name=Tensor, dim=5}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="C", invisible=true}} ) wrap("xcorr3", cname("conv3Dmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=3}, {name=Tensor, dim=3}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}}, cname("conv3Dcmul"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=4}, {name=Tensor, dim=4}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}}, cname("conv3Dmv"), {{name=Tensor, default=true, returned=true}, {name=real, default=0, invisible=true}, {name=real, default=1, invisible=true}, {name=Tensor, dim=4}, {name=Tensor, dim=5}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name=real, default=1, invisible=true}, {name='charoption', values={'V', 'F'}, default='V'}, {name='charoption', default="X", invisible=true}} ) for _,name in pairs({'lt','gt','le','ge','eq','ne'}) do wrap(name, cname(name .. 'Value'), {{name='ByteTensor',default=true, returned=true}, {name=Tensor}, {name=real}}, cname(name .. 'ValueT'), {{name=Tensor, returned=true}, {name=Tensor}, {name=real}}, cname(name .. 'Tensor'), {{name='ByteTensor',default=true, returned=true}, {name=Tensor}, {name=Tensor}}, cname(name .. 'TensorT'), {{name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}}) end wrap("nonzero", cname("nonzero"), {{name="IndexTensor", default=true, returned=true}, {name=Tensor}}) if Tensor == 'ByteTensor' then -- Logical accumulators only apply to ByteTensor for _,name in ipairs({'all', 'any'}) do wrap(name, cname('logical' .. name), {{name=Tensor}, {name="boolean", creturned=true}}) end end if Tensor == 'IntTensor' then wrap("abs", cname("abs"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}, "abs", {{name=real}, {name=real, creturned=true}}) elseif Tensor == 'LongTensor' then wrap("abs", cname("abs"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}, "labs", {{name=real}, {name=real, creturned=true}}) end if Tensor == 'FloatTensor' or Tensor == 'DoubleTensor' then wrap("mean", cname("meanall"), {{name=Tensor}, {name=accreal, creturned=true}}, cname("mean"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="index"}}) for _,name in ipairs({"var", "std"}) do wrap(name, cname(name .. "all"), {{name=Tensor}, {name=accreal, creturned=true}}, cname(name), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="index"}, {name="boolean", default=false}}) end wrap("histc", cname("histc"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name="long",default=100}, {name="double",default=0}, {name="double",default=0}}) wrap("norm", cname("normall"), {{name=Tensor}, {name=real, default=2}, {name=accreal, creturned=true}}, cname("norm"), {{name=Tensor, default=true, returned=true}, {name=Tensor}, {name=real}, {name="index"}}) wrap("renorm", cname("renorm"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}, {name="index"}, {name=real}}) wrap("dist", cname("dist"), {{name=Tensor}, {name=Tensor}, {name=real, default=2}, {name=accreal, creturned=true}}) wrap("linspace", cname("linspace"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=real}, {name=real}, {name="long", default=100}}) wrap("logspace", cname("logspace"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=real}, {name=real}, {name="long", default=100}}) for _,name in ipairs({"log", "log1p", "exp", "cos", "acos", "cosh", "sin", "asin", "sinh", "tan", "atan", "tanh", "sqrt", "round", "ceil", "floor"}) do --"abs"}) do wrap(name, cname(name), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}, name, {{name=real}, {name=real, creturned=true}}) end wrap("abs", cname("abs"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}, "fabs", {{name=real}, {name=real, creturned=true}}) wrap("neg", cname("neg"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}}) wrap("atan2", cname("atan2"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=Tensor}}, "atan2", {{name=real}, {name=real}, {name=real, creturned=true}} ) wrap("pow", cname("pow"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=Tensor, method={default=1}}, {name=real}}, cname("tpow"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name=real}, {name=Tensor, method={default=1}}}, "pow", {{name=real}, {name=real}, {name=real, creturned=true}}) wrap("rand", cname("rand"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name='Generator', default=true}, {name="LongArg"}}) wrap("randn", cname("randn"), {{name=Tensor, default=true, returned=true, method={default='nil'}}, {name='Generator', default=true}, {name="LongArg"}}) wrap("multinomial", cname("multinomial"), {{name="IndexTensor", default=true, returned=true, method={default='nil'}}, {name='Generator', default=true}, {name=Tensor}, {name="int"}, {name="boolean", default=false}}) for _,f in ipairs({{name='uniform', a=0, b=1}, {name='normal', a=0, b=1}, {name='cauchy', a=0, b=1}, {name='logNormal', a=1, b=2}}) do wrap(f.name, string.format("THRandom_%s", f.name), {{name='Generator', default=true}, {name="double", default=f.a}, {name="double", default=f.b}, {name="double", creturned=true}}, cname(f.name), {{name=Tensor, returned=true}, {name='Generator', default=true}, {name=real, default=f.a}, {name=real, default=f.b}}) end for _,f in ipairs({{name='exponential'}}) do wrap(f.name, string.format("THRandom_%s", f.name), {{name='Generator', default=true}, {name="double", default=f.a}, {name="double", creturned=true}}, cname(f.name), {{name=Tensor, returned=true}, {name='Generator', default=true}, {name=real, default=f.a}}) end for _,name in ipairs({"gesv","gels"}) do interface:wrap(name, cname(name), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}}, cname(name), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name=Tensor}} ) end interface:wrap("trtrs", cname("trtrs"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}, -- uplo {name='charoption', values={'N', 'T'}, default='N'}, -- trans {name='charoption', values={'N', 'U'}, default='N'}}, -- diag cname("trtrs"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}, -- uplo {name='charoption', values={'N', 'T'}, default='N'}, -- trans {name='charoption', values={'N', 'U'}, default='N'}} -- diag ) interface:wrap("symeig", cname("syev"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}, {name='charoption', values={'N', 'V'}, default='N'}, {name='charoption', values={'U', 'L'}, default='U'}}, cname("syev"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name='charoption', values={'N', 'V'}, default='N'}, {name='charoption', values={'U', 'L'}, default='U'}} ) interface:wrap("eig", cname("geev"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}, {name='charoption', values={'N', 'V'}, default='N'}}, cname("geev"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name='charoption', values={'N', 'V'}, default='N'}} ) interface:wrap("svd", cname("gesvd"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}, {name='charoption', values={'A', 'S'}, default='S'}}, cname("gesvd"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name='charoption', values={'A', 'S'}, default='S'}} ) interface:wrap("inverse", cname("getri"), {{name=Tensor, returned=true}, {name=Tensor}}, cname("getri"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}} ) interface:wrap("potrf", cname("potrf"), {{name=Tensor, returned=true}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}}, -- uplo cname("potrf"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}} ) interface:wrap("potrs", cname("potrs"), {{name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}}, -- uplo cname("potrs"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}} ) interface:wrap("potri", cname("potri"), {{name=Tensor, returned=true}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}}, -- uplo cname("potri"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name='charoption', values={'U', 'L'}, default='U'}} -- uplo ) interface:wrap("qr", cname("qr"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}}, cname("qr"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}} ) interface:wrap("geqrf", cname("geqrf"), {{name=Tensor, returned=true}, {name=Tensor, returned=true}, {name=Tensor}}, cname("geqrf"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}} ) interface:wrap("orgqr", cname("orgqr"), {{name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}}, cname("orgqr"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name=Tensor}} ) interface:wrap("ormqr", cname("ormqr"), {{name=Tensor, returned=true}, {name=Tensor}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'L', 'R'}, default='L'}, {name='charoption', values={'N', 'T'}, default='N'}}, cname("ormqr"), {{name=Tensor, default=true, returned=true, invisible=true}, {name=Tensor}, {name=Tensor}, {name=Tensor}, {name='charoption', values={'L', 'R'}, default='L'}, {name='charoption', values={'N', 'T'}, default='N'}} ) end method:register(string.format("m_torch_%sMath__", Tensor)) interface:print(method:tostring()) method:clearhistory() interface:register(string.format("torch_%sMath__", Tensor)) interface:print(string.gsub([[ static void torch_TensorMath_init(lua_State *L) { luaT_pushmetatable(L, "torch.Tensor"); /* register methods */ luaT_setfuncs(L, m_torch_TensorMath__, 0); /* register functions into the "torch" field of the tensor metaclass */ lua_pushstring(L, "torch"); lua_newtable(L); luaT_setfuncs(L, torch_TensorMath__, 0); lua_rawset(L, -3); lua_pop(L, 1); } ]], 'Tensor', Tensor)) end interface:dispatchregister("torch_TensorMath__") interface:print([[ void torch_TensorMath_init(lua_State *L) { torch_ByteTensorMath_init(L); torch_CharTensorMath_init(L); torch_ShortTensorMath_init(L); torch_IntTensorMath_init(L); torch_LongTensorMath_init(L); torch_FloatTensorMath_init(L); torch_DoubleTensorMath_init(L); luaT_setfuncs(L, torch_TensorMath__, 0); } ]]) if arg[1] then interface:tofile(arg[1]) else print(interface:tostring()) end
bsd-3-clause
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AssetsManager.lua
14
3014
-------------------------------- -- @module AssetsManager -- @extend Node -- @parent_module cc -------------------------------- -- -- @function [parent=#AssetsManager] setStoragePath -- @param self -- @param #char storagePath -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] setPackageUrl -- @param self -- @param #char packageUrl -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] checkUpdate -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#AssetsManager] getStoragePath -- @param self -- @return char#char ret (return value: char) -------------------------------- -- -- @function [parent=#AssetsManager] update -- @param self -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- @brief Sets connection time out in seconds -- @function [parent=#AssetsManager] setConnectionTimeout -- @param self -- @param #unsigned int timeout -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] setVersionFileUrl -- @param self -- @param #char versionFileUrl -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] getPackageUrl -- @param self -- @return char#char ret (return value: char) -------------------------------- -- @brief Gets connection time out in secondes -- @function [parent=#AssetsManager] getConnectionTimeout -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- -- @function [parent=#AssetsManager] getVersion -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#AssetsManager] getVersionFileUrl -- @param self -- @return char#char ret (return value: char) -------------------------------- -- -- @function [parent=#AssetsManager] deleteVersion -- @param self -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] create -- @param self -- @param #char packageUrl -- @param #char versionFileUrl -- @param #char storagePath -- @param #function errorCallback -- @param #function progressCallback -- @param #function successCallback -- @return AssetsManager#AssetsManager ret (return value: cc.AssetsManager) -------------------------------- -- -- @function [parent=#AssetsManager] AssetsManager -- @param self -- @return AssetsManager#AssetsManager self (return value: cc.AssetsManager) return nil
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/slider.lua
1
4424
TOOL.Category = "Constraints" TOOL.Name = "#tool.slider.name" TOOL.Command = nil TOOL.ConfigName = nil TOOL.ClientConVar[ "width" ] = "1.5" TOOL.ClientConVar[ "material" ] = "cable/cable" function TOOL:LeftClick( trace ) if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then return end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) if ( iNum > 0 ) then if ( !self:GetEnt(1):IsValid() && !self:GetEnt(2):IsValid() ) then return end if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local width = self:GetClientNumber( "width" ) or 1.5 local material = self:GetClientInfo( "material" ) -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local constraint,rope = constraint.Slider( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, width, material ) undo.Create("Slider") undo.AddEntity( constraint ) if rope then undo.AddEntity( rope ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() self:GetOwner():AddCleanup( "ropeconstraints", constraint ) self:GetOwner():AddCleanup( "ropeconstraints", rope ) -- Clear the objects so we're ready to go again self:ClearObjects() else self:SetStage( iNum+1 ) end return true end function TOOL:RightClick( trace ) local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) local tr = {} tr.start = trace.HitPos tr.endpos = tr.start + (trace.HitNormal * 16384) tr.filter = {} tr.filter[1] = self:GetOwner() if (trace.Entity:IsValid()) then tr.filter[2] = trace.Entity end local tr = util.TraceLine( tr ) if ( !tr.Hit ) then self:ClearObjects() return end -- Don't try to constrain world to world if ( trace.HitWorld && tr.HitWorld ) then self:ClearObjects() return end if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then self:ClearObjects() return end if ( tr.Entity:IsValid() && tr.Entity:IsPlayer() ) then self:ClearObjects() return end local Phys2 = tr.Entity:GetPhysicsObjectNum( tr.PhysicsBone ) self:SetObject( 2, tr.Entity, tr.HitPos, Phys2, tr.PhysicsBone, trace.HitNormal ) if ( CLIENT ) then self:ClearObjects() return true end local width = self:GetClientNumber( "width" ) or 1.5 local material = self:GetClientInfo( "material" ) -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local constraint,rope = constraint.Slider( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, width, material ) undo.Create("Slider") undo.AddEntity( constraint ) if rope then undo.AddEntity( rope ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() self:GetOwner():AddCleanup( "ropeconstraints", constraint ) self:GetOwner():AddCleanup( "ropeconstraints", rope ) -- Clear the objects so we're ready to go again self:ClearObjects() return true end function TOOL:Reload( trace ) if (!trace.Entity:IsValid() || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end local bool = constraint.RemoveConstraints( trace.Entity, "Slider" ) return bool end function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Text = "#tool.slider.name", Description = "#tool.slider.help" } ) CPanel:AddControl( "ComboBox", { Label = "#tool.presets", MenuButton = 1, Folder = "rope", Options = { Default = { slider_width='1', slider_material='cable/rope' } }, CVars = { "slider_width", "slider_material" } }) CPanel:AddControl( "Slider", { Label = "#tool.slider.width", Type = "Float", Command = "slider_width", Min = "0", Max = "10" } ) CPanel:AddControl( "RopeMaterial", { Label = "#tool.slider.material", convar = "slider_material" } ) end
mit
pazos/koreader
frontend/luxl.lua
9
17425
--[[ This code was derived from the pico_xml project which can be found here: http://kd7yhr.org/bushbo/pico_xml.md The original C code, written by: Brian O. Bush Pure Lua Version written by: William A Adams Dramatic Speed Improvements by: Robert G Jakabosky https://github.com/Wiladams/LAPHLibs/blob/master/laphlibs/luxl.lua References http://www.faqs.org/rfcs/rfc3076.html http://www.w3.org/TR/REC-xml/ ]] local ffi = require "ffi" local bit = require "bit" local band = bit.band --[[ Types of characters; 0 is not valid 1 is letters, 2 are digits (including '.') 3 whitespace --]] local char_type = ffi.new("const int[256]", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); -- Internal states that the parser can be in at any given time. local ST_START = 0; -- starting base state; default state local ST_TEXT =1; -- text state local ST_START_TAG = 2; -- start tag state local ST_START_TAGNAME =3; -- start tagname state local ST_START_TAGNAME_END =4; -- start tagname ending state local ST_END_TAG =5; -- end tag state local ST_END_TAGNAME=6; -- end tag tagname state local ST_END_TAGNAME_END=7; -- end tag tagname ending local ST_EMPTY_TAG=8; -- empty tag state local ST_SPACE=9; -- linear whitespace state local ST_ATTR_NAME=10; -- attribute name state local ST_ATTR_NAME_END=11; -- attribute name ending state local ST_ATTR_VAL=12; -- attribute value starting state local ST_ATTR_VAL2=13; -- attribute value state local ST_ERROR=14; -- error state -- character classes that we will match against; This could be expanded if -- need be, however, we are aiming for simple. local CCLASS_NONE = 0; -- matches nothing; a base state local CCLASS_LEFT_ANGLE=1; -- matches start tag '<' local CCLASS_SLASH=2; -- matches forward slash local CCLASS_RIGHT_ANGLE=3; -- matches end tag '>' local CCLASS_EQUALS=4; -- matches equals sign local CCLASS_QUOTE=5; -- matches double-quotes local CCLASS_LETTERS=6; -- matches a-zA-Z letters and digits 0-9 local CCLASS_SPACE=7; -- matches whitespace local CCLASS_ANY=8; -- matches any ASCII character; will match all above classes -- Types of events: start element, end element, text, attr name, attr -- val and start/end document. Other events can be ignored! local EVENT_START = 0; -- Start tag local EVENT_END = 1; -- End tag local EVENT_TEXT = 2; -- Text local EVENT_ATTR_NAME = 3; -- Attribute name local EVENT_ATTR_VAL = 4; -- Attribute value local EVENT_END_DOC = 5; -- End of document local EVENT_MARK = 6; -- Internal only; notes position in buffer local EVENT_NONE = 7; -- Internal only; should never see this event local entity_refs = { ["&lt;"] = '<', ["&gt;"] = '>', ["&amp;"] = '&', ["&apos;"] = '\'', ["&quot;"] = '"', } -- Map constant values to constant names. local STATE_NAMES = { [ST_START] = "ST_START", [ST_TEXT] = "ST_TEXT", [ST_START_TAG] = "ST_START_TAG", [ST_START_TAGNAME] = "ST_START_TAGNAME", [ST_START_TAGNAME_END] = "ST_START_TAGNAME_END", [ST_END_TAG] = "ST_END_TAG", [ST_END_TAGNAME] = "ST_END_TAGNAME", [ST_END_TAGNAME_END] = "ST_END_TAGNAME_END", [ST_EMPTY_TAG] = "ST_EMPTY_TAG", [ST_SPACE] = "ST_SPACE", [ST_ATTR_NAME] = "ST_ATTR_NAME", [ST_ATTR_NAME_END] = "ST_ATTR_NAME_END", [ST_ATTR_VAL] = "ST_ATTR_VAL", [ST_ATTR_VAL2] = "ST_ATTR_VAL2", [ST_ERROR] = "ST_ERROR", } --[[ State transition table element; contains: (1) current state, (2) clazz that must match, (3) next state if we match, and (4) event that is emitted upon match. --]] -- Note: States must be grouped in match order AND grouped together! local LEXER_STATES = { -- [0-2] starting state, which also serves as the default state in case of error { state = ST_START, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_START, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_NONE }, { state = ST_START, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_MARK }, -- [3-5] space state handles linear white space { state = ST_SPACE, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_SPACE, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_TEXT }, { state = ST_SPACE, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_MARK }, -- [6-8] handle start tag { state = ST_START_TAG, cclass = CCLASS_LETTERS, next_state = ST_START_TAGNAME, event = EVENT_MARK }, { state = ST_START_TAG, cclass = CCLASS_SLASH, next_state = ST_END_TAG, event = EVENT_MARK }, { state = ST_START_TAG, cclass = CCLASS_SPACE, next_state = ST_START_TAG, event = EVENT_NONE }, -- < tag > -- [9-12] handle start tag name { state = ST_START_TAGNAME, cclass = CCLASS_LETTERS, next_state = ST_START_TAGNAME, event = EVENT_NONE }, { state = ST_START_TAGNAME, cclass = CCLASS_SPACE, next_state = ST_START_TAGNAME_END, event = EVENT_START }, { state = ST_START_TAGNAME, cclass = CCLASS_SLASH, next_state = ST_EMPTY_TAG, event = EVENT_END }, { state = ST_START_TAGNAME, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_START }, -- [13-16] handle start tag name end { state = ST_START_TAGNAME_END, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_START_TAGNAME_END, cclass = CCLASS_SPACE, next_state = ST_START_TAGNAME_END, event = EVENT_NONE }, { state = ST_START_TAGNAME_END, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_START }, { state = ST_START_TAGNAME_END, cclass = CCLASS_SLASH, next_state = ST_EMPTY_TAG, event = EVENT_MARK }, -- Empty tag <br /> -- [17] handle empty tags, e.g., <br /> { state = ST_EMPTY_TAG, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_END }, -- Empty tag <br /> -- [18] handle end tag, e.g., <tag /> { state = ST_END_TAG, cclass = CCLASS_LETTERS, next_state = ST_END_TAGNAME, event = EVENT_NONE }, -- [19-21] handle end tag name { state = ST_END_TAGNAME, cclass = CCLASS_LETTERS, next_state = ST_END_TAGNAME, event = EVENT_NONE }, { state = ST_END_TAGNAME, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_END }, { state = ST_END_TAGNAME, cclass = CCLASS_SPACE, next_state = ST_END_TAGNAME_END, event = EVENT_END }, -- space after end tag name </br > -- [22-23] handle ending of end tag name { state = ST_END_TAGNAME_END, cclass = CCLASS_SPACE, next_state = ST_END_TAGNAME_END, event = EVENT_NONE }, { state = ST_END_TAGNAME_END, cclass = CCLASS_RIGHT_ANGLE,next_state = ST_START, event = EVENT_NONE }, -- [24-26] handle text { state = ST_TEXT, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_TEXT, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_TEXT }, { state = ST_TEXT, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_NONE }, -- [27-29] handle attribute names { state = ST_ATTR_NAME, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_ATTR_NAME, cclass = CCLASS_SPACE, next_state = ST_ATTR_NAME_END, event = EVENT_ATTR_NAME }, -- space before '=' sign { state = ST_ATTR_NAME, cclass = CCLASS_EQUALS, next_state = ST_ATTR_VAL, event = EVENT_ATTR_NAME }, -- <tag attr ="2"> -- [30-32] attribute name end { state = ST_ATTR_NAME_END, cclass = CCLASS_SPACE, next_state = ST_ATTR_NAME_END, event = EVENT_NONE }, { state = ST_ATTR_NAME_END, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_ATTR_NAME_END, cclass = CCLASS_EQUALS, next_state = ST_ATTR_VAL, event = EVENT_NONE }, -- [33-34] handle attribute values, initial quote and spaces { state = ST_ATTR_VAL, cclass = CCLASS_QUOTE, next_state = ST_ATTR_VAL2, event = EVENT_NONE }, { state = ST_ATTR_VAL, cclass = CCLASS_SPACE, next_state = ST_ATTR_VAL, event = EVENT_NONE }, -- initial spaces before quoted attribute value -- [35-37] handle actual attribute values { state = ST_ATTR_VAL2, cclass = CCLASS_QUOTE, next_state = ST_START_TAGNAME_END, event = EVENT_ATTR_VAL }, { state = ST_ATTR_VAL2, cclass = CCLASS_LETTERS, next_state = ST_ATTR_VAL2, event = EVENT_MARK }, { state = ST_ATTR_VAL2, cclass = CCLASS_SLASH, next_state = ST_ATTR_VAL2, event = EVENT_MARK }, -- [38] End of table marker { state = ST_ERROR, cclass = CCLASS_NONE, next_state = ST_ERROR, event = EVENT_NONE } }; ffi.cdef[[ struct parse_state { const char* buf; /* reference to buffer */ int bufsz; /* size of buf */ int mark; int i; int ix; /* index into buffer */ }; ]] local cclass_match = { [CCLASS_LETTERS] = "(ctype == 1 or ctype == 2)", [CCLASS_LEFT_ANGLE] = "(c == T_LT)", [CCLASS_SLASH] = "(c == T_SLASH)", [CCLASS_RIGHT_ANGLE] = "(c == T_GT)", [CCLASS_EQUALS] = "(c == T_EQ)", [CCLASS_QUOTE] = "(c == T_QUOTE)", [CCLASS_SPACE] = "(ctype == 3)", [CCLASS_ANY] = "true", } local STATES = {} local STATE_FUNCS = {} local function next_char(ps, state, verbose) local i = ps.ix if i >= ps.bufsz then return EVENT_END_DOC, 0, i, state end ps.i = i local c = band(ps.buf[i], 0xff); ps.ix = i + 1 if verbose then verbose(i, STATE_FUNCS[state], c) end -- run state function to find next state. return state(ps, c, verbose) end local fsm_code = '' local function code(...) for i=1,select("#", ...) do fsm_code = fsm_code .. tostring(select(i, ...)) end end code[[ local STATES, next_char, char_type = ... local T_LT = string.byte('<') local T_SLASH = string.byte('/') local T_GT = string.byte('>') local T_EQ = string.byte('=') local T_QUOTE = string.byte('"') ]] -- pre-define locals for state functions. for i=0,#STATE_NAMES do local name = STATE_NAMES[i] code('local ', name, '_f\n') end -- group LEXER states. for i=1,#LEXER_STATES do local p_state = LEXER_STATES[i] local state = STATES[p_state.state] local cclasses if not state then cclasses = {} state = { state = p_state.state, cclasses = cclasses } STATES[p_state.state] = state else cclasses = state.cclasses end cclasses[#cclasses + 1] = p_state end local function gen_cclass_code(prefix, cclass) local next_state = STATE_NAMES[cclass.next_state] if cclass.event == EVENT_MARK then code(prefix, "if(ps.mark == 0) then ps.mark = ps.i end -- mark the position\n") elseif cclass.event ~= EVENT_NONE then code(prefix, "if(ps.mark > 0) then\n") code(prefix,' return ', cclass.event,', ',next_state,'_f\n') code(prefix, "end\n") end code(prefix,'return next_char(ps, ', next_state,'_f, verbose)\n') end -- generate state functions. for i=0,#STATE_NAMES do local name = STATE_NAMES[i] local state = STATES[i] local cclasses = state.cclasses code('function ', name, '_f(ps, c, verbose)\n') code(' local ctype = char_type[c]\n') local has_any for i=1,#cclasses do local cclass = cclasses[i] local id = cclass.cclass local condition = cclass_match[id] if id == CCLASS_ANY then has_any = cclass elseif i == 1 then code(' if ', condition, ' then\n') gen_cclass_code(' ', cclass) else code(' elseif ', condition, ' then\n') gen_cclass_code(' ', cclass) end end code(' end\n') -- catch-all for cclass_any or goto error state. if has_any then gen_cclass_code(' ', has_any) else -- exit from FSM on error. code(' return nil, ',name,'_f, c\n') end code('end\n') -- map state id to state function code('STATES[', i, '] = ', name, '_f\n') -- reverse map state function to state id code('STATES[', name, '_f] = ', i, '\n') end -- Compile FSM code local state_funcs = assert(loadstring(fsm_code, "luxl FSM code")) state_funcs(STATE_FUNCS, next_char, char_type) fsm_code = nil local luxl = { EVENT_START = EVENT_START; -- Start tag EVENT_END = EVENT_END; -- End tag EVENT_TEXT = EVENT_TEXT; -- Text EVENT_ATTR_NAME = EVENT_ATTR_NAME; -- Attribute name EVENT_ATTR_VAL = EVENT_ATTR_VAL; -- Attribute value EVENT_END_DOC = EVENT_END_DOC; -- End of document EVENT_MARK = EVENT_MARK; -- Internal only; notes position in buffer EVENT_NONE = EVENT_NONE; -- Internal only; should never see this event } local luxl_mt = { __index = luxl } function luxl.new(buffer, bufflen) local newone = { buf = ffi.cast("const uint8_t *", buffer); -- pointer to "uint8_t *" buffer (0 based) bufsz = bufflen; -- size of input buffer state = ST_START; -- current state event = EVENT_NONE; -- current event err = 0; -- number of errors thus far markix = 0; -- offset of current item of interest marksz = 0; -- size of current item of interest MsgHandler = nil; -- Routine to handle messages ErrHandler = nil; -- Routine to call when there's an error EventHandler = nil; ps = ffi.new('struct parse_state', { buf = buffer, bufsz = bufflen, mark = 0, i = 0, ix = 0, }), } setmetatable(newone, luxl_mt); return newone; end function luxl:Reset(buffer, bufflen) self.buf = buffer -- pointer to "uint8_t *" buffer (0 based) self.bufsz = bufflen -- size of input buffer self.state = ST_START -- current state self.event = EVENT_NONE -- current event self.err = 0 -- number of errors thus far self.markix = 0 -- offset of current item of interest self.marksz = 0 -- size of current item of interest local ps = self.ps ps.buf = buffer ps.bufsz = bufflen ps.mark = 0 ps.i = 0 ps.ix = 0 end function luxl:SetMessageHandler(handler) self.MsgHandler = handler; end --[[ GetNext is responsible for moving through the stream of characters. At the moment, it's fairly naive in terms of character encodings. In a more robust implementation, luxl will read from a stream, which knows about the specific encoding, and will hand out code points based on that particular encoding. So, only straight ASCII for the moment. Returns event type, starting offset, size --]] function luxl:GetNext() local event, state_f, c local ps = self.ps ps.mark = 0 state_f = STATE_FUNCS[self.state] repeat event, state_f, c = next_char(ps, state_f, self.MsgHandler) -- update state id. self.state = STATE_FUNCS[state_f] if not event then -- handle error -- default to start state self.err = self.err + 1; if self.ErrHandler then self.ErrHandler(ps.i, self.state, c); end end until event -- basically we are guaranteed never to have an event of -- type EVENT_MARK or EVENT_NONE here. self.event = event local markix = ps.mark local marksz = ps.i-ps.mark self.markix = markix self.marksz = marksz if(self.EventHandler) then self.EventHandler(event, markix, marksz) end return event, markix, marksz end function luxl:Lexemes() return function() local event, offset, size = self:GetNext(); if(event == EVENT_END_DOC) then return nil; else return event, offset, size; end end end return luxl
agpl-3.0
kurybr/kury.settings
awesome-config/lain/widget/alsa.lua
4
1481
--[[ Licensed under GNU General Public License v2 * (c) 2013, Luca CPZ * (c) 2010, Adrian C. <anrxc@sysphere.org> --]] local helpers = require("lain.helpers") local shell = require("awful.util").shell local wibox = require("wibox") local string = string -- ALSA volume -- lain.widget.alsa local function factory(args) local alsa = { widget = wibox.widget.textbox() } local args = args or {} local timeout = args.timeout or 5 local settings = args.settings or function() end alsa.cmd = args.cmd or "amixer" alsa.channel = args.channel or "Master" alsa.togglechannel = args.togglechannel local format_cmd = string.format("%s get %s", alsa.cmd, alsa.channel) if alsa.togglechannel then format_cmd = { shell, "-c", string.format("%s get %s; %s get %s", alsa.cmd, alsa.channel, alsa.cmd, alsa.togglechannel) } end alsa.last = {} function alsa.update() helpers.async(format_cmd, function(mixer) local l,s = string.match(mixer, "([%d]+)%%.*%[([%l]*)") if alsa.last.level ~= l or alsa.last.status ~= s then volume_now = { level = l, status = s } widget = alsa.widget settings() alsa.last = volume_now end end) end helpers.newtimer(string.format("alsa-%s-%s", alsa.cmd, alsa.channel), timeout, alsa.update) return alsa end return factory
mit
breakds/corpus-accu
cnn-sentence/nearest.lua
1
2959
require 'torch' require 'nn' require 'os' ---------- Command Line Options ---------- local cmd = torch.CmdLine() cmd:option('-dictionary', '/home/breakds/tmp/bilibili/input/word_vecs.bin', 'path to the word2vec binary dictionary.') cmd:option('-model', '', 'Specifies the folder where trained model resides.') cmd:option('-template', '', 'Specifies the path to the file that contains predefined templates.') cmd:option('-input', '', 'Path to the input file') cmd:option('-sentence_size', 20, 'Max allowed length of sentences.') local arguments = cmd:parse(arg) function LoadData(DataSet, dictionary, model, path) local options = {} options.sentence_size = arguments.sentence_size options.dictionary = dictionary local input = DataSet.Load(path, options) local data = {} data.feature = {} data.text = {} local input_file = assert(torch.DiskFile(path, 'r')) for i = 1, input:size(1) do local input_vector = torch.Tensor(arguments.sentence_size, dictionary.dimension) for j = 1, arguments.sentence_size do if 0 < input[i][j] then input_vector[j] = dictionary.vectors[input[i][j]] else input_vector[j]:fill(0) end end local feature = model.encoder:forward(input_vector) -- Normalization feature = feature / torch.sqrt(torch.dot(feature, feature)) local text = input_file:readString('*l') table.insert(data.feature, feature) table.insert(data.text, text) end input_file:close() function data:size() return #self.feature end return data end function Testing() local Dictionary = require 'DataHandler.Dictionary' local DataSet = require 'DataHandler.DataSet' local SimpleCNN = require 'Model.SimpleCNN' assert(arguments.dictionary) assert(arguments.model) assert(arguments.input) assert(arguments.template) -- Load Dictionary local dictionary = Dictionary(arguments.dictionary) -- Load Model local model = SimpleCNN {load_path = arguments.model} -- Load Templates and Inputs local template = LoadData(DataSet, dictionary, model, arguments.template) local input = LoadData(DataSet, dictionary, model, arguments.input) for i = 1, input:size() do local distances = torch.Tensor(template:size()) for j = 1, template:size() do distances[j] = torch.dot(input.feature[i], template.feature[j]) end new_distances, sorted_indices = torch.sort(distances, 1, true) -- Output print('--------------------------------------------------') print(input.text[i]) for j = 1, template:size() do print(string.format('%.5f %s', distances[sorted_indices[j]], template.text[sorted_indices[j]])) end print('') end end Testing()
mit
mahdikord/mahdiho
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
mjarco/sysdig
userspace/sysdig/chisels/v_io_by_type.lua
8
2486
--[[ Copyright (C) 2013-2015 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] view_info = { id = "io_by_type", name = "I/O by Type", description = "Show an overview of the I/O volume based on I/O type. Possible I/O types are: file, directory, ipv4 or ipv6 network traffic, pipe, unix socket, signal fd, event fd, inotify fd.", tips = {"This view is a good starting point to understand what a machine is doing besides CPU computation. Remeber that you can apply it to a process or to a container as well, to get an overview of what they are doing."}, tags = {"Default"}, view_type = "table", applies_to = {"", "container.id", "proc.pid", "proc.name", "thread.tid", "fd.sport", "evt.res"}, use_defaults = true, drilldown_target = "procs", columns = { { name = "NA", field = "fd.type", is_key = true }, { name = "BPS IN", field = "evt.buflen.in", description = "Bytes per second read from the FDs of the specific type.", colsize = 12, aggregation = "TIME_AVG" }, { name = "BPS OUT", field = "evt.buflen.out", description = "Bytes per second written to the FDs of the specific type.", colsize = 12, aggregation = "TIME_AVG" }, { is_sorting = true, name = "IOPS", field = "evt.count", description = "Number of I/O operations for the specified I/O category. This counts all the operations on the file, including, open, close, read, write, stat, and so on. As a consequence, this value can be nonzero even if I/O bytes for the file are zero.", colsize = 9, aggregation = "TIME_AVG" }, { name = "TIME", field = "evt.latency", description = "Time spent by processes doing any I/O operation (including wait) of this type.", colsize = 9, aggregation = "SUM" }, { name = "I/O Type", field = "fd.type", description = "Type of I/O. Can be one of: file, directory, ipv4, ipv6, pipe, unix, signal, event, inotify", aggregation = "SUM", colsize = 0 }, } }
gpl-2.0
yetsky/luci
modules/base/luasrc/http/protocol.lua
55
18445
--[[ HTTP protocol implementation for LuCI (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$ ]]-- --- LuCI http protocol class. -- This class contains several functions useful for http message- and content -- decoding and to retrive form data from raw http messages. module("luci.http.protocol", package.seeall) local ltn12 = require("luci.ltn12") HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size --- Decode an urlencoded string - optionally without decoding -- the "+" sign to " " - and return the decoded string. -- @param str Input string in x-www-urlencoded format -- @param no_plus Don't decode "+" signs to spaces -- @return The decoded string -- @see urlencode function urldecode( str, no_plus ) local function __chrdec( hex ) return string.char( tonumber( hex, 16 ) ) end if type(str) == "string" then if not no_plus then str = str:gsub( "+", " " ) end str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec ) end return str end --- Extract and split urlencoded data pairs, separated bei either "&" or ";" -- from given url or string. Returns a table with urldecoded values. -- Simple parameters are stored as string values associated with the parameter -- name within the table. Parameters with multiple values are stored as array -- containing the corresponding values. -- @param url The url or string which contains x-www-urlencoded form data -- @param tbl Use the given table for storing values (optional) -- @return Table containing the urldecoded parameters -- @see urlencode_params function urldecode_params( url, tbl ) local params = tbl or { } if url:find("?") then url = url:gsub( "^.+%?([^?]+)", "%1" ) end for pair in url:gmatch( "[^&;]+" ) do -- find key and value local key = urldecode( pair:match("^([^=]+)") ) local val = urldecode( pair:match("^[^=]+=(.+)$") ) -- store if type(key) == "string" and key:len() > 0 then if type(val) ~= "string" then val = "" end if not params[key] then params[key] = val elseif type(params[key]) ~= "table" then params[key] = { params[key], val } else table.insert( params[key], val ) end end end return params end --- Encode given string to x-www-urlencoded format. -- @param str String to encode -- @return String containing the encoded data -- @see urldecode function urlencode( str ) local function __chrenc( chr ) return string.format( "%%%02x", string.byte( chr ) ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%+!*'(),])", __chrenc ) end return str end --- Encode each key-value-pair in given table to x-www-urlencoded format, -- separated by "&". Tables are encoded as parameters with multiple values by -- repeating the parameter name with each value. -- @param tbl Table with the values -- @return String containing encoded values -- @see urldecode_params function urlencode_params( tbl ) local enc = "" for k, v in pairs(tbl) do if type(v) == "table" then for i, v2 in ipairs(v) do enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v2) end else enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v) end end return enc end -- (Internal function) -- Initialize given parameter and coerce string into table when the parameter -- already exists. -- @param tbl Table where parameter should be created -- @param key Parameter name -- @return Always nil local function __initval( tbl, key ) if tbl[key] == nil then tbl[key] = "" elseif type(tbl[key]) == "string" then tbl[key] = { tbl[key], "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Append given data to given parameter, either by extending the string value -- or by appending it to the last string in the parameter's value table. -- @param tbl Table containing the previously initialized parameter value -- @param key Parameter name -- @param chunk String containing the data to append -- @return Always nil -- @see __initval local function __appendval( tbl, key, chunk ) if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk else tbl[key] = tbl[key] .. chunk end end -- (Internal function) -- Finish the value of given parameter, either by transforming the string value -- or - in the case of multi value parameters - the last element in the -- associated values table. -- @param tbl Table containing the previously initialized parameter value -- @param key Parameter name -- @param handler Function which transforms the parameter value -- @return Always nil -- @see __initval -- @see __appendval local function __finishval( tbl, key, handler ) if handler then if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] ) else tbl[key] = handler( tbl[key] ) end end end -- Table of our process states local process_states = { } -- Extract "magic", the first line of a http message. -- Extracts the message type ("get", "post" or "response"), the requested uri -- or the status code if the line descripes a http response. process_states['magic'] = function( msg, chunk, err ) if chunk ~= nil then -- ignore empty lines before request if #chunk == 0 then return true, nil end -- Is it a request? local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$") -- Yup, it is if method then msg.type = "request" msg.request_method = method:lower() msg.request_uri = uri msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end -- Is it a response? else local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$") -- Is a response if code then msg.type = "response" msg.status_code = code msg.status_message = message msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end end end end -- Can't handle it return nil, "Invalid HTTP message magic" end -- Extract headers from given string. process_states['headers'] = function( msg, chunk ) if chunk ~= nil then -- Look for a valid header format local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" ) if type(hdr) == "string" and hdr:len() > 0 and type(val) == "string" and val:len() > 0 then msg.headers[hdr] = val -- Valid header line, proceed return true, nil elseif #chunk == 0 then -- Empty line, we won't accept data anymore return false, nil else -- Junk data return nil, "Invalid HTTP header received" end else return nil, "Unexpected EOF" end end --- Creates a ltn12 source from the given socket. The source will return it's -- data line by line with the trailing \r\n stripped of. -- @param sock Readable network socket -- @return Ltn12 source function function header_source( sock ) return ltn12.source.simplify( function() local chunk, err, part = sock:receive("*l") -- Line too long if chunk == nil then if err ~= "timeout" then return nil, part and "Line exceeds maximum allowed length" or "Unexpected EOF" else return nil, err end -- Line ok elseif chunk ~= nil then -- Strip trailing CR chunk = chunk:gsub("\r$","") return chunk, nil end end ) end --- Decode a mime encoded http message body with multipart/form-data -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- If an optional file callback function is given then it is feeded with the -- file contents chunk by chunk and only the extracted file name is stored -- within the params table. The callback function will be called subsequently -- with three arguments: -- o Table containing decoded (name, file) and raw (headers) mime header data -- o String value containing a chunk of the file data -- o Boolean which indicates wheather the current chunk is the last one (eof) -- @param src Ltn12 source function -- @param msg HTTP message object -- @param filecb File callback function (optional) -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function mimedecode_message_body( src, msg, filecb ) if msg and msg.env.CONTENT_TYPE then msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$") end if not msg.mime_boundary then return nil, "Invalid Content-Type found" end local tlen = 0 local inhdr = false local field = nil local store = nil local lchunk = nil local function parse_headers( chunk, field ) local stat repeat chunk, stat = chunk:gsub( "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n", function(k,v) field.headers[k] = v return "" end ) until stat == 0 chunk, stat = chunk:gsub("^\r\n","") -- End of headers if stat > 0 then if field.headers["Content-Disposition"] then if field.headers["Content-Disposition"]:match("^form%-data; ") then field.name = field.headers["Content-Disposition"]:match('name="(.-)"') field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$') end end if not field.headers["Content-Type"] then field.headers["Content-Type"] = "text/plain" end if field.name and field.file and filecb then __initval( msg.params, field.name ) __appendval( msg.params, field.name, field.file ) store = filecb elseif field.name then __initval( msg.params, field.name ) store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end else store = nil end return chunk, true end return chunk, false end local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" end if chunk and not lchunk then lchunk = "\r\n" .. chunk elseif lchunk then local data = lchunk .. ( chunk or "" ) local spos, epos, found repeat spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true ) if not spos then spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true ) end if spos then local predata = data:sub( 1, spos - 1 ) if inhdr then predata, eof = parse_headers( predata, field ) if not eof then return nil, "Invalid MIME section header" elseif not field.name then return nil, "Invalid Content-Disposition header" end end if store then store( field, predata, true ) end field = { headers = { } } found = found or true data, eof = parse_headers( data:sub( epos + 1, #data ), field ) inhdr = not eof end until not spos if found then -- We found at least some boundary. Save -- the unparsed remaining data for the -- next chunk. lchunk, data = data, nil else -- There was a complete chunk without a boundary. Parse it as headers or -- append it as data, depending on our current state. if inhdr then lchunk, eof = parse_headers( data, field ) inhdr = not eof else -- We're inside data, so append the data. Note that we only append -- lchunk, not all of data, since there is a chance that chunk -- contains half a boundary. Assuming that each chunk is at least the -- boundary in size, this should prevent problems store( field, lchunk, false ) lchunk, chunk = chunk, nil end end end return true end return ltn12.pump.all( src, snk ) end --- Decode an urlencoded http message body with application/x-www-urlencoded -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- @param src Ltn12 source function -- @param msg HTTP message object -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function urldecode_message_body( src, msg ) local tlen = 0 local lchunk = nil local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" elseif tlen > HTTP_MAX_CONTENT then return nil, "Message body size exceeds maximum allowed length" end if not lchunk and chunk then lchunk = chunk elseif lchunk then local data = lchunk .. ( chunk or "&" ) local spos, epos repeat spos, epos = data:find("^.-[;&]") if spos then local pair = data:sub( spos, epos - 1 ) local key = pair:match("^(.-)=") local val = pair:match("=([^%s]*)%s*$") if key and #key > 0 then __initval( msg.params, key ) __appendval( msg.params, key, val ) __finishval( msg.params, key, urldecode ) end data = data:sub( epos + 1, #data ) end until not spos lchunk = data end return true end return ltn12.pump.all( src, snk ) end --- Try to extract an http message header including information like protocol -- version, message headers and resulting CGI environment variables from the -- given ltn12 source. -- @param src Ltn12 source function -- @return HTTP message object -- @see parse_message_body function parse_message_header( src ) local ok = true local msg = { } local sink = ltn12.sink.simplify( function( chunk ) return process_states['magic']( msg, chunk ) end ) -- Pump input data... while ok do -- get data ok, err = ltn12.pump.step( src, sink ) -- error if not ok and err then return nil, err -- eof elseif not ok then -- Process get parameters if ( msg.request_method == "get" or msg.request_method == "post" ) and msg.request_uri:match("?") then msg.params = urldecode_params( msg.request_uri ) else msg.params = { } end -- Populate common environment variables msg.env = { CONTENT_LENGTH = msg.headers['Content-Length']; CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type']; REQUEST_METHOD = msg.request_method:upper(); REQUEST_URI = msg.request_uri; SCRIPT_NAME = msg.request_uri:gsub("?.+$",""); SCRIPT_FILENAME = ""; -- XXX implement me SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version); QUERY_STRING = msg.request_uri:match("?") and msg.request_uri:gsub("^.+?","") or "" } -- Populate HTTP_* environment variables for i, hdr in ipairs( { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Cookie', 'Host', 'Referer', 'User-Agent', } ) do local var = 'HTTP_' .. hdr:upper():gsub("%-","_") local val = msg.headers[hdr] msg.env[var] = val end end end return msg end --- Try to extract and decode a http message body from the given ltn12 source. -- This function will examine the Content-Type within the given message object -- to select the appropriate content decoder. -- Currently the application/x-www-urlencoded and application/form-data -- mime types are supported. If the encountered content encoding can't be -- handled then the whole message body will be stored unaltered as "content" -- property within the given message object. -- @param src Ltn12 source function -- @param msg HTTP message object -- @param filecb File data callback (optional, see mimedecode_message_body()) -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function parse_message_body( src, msg, filecb ) -- Is it multipart/mime ? if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^multipart/form%-data") then return mimedecode_message_body( src, msg, filecb ) -- Is it application/x-www-form-urlencoded ? elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded") then return urldecode_message_body( src, msg, filecb ) -- Unhandled encoding -- If a file callback is given then feed it chunk by chunk, else -- store whole buffer in message.content else local sink -- If we have a file callback then feed it if type(filecb) == "function" then sink = filecb -- ... else append to .content else msg.content = "" msg.content_length = 0 sink = function( chunk, err ) if chunk then if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then msg.content = msg.content .. chunk msg.content_length = msg.content_length + #chunk return true else return nil, "POST data exceeds maximum allowed length" end end return true end end -- Pump data... while true do local ok, err = ltn12.pump.step( src, sink ) if not ok and err then return nil, err elseif not err then return true end end return true end end --- Table containing human readable messages for several http status codes. -- @class table statusmsg = { [200] = "OK", [206] = "Partial Content", [301] = "Moved Permanently", [302] = "Found", [304] = "Not Modified", [400] = "Bad Request", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [408] = "Request Time-out", [411] = "Length Required", [412] = "Precondition Failed", [416] = "Requested range not satisfiable", [500] = "Internal Server Error", [503] = "Server Unavailable", }
apache-2.0
ZerothAngel/FtDScripts
control/depthcontrol.lua
1
3769
--@ commonstargets commons control drivemaintainer evasion terraincheck sign clamp -- Depth Control module ManualDepthController = DriveMaintainer.new(ManualDepthDriveMaintainerFacing) -- Note: Aside from Offset, all should be absolute altitudes, i.e. -depth DepthControl_Desired = 0 DepthControl_Offset = 0 DepthControl_Min = 0 DepthControl_Max = 0 DepthControl_LastDodge = nil function Depth_Control(I) DepthControl_Offset = 0 DepthControl_Min = -HardMaxDepth DepthControl_Max = -HardMinDepth local DesiredDepth,Absolute if ManualDepthDriveMaintainerFacing and ManualDepthWhen[C:MovementMode()] then -- Manual depth control local ManualDesiredDepth = ManualDepthController:GetThrottle(I) if ManualDesiredDepth > 0 then -- Relative DesiredDepth,Absolute = (500 - ManualDesiredDepth*500),false else -- Absolute DesiredDepth,Absolute = -ManualDesiredDepth*500,true end if ManualEvasion and C:FirstTarget() then DepthControl_Offset = CalculateEvasion(DepthEvasion) end else -- Use configured depths if C:FirstTarget() then DesiredDepth,Absolute = DesiredDepthCombat.Depth,DesiredDepthCombat.Absolute DepthControl_Offset = CalculateEvasion(DepthEvasion) else DesiredDepth,Absolute = DesiredDepthIdle.Depth,DesiredDepthIdle.Absolute end end if Absolute then DesiredDepth = -DesiredDepth else -- Look ahead at terrain local TerrainHeight = GetTerrainHeight(I, C:Velocity(), -500, -TerrainMinDepth) -- Set new absolute minimum DepthControl_Min = math.max(DepthControl_Min, TerrainHeight) -- And offset desired depth (actually desired elevation) by terrain -- And constrain by relative limits DesiredDepth = Clamp(DesiredDepth + TerrainHeight, -TerrainMaxDepth, -TerrainMinDepth) end DepthControl_Desired = DesiredDepth end function Depth_Apply(_, HighPriorityOffset, NoOffset) -- Determine depth based on presence of HighPriorityOffset local NewAltitude if DepthDodgeMode > 0 and HighPriorityOffset then if DepthDodgeMode == 2 then -- Most leeway if DepthControl_LastDodge then -- Try to keep going in the same direction if Sign(HighPriorityOffset) == DepthControl_LastDodge[1] then NewAltitude = C:Altitude() + DepthControl_LastDodge[2] * math.abs(HighPriorityOffset) else -- But reset if the AI changes direction DepthControl_LastDodge = nil end end if not DepthControl_LastDodge then local Above = math.max(0, DepthControl_Max - C:Altitude()) local Below = math.max(0, C:Altitude() - DepthControl_Min) if Below > Above then NewAltitude = C:Altitude() - math.abs(HighPriorityOffset) DepthControl_LastDodge = { Sign(HighPriorityOffset), -1 } else NewAltitude = C:Altitude() + math.abs(HighPriorityOffset) DepthControl_LastDodge = { Sign(HighPriorityOffset), 1 } end end elseif DepthDodgeMode == 3 then -- Always upwards NewAltitude = C:Altitude() + math.abs(HighPriorityOffset) elseif DepthDodgeMode == 4 then -- Always downwards NewAltitude = C:Altitude() - math.abs(HighPriorityOffset) else -- As recommended NewAltitude = C:Altitude() + HighPriorityOffset end else NewAltitude = DepthControl_Desired + (NoOffset and 0 or DepthControl_Offset) DepthControl_LastDodge = nil end -- Constrain and set V.SetAltitude(Clamp(NewAltitude, DepthControl_Min, DepthControl_Max)) end
mit